(function ($) {
  'use strict';

  const state = {
    tab: 'used',
    page: 1,
    per_page: 20,
    busy: false,
    lastBatchId: null,
  };

  function ajax(action, data) {
    return $.post(fold82smMediaOrganizer.ajax_url, Object.assign({
      action,
      nonce: fold82smMediaOrganizer.nonce,
    }, data || {}));
  }

  function setProgress(show, text, pct) {
    const $box = $('#fold82sm-media-progress');
    if (!show) {
      $box.hide();
      return;
    }
    $('#fold82sm-media-progress-text').text(text || '');
    $('#fold82sm-media-progress-bar').css('width', Math.max(0, Math.min(100, pct || 0)) + '%');
    $box.show();
  }

  function esc(s) {
    return String(s || '').replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
  }

  function renderAttachmentRow(item, withCheckbox) {
  const thumb = item.thumb
    ? `<img src="${esc(item.thumb)}" style="width:48px;height:48px;object-fit:cover;border-radius:4px;"/>`
    : '';

  const title = item.title ? esc(item.title) : `#${item.attachment_id}`;
  const link  = item.url ? `<a href="${esc(item.url)}" target="_blank" rel="noopener">View</a>` : '';

  const usageCount = (item.usage_count !== null && item.usage_count !== undefined)
    ? (parseInt(item.usage_count, 10) || 0)
    : null;

  // Badge "X uses" + "View all" 
  const viewAllInline = (usageCount !== null && usageCount > 0)
    ? ` <a href="#" class="fold82sm-view-all-uses"
          data-attachment="${item.attachment_id}"
          data-title="${esc(item.title || ('#' + item.attachment_id))}"
          data-total="${usageCount}">View all</a>`
    : '';

  const usage = (usageCount !== null)
    ? `<span style="display:inline-block;padding:2px 8px;border:1px solid #ccd0d4;border-radius:999px;font-size:12px;">${usageCount} uses</span>${viewAllInline}`
    : '';
  
  let where = '';
  if (usageCount !== null && usageCount > 0) {
    const previewItems = (item.where_used && item.where_used.length) ? item.where_used : [];

    const list = previewItems.map(w => {
      const t = esc(w.title || ('#' + w.post_id));
      const e = w.edit ? `<a href="${esc(w.edit)}">Edit</a>` : '';
      const v = w.view ? `<a href="${esc(w.view)}" target="_blank" rel="noopener">View</a>` : '';
      return `<span style="margin-right:10px;">${t} ${e} ${v}</span>`;
    }).join('');

    where = list
      ? `<div style="margin-top:6px; font-size:12px; color:#666;">Used in: ${list}</div>`
      : '';
  }

  const cb = withCheckbox
    ? `<input type="checkbox" class="fold82sm-media-select" value="${item.attachment_id}" />`
    : '';

  return `
    <tr>
      <td style="width:30px;">${cb}</td>
      <td style="width:60px;">${thumb}</td>
      <td>
        <div style="font-weight:600;">${title}</div>
        <div style="font-size:12px; margin-top:2px;">${link} ${usage}</div>
        ${where}
      </td>
    </tr>
  `;
}

  function renderDuplicatesGroup(group) {
    const head = `
      <div style="display:flex;justify-content:space-between;align-items:center;padding:10px 12px;background:#f6f7f7;border:1px solid #ccd0d4;border-radius:4px;">
        <div><strong>Hash:</strong> ${esc(group.file_hash)} &nbsp; <span style="color:#666;">(${group.count} files)</span></div>
        <button class="button fold82sm-select-all-dup" type="button">Select all</button>
      </div>
    `;

    const rows = (group.attachments || []).map(a => renderAttachmentRow(a, true)).join('');

    return `
      <div class="fold82sm-dup-group" style="margin: 12px 0;">
        ${head}
        <table id="content-table" class="wp-list-table widefat fixed striped" style="margin-top:8px;">
          <tbody>${rows}</tbody>
        </table>
      </div>
    `;
  }

  function renderTab(data) {
    const $c = $('#fold82sm-media-tab-content');

    let html = '';

    if (state.tab === 'restore') {
      const items = data.items || [];
      html += '<table id="content-table" class="wp-list-table widefat fixed striped"><thead><tr><th>Batch</th><th>Action</th><th>Count</th><th>When</th><th></th></tr></thead><tbody>';
      if (!items.length) {
        html += '<tr><td colspan="5">No restore points yet.</td></tr>';
      } else {
        items.forEach(it => {
          html += `<tr>
            <td><code>${esc(it.batch_id)}</code></td>
            <td>${esc(it.action)}</td>
            <td>${esc(it.count)}</td>
            <td>${esc(it.created_at)}</td>
            <td><button class="button fold82sm-undo" data-batch="${esc(it.batch_id)}" type="button">Undo</button></td>
          </tr>`;
        });
      }
      html += '</tbody></table>';
      $c.html(html);
      return;
    }

    if (state.tab === 'duplicates') {
      const groups = data.items || [];
      if (!groups.length) {
        $c.html('<div style="padding:12px;background:#fff;border:1px solid #ccd0d4;border-radius:4px;">No duplicates found. Run “Compute Hashes” first.</div>');
        return;
      }
      html += '<div style="margin-bottom:10px; display:flex; gap:8px; flex-wrap:wrap;">'
        + '<button class="button button-secondary" id="fold82sm-action-quarantine" type="button">Quarantine selected</button>'
        + '<button class="button" id="fold82sm-action-trash" type="button">Move to Trash</button>'
        + '</div>';
      groups.forEach(g => html += renderDuplicatesGroup(g));
      $c.html(html);
      return;
    }

    const items = data.items || [];

    html += '<div style="margin-bottom:10px; display:flex; gap:8px; flex-wrap:wrap;">';

    if (state.tab === 'quarantine') {
      html += '<button class="button button-secondary" id="fold82sm-action-unquarantine" type="button">Unquarantine selected</button>';
    } else {
      html += '<button class="button button-secondary" id="fold82sm-action-quarantine" type="button">Quarantine selected</button>';
    }
    html += '<button class="button" id="fold82sm-action-trash" type="button">Move to Trash</button>';
    html += '</div>';

    html += '<table id="content-table" class="wp-list-table widefat fixed striped"><thead><tr><th style="width:30px;"><input type="checkbox" id="fold82sm-media-select-all" /></th><th style="width:60px;"></th><th>File</th></tr></thead><tbody>';

    if (!items.length) {
      html += `<tr><td colspan="3">No items.</td></tr>`;
    } else {
      items.forEach(it => html += renderAttachmentRow(it, true));
    }

    html += '</tbody></table>';

    const pg = data.pagination || {};
    const pages = pg.pages || 1;
    const page = pg.page || 1;
    const total = pg.total || 0;

    html += `
      <div style="margin-top:12px; display:flex; justify-content:space-between; align-items:center;">
        <div style="color:#666;">Total: ${total}</div>
        <div style="display:flex; gap:6px;">
          <button class="button" id="fold82sm-prev" type="button" ${page <= 1 ? 'disabled' : ''}>Prev</button>
          <span style="padding:6px 8px;">Page ${page} / ${pages}</span>
          <button class="button" id="fold82sm-next" type="button" ${page >= pages ? 'disabled' : ''}>Next</button>
        </div>
      </div>
    `;

    $c.html(html);
  }

  function loadTab() {
  if (state.busy) return;
  state.busy = true;

  $('#fold82sm-media-tab-content').html(
    '<div style="padding:12px;background:#fff;border:1px solid #ccd0d4;border-radius:4px;">Loading...</div>'
  );

  ajax('fold82sm_media_get_tab', { tab: state.tab, page: state.page, per_page: state.per_page })
    .done(res => {
      if (!res || !res.success) {
        alert((res && res.data && res.data.message) ? res.data.message : 'Error');
        return;
      }

      renderTab(res.data);

      // Update total files counter in header
      const total = (res.data && res.data.pagination && res.data.pagination.total)
        ? res.data.pagination.total
        : 0;

      $('#fold82sm-media-total-count').text(total);
    })
    .fail(() => alert('Request failed'))
    .always(() => { state.busy = false; });
}

  function getSelectedIds() {
    const ids = [];
    $('.fold82sm-media-select:checked').each(function () {
      ids.push(parseInt($(this).val(), 10));
    });
    return ids.filter(Boolean);
  }

  function applyAction(action) {
    const ids = getSelectedIds();
    if (!ids.length) return alert('Select at least one item.');

    const safe = $('#fold82sm-media-safe-mode').is(':checked') ? 1 : 0;

    ajax('fold82sm_media_apply_action', { do: action, ids, safe_mode: safe })
      .done(res => {
        if (!res || !res.success) {
          alert((res && res.data && res.data.message) ? res.data.message : 'Error');
          return;
        }
        state.lastBatchId = res.data.batch_id;
        loadTab();
      })
      .fail(() => alert('Request failed'));
  }

  function runBatch(actionName, perPage, progressLabel, doneCb) {
    let offset = 0;
    setProgress(true, progressLabel + '…', 0);

    function step() {
      ajax(actionName, { offset, per_page: perPage })
        .done(res => {
          if (!res || !res.success) {
            setProgress(false);
            alert((res && res.data && res.data.message) ? res.data.message : 'Error');
            return;
          }
          const d = res.data;
          offset = d.next_offset || 0;
          const total = d.total || 0;
          const processed = d.processed || 0;
          const pct = total ? Math.round((processed / total) * 100) : 100;
          setProgress(true, `${progressLabel}: ${processed}/${total}`, pct);
          if (d.done) {
            setProgress(false);
            if (doneCb) doneCb();
          } else {
            step();
          }
        })
        .fail(() => {
          setProgress(false);
          alert('Request failed');
        });
    }

    step();
  }

  $(document).on('click', '.nav-tab-wrapper .nav-tab', function (e) {
    e.preventDefault();
    $('.nav-tab-wrapper .nav-tab').removeClass('nav-tab-active');
    $(this).addClass('nav-tab-active');
    state.tab = $(this).data('tab');
    state.page = 1;
    loadTab();
  });

  $(document).on('change', '#fold82sm-media-select-all', function () {
    $('.fold82sm-media-select').prop('checked', $(this).is(':checked'));
  });

  $(document).on('click', '.fold82sm-select-all-dup', function () {
    $(this).closest('.fold82sm-dup-group').find('.fold82sm-media-select').prop('checked', true);
  });

  $(document).on('click', '#fold82sm-prev', function () {
    state.page = Math.max(1, state.page - 1);
    loadTab();
  });

  $(document).on('click', '#fold82sm-next', function () {
    state.page = state.page + 1;
    loadTab();
  });

  $(document).on('click', '#fold82sm-action-quarantine', function () { applyAction('quarantine'); });
  $(document).on('click', '#fold82sm-action-unquarantine', function () { applyAction('unquarantine'); });
  $(document).on('click', '#fold82sm-action-trash', function () {
    if (!confirm('Move selected items to Trash?')) return;
    applyAction('trash');
  });

  $(document).on('click', '.fold82sm-undo', function () {
    const batch = $(this).data('batch');
    if (!batch) return;
    ajax('fold82sm_media_undo_batch', { batch_id: batch })
      .done(res => {
        if (!res || !res.success) {
          alert((res && res.data && res.data.message) ? res.data.message : 'Error');
          return;
        }
        alert(`Restored: ${res.data.restored}`);
        loadTab();
      })
      .fail(() => alert('Request failed'));
  });

  $('#fold82sm-media-start-scan').on('click', function () {
    runBatch('fold82sm_media_scan_batch', 25, 'Scanning content', () => loadTab());
  });

  $('#fold82sm-media-deep-scan').on('click', function () {
    runBatch('fold82sm_media_deep_scan_batch', 8, 'Deep scanning public pages', () => loadTab());
  });

  $('#fold82sm-media-compute-hashes').on('click', function () {
    runBatch('fold82sm_media_hash_batch', 25, 'Computing hashes', () => loadTab());
  });

  $(function () {
    loadTab();
  });

/**
 * Ensure the uses modal exists in the DOM
 */
function ensureUsesModal() {
  if ($('#fold82sm-uses-modal').length) return;

  const modal = `
    <div id="fold82sm-uses-modal" style="display:none;">
        <div class="fold82sm-uses-modal-backdrop"></div>
        <div class="fold82sm-uses-modal-panel">
          <div class="fold82sm-uses-modal-header">
            <div>
              <div style="font-weight:700;font-size:14px;" id="fold82sm-uses-modal-title">Used in</div>
              <div style="font-size:12px;color:#666;" id="fold82sm-uses-modal-subtitle"></div>
            </div>
            <button type="button" class="button" id="fold82sm-uses-modal-close">Close</button>
          </div>
          <div class="fold82sm-uses-modal-body" id="fold82sm-uses-modal-body"></div>
          <div class="fold82sm-uses-modal-footer" id="fold82sm-uses-modal-footer"></div>
        </div>
      </div>
    `;
    $('body').append(modal);
  }

  function openUsesModal(attachmentId, mediaTitle, total) {
    ensureUsesModal();

    $('#fold82sm-uses-modal-title').text('Used in');
    $('#fold82sm-uses-modal-subtitle').text((mediaTitle ? mediaTitle + ' — ' : '') + 'Total: ' + (parseInt(total, 10) || 0));

    $('#fold82sm-uses-modal').fadeIn(120);

    const stateModal = {
      attachmentId: attachmentId,
      page: 1,
      perPage: 20,
      total: parseInt(total, 10) || 0
    };

    function renderModalList(res) {
      const items = (res && res.items) ? res.items : [];
      const pg = (res && res.pagination) ? res.pagination : { page: 1, pages: 1, total: 0 };

      if (!items.length) {
        $('#fold82sm-uses-modal-body').html('<div style="padding:12px;">No items.</div>');
      } else {
        let out = '<div style="display:flex;flex-direction:column;">';
        items.forEach(p => {
          const t = esc(p.title || ('#' + p.post_id));
          const view = p.view ? `<a class="button button-small" href="${esc(p.view)}" target="_blank" rel="noopener">View</a>` : '';
          const edit = p.edit ? `<a class="button button-small" href="${esc(p.edit)}">Edit</a>` : '';
          out += `
            <div style="display:flex;justify-content:space-between;align-items:center;gap:10px;padding:10px 12px;border-top:1px solid #f0f0f1;">
              <div style="font-weight:600;">${t}</div>
              <div style="display:flex;gap:8px;flex-wrap:wrap;">${view} ${edit}</div>
            </div>
          `;
        });
        out += '</div>';
        $('#fold82sm-uses-modal-body').html(out);
      }

      const prevDisabled = (pg.page <= 1) ? 'disabled' : '';
      const nextDisabled = (pg.page >= pg.pages) ? 'disabled' : '';

      $('#fold82sm-uses-modal-footer').html(`
        <div style="display:flex;justify-content:space-between;align-items:center;padding:10px 12px;border-top:1px solid #e2e4e7;background:#f6f7f7;">
          <div style="color:#666;">Page ${pg.page} / ${pg.pages} — Total: ${pg.total}</div>
          <div style="display:flex;gap:6px;">
            <button type="button" class="button" id="fold82sm-uses-prev" ${prevDisabled}>Prev</button>
            <button type="button" class="button" id="fold82sm-uses-next" ${nextDisabled}>Next</button>
          </div>
        </div>
      `);

      $('#fold82sm-uses-prev').off('click').on('click', function () {
        if (stateModal.page <= 1) return;
        stateModal.page--;
        loadModalPage();
      });

      $('#fold82sm-uses-next').off('click').on('click', function () {
        if (stateModal.page >= pg.pages) return;
        stateModal.page++;
        loadModalPage();
      });
    }

    function loadModalPage() {
      $('#fold82sm-uses-modal-body').html('<div style="padding:12px;">Loading...</div>');

      ajax('fold82sm_media_where_used', {
        attachment_id: stateModal.attachmentId,
        page: stateModal.page,
        per_page: stateModal.perPage
      })
        .done(r => {
          if (!r || !r.success) {
            alert((r && r.data && r.data.message) ? r.data.message : 'Error');
            return;
          }
          renderModalList(r.data);
        })
        .fail(() => alert('Request failed'));
    }

    loadModalPage();
  }

  $(document).on('click', '.fold82sm-view-all-uses', function (e) {
    e.preventDefault();
    const attachmentId = parseInt($(this).data('attachment'), 10);
    const title = $(this).data('title') || '';
    const total = $(this).data('total') || 0;
    if (!attachmentId) return;
    openUsesModal(attachmentId, title, total);

  });

  $(document).on('click', '#fold82sm-uses-modal-close, .fold82sm-uses-modal-backdrop', function () {
    $('#fold82sm-uses-modal').fadeOut(120);
  });

})(jQuery);