(function ($) {
  'use strict';

  function t(key, fallback) {
    return (AIIO.i18n && AIIO.i18n[key]) ? AIIO.i18n[key] : (fallback || key);
  }

  function notice(message, type) {
    const cls = type === 'error' ? 'aiio-alert-error' : (type === 'success' ? 'aiio-alert-success' : 'aiio-alert-info');
    $('#aiio-notice').html('<div class="aiio-alert ' + cls + '">' + $('<div>').text(message).html() + '</div>');
  }

  function ajax(action, data) {
    data = data || {};
    data.action = action;
    data.nonce = AIIO.nonce;
    return $.post(AIIO.ajax, data);
  }

  function formatBytes(bytes) {
    bytes = Math.max(0, parseInt(bytes, 10) || 0);
    if (bytes >= 1048576) return (bytes / 1048576).toFixed(2) + ' MB';
    if (bytes >= 1024) return (bytes / 1024).toFixed(1) + ' KB';
    return bytes + ' B';
  }

  let previewId = 0;

  function renderPreview(data) {
    previewId = parseInt(data.attachment_id, 10) || 0;
    let html = '<p><strong>#' + previewId + '</strong> ' + $('<div>').text(data.filename || '').html() + '</p>';
    html += '<div class="aiio-preview-stats">';
    html += stat(t('before', 'Before'), formatBytes(data.before_bytes));
    html += stat(t('after', 'After'), formatBytes(data.after_bytes));
    html += stat(t('saved', 'Saved'), formatBytes(data.saved_bytes) + ' (' + (data.saved_percent || 0) + '%)');
    html += '</div>';

    if (data.webp && data.webp.bytes) {
      let webpLine = t('webpSidecar', 'WebP sidecar preview') + ': ' + formatBytes(data.webp.bytes);
      if (data.webp.quality) {
        webpLine += ' (' + t('quality', 'Quality') + ' ' + data.webp.quality + ')';
      }
      html += '<p class="pewit-muted">' + webpLine + '</p>';
    }
    if (data.avif && data.avif.bytes) {
      html += '<p class="pewit-muted">' + t('avifSidecar', 'AVIF sidecar preview') + ': ' + formatBytes(data.avif.bytes) + '</p>';
    }
    if (data.av1_webm && data.av1_webm.bytes) {
      html += '<p class="pewit-muted">' + t('av1Sidecar', 'AV1 WebM sidecar preview') + ': ' + formatBytes(data.av1_webm.bytes) + '</p>';
    }
    if (data.note) {
      html += '<p class="pewit-muted">' + $('<div>').text(data.note).html() + '</p>';
    }

    if ((data.saved_bytes || 0) <= 0 && data.type !== 'video') {
      html += '<p class="aiio-warn">' + t('noSavings', 'This image may already be well compressed.') + '</p>';
    }

    $('#aiio-preview-body').html(html);
    $('#aiio-preview-panel').prop('hidden', false);
    $('#aiio-apply-preview').prop('disabled', previewId <= 0);
  }

  function stat(label, value) {
    return '<div class="aiio-preview-stat"><span>' + label + '</span><strong>' + value + '</strong></div>';
  }

  function renderImageList(items) {
    if (!items || !items.length) {
      $('#aiio-image-list').html('<p class="pewit-muted">' + t('noResults', 'No heavy images found for the current threshold.') + '</p>');
      return;
    }

    let html = '';
    items.forEach(function (item) {
      html += '<div class="aiio-image-row" data-id="' + item.id + '">';
      html += '<div class="aiio-image-thumb">';
      if (item.thumb) html += '<img src="' + item.thumb + '" alt="" width="48" height="48" loading="lazy" />';
      html += '</div><div class="aiio-image-meta">';
      html += '<strong>' + $('<div>').text(item.filename || ('#' + item.id)).html() + '</strong>';
      html += '<span class="pewit-muted">#' + item.id + ' · ' + (item.media_type || 'image') + ' · ' + (item.size_label || formatBytes(item.bytes)) + '</span>';
      if (item.last_optimized) html += '<span class="pewit-badge pewit-badge-ok">' + t('optimized', 'Optimized') + '</span>';
      if (!item.optimizable && item.skip_reason) html += '<span class="pewit-muted">' + $('<div>').text(item.skip_reason).html() + '</span>';
      html += '</div><div class="aiio-image-actions">';
      if (item.optimizable) {
        html += '<button type="button" class="pewit-btn pewit-btn-secondary aiio-preview-btn" data-id="' + item.id + '">' + t('preview', 'Preview') + '</button>';
      }
      if (AIIO.canAutomate && item.has_backup) {
        html += '<button type="button" class="pewit-btn pewit-btn-secondary aiio-rollback-btn" data-id="' + item.id + '">' + t('rollback', 'Rollback') + '</button>';
      }
      html += '</div></div>';
    });
    $('#aiio-image-list').html(html);
  }

  function updateStats(stats) {
    if (!stats) return;
    $('#aiio-stat-total').text(stats.total_images || 0);
    $('#aiio-stat-over').text(stats.over_threshold || 0);
    $('#aiio-stat-optimizable').text(stats.optimizable || 0);
  }

  function renderJob(job) {
    if (!job || !job.id) {
      $('#aiio-job-panel').html('<p class="pewit-muted">' + t('noJobs', 'No jobs yet. Start one from the Images tab.') + '</p>');
      return;
    }

    const total = parseInt(job.total, 10) || 0;
    const done = (job.processed || []).length + (job.failed || []).length + (job.skipped || []).length;
    const pct = total > 0 ? Math.min(100, Math.round((done / total) * 100)) : 0;

    let html = '<div class="aiio-job-summary">';
    html += '<div><strong>' + t('status', 'Status') + ':</strong> <span id="aiio-job-status">' + (job.status || '') + '</span></div>';
    html += '<div><strong>' + t('progress', 'Progress') + ':</strong> <span id="aiio-job-progress">' + done + ' / ' + total + '</span></div>';
    html += '<div class="aiio-progress"><span id="aiio-job-bar" style="width:' + pct + '%"></span></div></div>';
    html += '<div class="aiio-job-log" id="aiio-job-log">';

    const log = (job.log || []).slice().reverse();
    log.forEach(function (entry) {
      html += '<div class="aiio-log-line aiio-log-' + (entry.level || 'info') + '">';
      html += '<span class="aiio-log-time">' + (entry.time || '') + '</span>';
      html += $('<div>').text(entry.message || '').html();
      html += '</div>';
    });
    html += '</div>';

    $('#aiio-job-panel').html(html);
    $('#aiio-stat-job').text(job.status ? job.status.charAt(0).toUpperCase() + job.status.slice(1) : t('none', 'None'));
  }

  let jobPollTimer = null;

  function pollJob() {
    ajax('aiio_job_status').done(function (res) {
      if (!res || !res.success) return;
      renderJob(res.data.job || {});
      const status = (res.data.job || {}).status;
      if (status === 'running') {
        jobPollTimer = setTimeout(pollJob, 3000);
      } else {
        clearTimeout(jobPollTimer);
      }
    });
  }

  function collectOptimizableIds() {
    const ids = [];
    $('.aiio-image-row').each(function () {
      const id = parseInt($(this).data('id'), 10);
      if (id && $(this).find('.aiio-preview-btn').length) ids.push(id);
    });
    return ids;
  }

  $(function () {
    $(document).on('click', '#aiio-scan-library', function () {
      const $btn = $(this);
      $btn.prop('disabled', true).addClass('aiio-loading');
      notice(t('scanning', 'Scanning media library...'), 'info');
      ajax('aiio_scan').done(function (res) {
        if (!res.success) {
          notice((res.data && res.data.message) || t('scanFailed', 'Scan failed.'), 'error');
          return;
        }
        AIIO.scan = res.data;
        updateStats(res.data.stats);
        renderImageList(res.data.items);
        notice(t('scanDone', 'Scan complete.'), 'success');
      }).fail(function () {
        notice(t('scanFailed', 'Scan failed.'), 'error');
      }).always(function () {
        $btn.prop('disabled', false).removeClass('aiio-loading');
      });
    });

    $(document).on('click', '.aiio-preview-btn', function () {
      const id = parseInt($(this).data('id'), 10);
      if (!id) return;
      notice(t('previewing', 'Generating preview...'), 'info');
      ajax('aiio_preview_optimize', { attachment_id: id }).done(function (res) {
        if (!res.success) {
          notice((res.data && res.data.message) || t('previewFailed', 'Preview failed.'), 'error');
          return;
        }
        renderPreview(res.data);
        notice(t('previewReady', 'Preview ready — review savings before applying.'), 'success');
      }).fail(function () {
        notice(t('previewFailed', 'Preview failed.'), 'error');
      });
    });

    $(document).on('click', '#aiio-apply-preview', function () {
      if (!previewId) return;
      const $btn = $(this);
      $btn.prop('disabled', true);
      const payload = { attachment_id: previewId };
      if (AIIO.canAutomate && AIIO.settings && AIIO.settings.webp_enabled) {
        payload.webp = 1;
      }
      if (AIIO.canAutomate && AIIO.settings && AIIO.settings.avif_enabled) {
        payload.avif = 1;
      }
      ajax('aiio_apply_optimize', payload).done(function (res) {
        if (!res.success) {
          notice((res.data && res.data.message) || t('applyFailed', 'Apply failed.'), 'error');
          $btn.prop('disabled', false);
          return;
        }
        notice(t('applyDone', 'Optimization applied.'), 'success');
        $('#aiio-preview-panel').prop('hidden', true);
        previewId = 0;
        $('#aiio-scan-library').trigger('click');
      }).fail(function () {
        notice(t('applyFailed', 'Apply failed.'), 'error');
        $btn.prop('disabled', false);
      });
    });

    $(document).on('click', '#aiio-dismiss-preview', function () {
      $('#aiio-preview-panel').prop('hidden', true);
      previewId = 0;
    });

    $(document).on('click', '.aiio-rollback-btn', function () {
      const id = parseInt($(this).data('id'), 10);
      if (!id || !window.confirm(t('rollbackConfirm', 'Restore the original file from backup?'))) return;
      ajax('aiio_rollback', { attachment_id: id }).done(function (res) {
        if (!res.success) {
          notice((res.data && res.data.message) || t('rollbackFailed', 'Rollback failed.'), 'error');
          return;
        }
        notice(t('rollbackDone', 'Image restored from backup.'), 'success');
        $('#aiio-scan-library').trigger('click');
      });
    });

    $(document).on('click', '#aiio-bulk-start', function () {
      if (!AIIO.canAutomate) {
        notice(AIIO.i18n.automationLocked, 'error');
        return;
      }
      const ids = collectOptimizableIds();
      if (!ids.length) {
        notice(t('noBulk', 'No optimizable images in the list.'), 'error');
        return;
      }
      if (!window.confirm(t('bulkConfirm', 'Start bulk optimization for ') + ids.length + t('bulkConfirmEnd', ' images?'))) return;

      const payload = { attachment_ids: ids };
      if (AIIO.settings && AIIO.settings.webp_enabled) payload.webp = 1;
      if (AIIO.settings && AIIO.settings.avif_enabled) payload.avif = 1;

      ajax('aiio_start_job', payload).done(function (res) {
        if (!res.success) {
          notice((res.data && res.data.message) || t('jobFailed', 'Could not start job.'), 'error');
          return;
        }
        notice(t('jobStarted', 'Background job started.'), 'success');
        window.location.href = AIIO.jobs_url;
      });
    });

    $(document).on('click', '#aiio-cancel-job', function () {
      ajax('aiio_cancel_job').done(function (res) {
        if (!res.success) {
          notice((res.data && res.data.message) || t('cancelFailed', 'Could not cancel job.'), 'error');
          return;
        }
        renderJob(res.data.job || {});
        notice(t('jobCancelled', 'Job cancelled.'), 'success');
      });
    });

    $(document).on('click', '#aiio-save-settings', function () {
      ajax('aiio_save_settings', {
        jpeg_quality: $('#aiio_jpeg_quality').val(),
        png_compression: $('#aiio_png_compression').val(),
        size_threshold_kb: $('#aiio_size_threshold_kb').val(),
        webp_enabled: $('#aiio_webp_enabled').is(':checked') ? 1 : 0,
        webp_priority: $('#aiio_webp_priority').val(),
        avif_enabled: $('#aiio_avif_enabled').is(':checked') ? 1 : 0,
        avif_quality: $('#aiio_avif_quality').val(),
        video_av1_enabled: $('#aiio_video_av1_enabled').is(':checked') ? 1 : 0,
        video_av1_crf: $('#aiio_video_av1_crf').val(),
        auto_optimize_upload: $('#aiio_auto_optimize_upload').is(':checked') ? 1 : 0,
        notify_email_enabled: $('#aiio_notify_email_enabled').is(':checked') ? 1 : 0,
        notify_email_to: $('#aiio_notify_email_to').val(),
        notify_include_csv: $('#aiio_notify_include_csv').is(':checked') ? 1 : 0,
        only_used_images: $('#aiio_only_used_images').is(':checked') ? 1 : 0,
        exclude_filename_patterns: $('#aiio_exclude_filename_patterns').val(),
        lcp_budget_kb: $('#aiio_lcp_budget_kb').val(),
        only_etch_images: $('#aiio_only_etch_images').is(':checked') ? 1 : 0,
        etch_native_ui: $('#aiio_etch_native_ui').is(':checked') ? 1 : 0
      }).done(function (res) {
        if (!res.success) {
          notice((res.data && res.data.message) || t('saveFailed', 'Could not save settings.'), 'error');
          return;
        }
        AIIO.settings = res.data.settings || AIIO.settings;
        notice(t('saveDone', 'Settings saved.'), 'success');
      });
    });

    if (AIIO.page === 'pewit-ai-image-optimizer-jobs' && AIIO.job && AIIO.job.status === 'running') {
      pollJob();
    }

    $(document).on('click', '#aiio-lcp-scan', function () {
      var $btn = $(this).prop('disabled', true);
      ajax('aiio_lcp_scan', { budget_kb: $('#aiio_lcp_budget_kb').val() || 200 }).done(function (res) {
        if (res.success && res.data) {
          var d = res.data;
          $('#aiio-lcp-summary').text('Budget ' + d.budget_kb + ' KB — ' + d.over_budget + ' over budget.');
          notice(t('scanDone', 'Scan complete.'), 'success');
        }
      }).always(function () { $btn.prop('disabled', false); });
    });

    $(document).on('click', '#aiio-lcp-optimize', function () {
      var $btn = $(this).prop('disabled', true);
      ajax('aiio_lcp_optimize').done(function (res) {
        if (res.success && res.data) {
          notice('LCP optimize job started (' + (res.data.count || 0) + ' images).', 'success');
          if (AIIO.page === 'pewit-ai-image-optimizer-jobs') {
            pollJob();
          } else {
            window.location.href = AIIO.jobsUrl || 'admin.php?page=pewit-ai-image-optimizer-jobs';
          }
        } else {
          notice((res.data && res.data.message) || 'Failed.', 'error');
        }
      }).always(function () { $btn.prop('disabled', false); });
    });

    if (!AIIO.onboarding_done && $('#aiio-onboarding').length) {
      $('#aiio-onboarding').addClass('is-open');
      $('#aiio-onboarding-dismiss').on('click', function (e) {
        e.preventDefault();
        ajax('aiio_complete_onboarding').always(function () {
          $('#aiio-onboarding').remove();
        });
      });
    }
  });
})(jQuery);
