// Painel flutuante compartilhado pelos content scripts do TikTok e IG.
// Mostra contador de mídias detectadas, lista expansível, botão "Importar pro
// ScaleReels" e controles de auto-scroll. Estilo isolado pra não conflitar
// com o CSS dos sites.
//
// API exposta (no escopo do content script):
//   ISPanel.init({ platform, onImport, onAutoScroll })
//   ISPanel.addItems(items)   — adiciona/dedup
//   ISPanel.getItems()        — retorna itens detectados
//   ISPanel.clear()
//   ISPanel.setAutoScrollState(state)

(function () {
  if (window.__IS_PANEL__) return;

  const STATE = {
    platform: null,
    items: new Map(),       // id -> item
    panel: null,
    listEl: null,
    badgeEl: null,
    expanded: false,
    onImport: null,
    onAutoScroll: null,
    autoScrolling: false,
    pendingImport: null
  };

  function cssVar() {
    // Cor base por plataforma
    return STATE.platform === 'tiktok'
      ? 'linear-gradient(135deg, #25F4EE, #FE2C55)'
      : 'linear-gradient(135deg, #3b82f6, #ec4899)';
  }

  function buildPanel() {
    const panel = document.createElement('div');
    panel.id = '__is-ext-panel';
    panel.style.cssText = `
      position: fixed; bottom: 20px; right: 20px; z-index: 2147483647;
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
      color: #fff; user-select: none;
    `;

    panel.innerHTML = `
      <style>
        #__is-ext-panel * { box-sizing: border-box; }
        .is-fab {
          display: flex; align-items: center; gap: 10px;
          background: ${cssVar()};
          padding: 12px 16px; border-radius: 999px;
          box-shadow: 0 8px 24px rgba(0,0,0,0.35);
          cursor: pointer; font-size: 13px; font-weight: 700;
          transition: transform 0.15s;
        }
        .is-fab:hover { transform: translateY(-2px); }
        .is-badge {
          background: rgba(255,255,255,0.25); padding: 2px 8px; border-radius: 999px;
          font-size: 11px; font-weight: 800; min-width: 22px; text-align: center;
        }
        .is-panel {
          margin-top: 10px; display: none;
          width: 380px; max-height: 70vh;
          background: #131c2e; border: 1px solid rgba(255,255,255,0.1);
          border-radius: 14px; overflow: hidden;
          box-shadow: 0 16px 40px rgba(0,0,0,0.45);
        }
        .is-panel.open { display: flex; flex-direction: column; }
        .is-pan-hd {
          padding: 12px 14px; background: linear-gradient(180deg, rgba(255,255,255,0.04), transparent);
          border-bottom: 1px solid rgba(255,255,255,0.06);
          display: flex; justify-content: space-between; align-items: center;
        }
        .is-pan-title { font-size: 13px; font-weight: 700; }
        .is-pan-sub { font-size: 11px; color: #a8b0c0; margin-top: 2px; }
        .is-pan-actions { display: flex; gap: 6px; }
        .is-btn {
          padding: 6px 10px; border-radius: 8px; border: none;
          font-family: inherit; font-size: 11px; font-weight: 600;
          cursor: pointer; background: rgba(255,255,255,0.08); color: #fff;
          transition: background 0.15s;
        }
        .is-btn:hover { background: rgba(255,255,255,0.15); }
        .is-btn.p { background: #3b82f6; }
        .is-btn.p:hover { background: #60a5fa; }
        .is-btn.g { background: #22c55e; }
        .is-btn.g:hover { background: #16a34a; }
        .is-btn[disabled] { opacity: 0.4; cursor: not-allowed; }
        .is-pan-list {
          flex: 1; overflow-y: auto; padding: 8px;
        }
        .is-pan-list::-webkit-scrollbar { width: 6px; }
        .is-pan-list::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.12); border-radius: 3px; }
        .is-item {
          display: grid; grid-template-columns: 18px 52px 1fr auto;
          gap: 8px; align-items: center;
          padding: 6px 8px; border-radius: 8px; transition: background 0.1s;
        }
        .is-item:hover { background: rgba(255,255,255,0.04); }
        .is-item input[type="checkbox"] { width: 16px; height: 16px; accent-color: #3b82f6; }
        .is-thumb {
          width: 52px; height: 52px; object-fit: cover; border-radius: 6px;
          background: #1c2740; display: block;
        }
        .is-thumb.placeholder { display: flex; align-items: center; justify-content: center; font-size: 18px; color: #6b7488; }
        .is-meta { min-width: 0; font-size: 11px; }
        .is-meta b { color: #fff; font-weight: 600; }
        .is-meta .author { color: #a8b0c0; font-size: 10px; margin-top: 2px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
        .is-meta .desc { color: #6b7488; font-size: 10px; margin-top: 1px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; max-width: 200px; }
        .is-kind { font-size: 9px; padding: 2px 6px; border-radius: 4px; background: rgba(59,130,246,0.2); color: #a5b4fc; font-weight: 700; text-transform: uppercase; }
        .is-status { font-size: 9px; padding: 2px 6px; border-radius: 4px; font-weight: 700; text-transform: uppercase; white-space: nowrap; }
        .is-status.queued { background: rgba(156,163,175,0.22); color: #d1d5db; }
        .is-status.downloading { background: rgba(59,130,246,0.22); color: #93c5fd; }
        .is-status.processing { background: rgba(168,85,247,0.22); color: #d8b4fe; }
        .is-status.uploading { background: rgba(245,158,11,0.22); color: #fcd34d; }
        .is-status.done { background: rgba(34,197,94,0.22); color: #86efac; }
        .is-status.failed, .is-status.blocked { background: rgba(239,68,68,0.22); color: #fca5a5; }
        .is-spin { display: inline-block; width: 10px; height: 10px; border: 2px solid currentColor; border-bottom-color: transparent; border-radius: 50%; vertical-align: middle; margin-right: 4px; animation: is-spin 0.7s linear infinite; }
        @keyframes is-spin { to { transform: rotate(360deg); } }
        .is-empty { text-align: center; padding: 30px 14px; color: #6b7488; font-size: 12px; line-height: 1.5; }
        .is-pan-ver { font-size: 9px; color: #6b7488; font-weight: 600; margin-top: 2px; letter-spacing: 0.4px; }
        /* Bloco de configurações ativas no topo do painel (antes da lista de vídeos) */
        .is-cfg-strip {
          margin: 8px; padding: 10px 12px;
          background: linear-gradient(135deg, rgba(59,130,246,0.08), rgba(34,197,94,0.05));
          border: 1px solid rgba(59,130,246,0.18); border-radius: 10px;
        }
        .is-cfg-strip-hd {
          display: flex; justify-content: space-between; align-items: center; cursor: pointer;
          font-size: 11px; font-weight: 700; color: #c7d2fe;
        }
        .is-cfg-strip-hd .chev { transition: transform 0.2s; font-size: 10px; color: #60a5fa; }
        .is-cfg-strip.open .chev { transform: rotate(180deg); }
        .is-cfg-strip-body { display: none; margin-top: 8px; font-size: 11px; }
        .is-cfg-strip.open .is-cfg-strip-body { display: block; }
        .is-cfg-mini { display: flex; justify-content: space-between; align-items: center; padding: 6px 0; border-bottom: 1px solid rgba(255,255,255,0.04); gap: 8px; }
        .is-cfg-mini:last-child { border-bottom: 0; }
        .is-cfg-mini .l { color: #a8b0c0; font-size: 11px; }
        .is-cfg-mini .v { color: #fff; font-weight: 600; }
        .is-cfg-mini .v.off { color: #6b7488; font-weight: 400; }
        .is-cfg-mini .v.on { color: #86efac; }
        .is-cfg-strip-summary { color: #a8b0c0; font-weight: 400; font-size: 10px; margin-top: 4px; }
        /* Controles inline editáveis no strip */
        .is-cfg-toggle {
          display: inline-flex; align-items: center; gap: 4px; cursor: pointer;
          font-size: 11px; font-weight: 600; padding: 2px 8px; border-radius: 6px;
          background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.08);
          transition: background 0.12s;
        }
        .is-cfg-toggle:hover { background: rgba(255,255,255,0.12); }
        .is-cfg-toggle.on { background: rgba(34,197,94,0.18); border-color: rgba(34,197,94,0.4); color: #86efac; }
        .is-cfg-toggle.off { color: #6b7488; }
        .is-cfg-toggle.locked { opacity: 0.55; cursor: not-allowed; }
        .is-cfg-toggle.locked:hover { background: rgba(255,255,255,0.06); }
        .is-cfg-select {
          background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.1);
          color: #fff; font-size: 11px; font-family: inherit; padding: 3px 6px;
          border-radius: 6px; max-width: 130px;
        }
        .is-cfg-select:disabled { opacity: 0.5; cursor: not-allowed; }
        .is-cfg-pro {
          font-size: 8px; font-weight: 800; letter-spacing: 0.06em;
          background: linear-gradient(135deg,#f59e0b,#f97316); color: #fff;
          padding: 1px 4px; border-radius: 3px; margin-left: 4px;
        }
        /* Modal de confirmação de import */
        .is-modal-bg { position: fixed; inset: 0; background: rgba(7, 12, 22, 0.78); z-index: 2147483647; display: flex; align-items: center; justify-content: center; padding: 16px; }
        .is-modal { width: 360px; max-width: 100%; background: #131c2e; border: 1px solid rgba(255,255,255,0.1); border-radius: 14px; box-shadow: 0 20px 50px rgba(0,0,0,0.6); display: flex; flex-direction: column; max-height: 85vh; }
        .is-modal-hd { padding: 14px 16px; border-bottom: 1px solid rgba(255,255,255,0.06); display: flex; justify-content: space-between; align-items: center; }
        .is-modal-title { font-size: 14px; font-weight: 700; }
        .is-modal-x { background: rgba(255,255,255,0.08); border: 0; color: #fff; width: 24px; height: 24px; border-radius: 6px; cursor: pointer; font-size: 14px; line-height: 1; }
        .is-modal-x:hover { background: rgba(255,255,255,0.15); }
        .is-modal-body { padding: 12px 16px; overflow-y: auto; display: flex; flex-direction: column; gap: 8px; }
        .is-cfg-row { display: flex; justify-content: space-between; align-items: center; padding: 8px 10px; background: rgba(255,255,255,0.03); border-radius: 8px; font-size: 12px; }
        .is-cfg-row .lbl { color: #a8b0c0; display: flex; align-items: center; gap: 6px; }
        .is-cfg-row .val { color: #fff; font-weight: 600; }
        .is-cfg-row .val.off { color: #6b7488; font-weight: 400; }
        .is-cfg-row .val.on { color: #86efac; }
        .is-modal-hint { font-size: 10px; color: #6b7488; text-align: center; margin-top: 4px; line-height: 1.4; }
        .is-modal-hint a { color: #a5b4fc; text-decoration: none; }
        .is-modal-foot { padding: 12px 16px; border-top: 1px solid rgba(255,255,255,0.06); display: flex; justify-content: flex-end; gap: 8px; }
        .is-pan-foot {
          padding: 10px 14px; background: rgba(0,0,0,0.2);
          border-top: 1px solid rgba(255,255,255,0.06);
          display: flex; justify-content: space-between; align-items: center; gap: 8px;
        }
        .is-foot-info { font-size: 11px; color: #a8b0c0; }
        .is-foot-actions { display: flex; gap: 6px; }
      </style>

      <div class="is-fab" id="is-fab">
        <span>📥 ScaleReels</span>
        <span class="is-badge" id="is-badge">0</span>
      </div>

      <div class="is-panel" id="is-panel">
        <div class="is-pan-hd">
          <div>
            <div class="is-pan-title">Mídias detectadas</div>
            <div class="is-pan-sub" id="is-sub">Role o perfil pra coletar mais</div>
            <div class="is-pan-ver">${escapeHtml(chrome.runtime.getManifest?.()?.version ? 'v' + chrome.runtime.getManifest().version : '')}</div>
          </div>
          <div class="is-pan-actions">
            <button class="is-btn" id="is-toggle-all">Marcar todas</button>
            <button class="is-btn" id="is-clear">Limpar</button>
          </div>
        </div>

        <!-- Strip de configurações ativas — colapsável, aparece sempre acima da lista -->
        <div class="is-cfg-strip" id="is-cfg-strip">
          <div class="is-cfg-strip-hd" id="is-cfg-strip-toggle">
            <div>
              <div>⚙ Configurações ativas</div>
              <div class="is-cfg-strip-summary" id="is-cfg-strip-summary">Carregando...</div>
            </div>
            <span class="chev">▼</span>
          </div>
          <div class="is-cfg-strip-body" id="is-cfg-strip-body"></div>
        </div>

        <div class="is-pan-list" id="is-list"></div>
        <div class="is-pan-foot">
          <div class="is-foot-info" id="is-foot-info">0 selecionados</div>
          <div class="is-foot-actions">
            <button class="is-btn" id="is-autoscroll">⤵ Auto-scroll</button>
            <button class="is-btn p" id="is-import" disabled>Importar</button>
          </div>
        </div>
      </div>

      <!-- Modal de confirmação de importação -->
      <div class="is-modal-bg" id="is-modal-bg" style="display:none">
        <div class="is-modal">
          <div class="is-modal-hd">
            <div class="is-modal-title" id="is-modal-title">Confirmar importação</div>
            <button class="is-modal-x" id="is-modal-x">×</button>
          </div>
          <div class="is-modal-body" id="is-modal-body">
            <div style="text-align:center;padding:24px;color:#a8b0c0">Carregando configurações...</div>
          </div>
          <div class="is-modal-foot">
            <button class="is-btn" id="is-modal-cancel">Cancelar</button>
            <button class="is-btn p" id="is-modal-confirm" disabled>Confirmar e importar</button>
          </div>
        </div>
      </div>
    `;

    document.body.appendChild(panel);
    STATE.panel = panel;
    STATE.listEl = panel.querySelector('#is-list');
    STATE.badgeEl = panel.querySelector('#is-badge');

    panel.querySelector('#is-fab').addEventListener('click', toggle);
    panel.querySelector('#is-toggle-all').addEventListener('click', toggleAll);
    panel.querySelector('#is-clear').addEventListener('click', clear);
    panel.querySelector('#is-autoscroll').addEventListener('click', triggerAutoScroll);
    panel.querySelector('#is-import').addEventListener('click', triggerImport);
    panel.querySelector('#is-modal-x').addEventListener('click', closeImportModal);
    panel.querySelector('#is-modal-cancel').addEventListener('click', closeImportModal);
    panel.querySelector('#is-modal-confirm').addEventListener('click', confirmImportModal);
    panel.querySelector('#is-modal-bg').addEventListener('click', (e) => {
      if (e.target.id === 'is-modal-bg') closeImportModal();
    });
    panel.querySelector('#is-cfg-strip-toggle').addEventListener('click', () => {
      panel.querySelector('#is-cfg-strip').classList.toggle('open');
    });

    // Carrega configurações ativas pra mostrar no strip do topo
    loadConfigStrip();

    render();
  }

  // ── Strip de configurações ativas (com edição inline) ──────────────────
  // Carrega settings e renderiza o resumo + controles editáveis. O user pode
  // mudar destino, ligar/desligar anti-detect, escolher moldura/watermark direto
  // do painel sem abrir o popup do Chrome. Moldura/Watermark ficam locked com
  // tag PRO se o user não tem addon premium.
  function loadConfigStrip() {
    chrome.runtime.sendMessage({ type: 'GET_IMPORT_PREVIEW' }, (r) => {
      if (!STATE.panel) return;
      const sumEl = STATE.panel.querySelector('#is-cfg-strip-summary');
      const bodyEl = STATE.panel.querySelector('#is-cfg-strip-body');
      const strip = STATE.panel.querySelector('#is-cfg-strip');
      if (chrome.runtime.lastError || !r?.ok) {
        if (sumEl) sumEl.textContent = 'Não foi possível ler as configs';
        return;
      }
      const p = r.preview || {};
      STATE._cfgPreview = p;
      const hasAddon = !!p.has_addon_tools;

      const dest = '💾 Computador';
      const tags = [];
      if (p.anti_detect) tags.push('Anti-detect');
      if (p.apply_frame) tags.push(`Moldura: ${p.frame_name || '✓'}`);
      if (p.apply_watermark) tags.push(`Watermark: ${p.watermark_name || '✓'}`);
      const summary = `${dest}` + (tags.length ? ' · ' + tags.join(' · ') : ' · sem processamento');
      if (sumEl) sumEl.textContent = summary;

      const framesOpts = (p.frame_presets || []).map(f =>
        `<option value="${escapeAttr(f.id)}" ${f.id === p.frame_preset_id ? 'selected' : ''}>${escapeHtml(f.name)}</option>`
      ).join('');
      const wmOpts = (p.watermark_presets || []).map(w => {
        // Aceita tanto imagem quanto texto agora — texto é renderizado via canvas no SW
        // antes do transcode. Só fica disabled se backend marcou usable=false.
        const usable = w.usable !== false;
        const kindTag = w.kind === 'text' ? ' (texto)' : '';
        const label = usable ? `${w.name}${kindTag}` : `${w.name} (sem dados — recadastre)`;
        const sel = (w.id === p.watermark_preset_id && usable) ? 'selected' : '';
        const dis = usable ? '' : 'disabled';
        return `<option value="${usable ? escapeAttr(w.id) : ''}" ${sel} ${dis}>${escapeHtml(label)}</option>`;
      }).join('');

      const proTag = '<span class="is-cfg-pro">PRO</span>';
      const lockedClass = hasAddon ? '' : 'locked';
      const lockedAttr = hasAddon ? '' : 'disabled';

      // Drive removido em v1.1.9 — sempre baixa no computador. Strip mostra só
      // a info estática (sem toggle) pra deixar claro onde os vídeos vão parar.
      const html = `
        <div class="is-cfg-mini">
          <span class="l">📁 Onde salvar</span>
          <span class="is-cfg-toggle on" style="cursor:default">💾 Pasta Downloads</span>
        </div>
        <div class="is-cfg-mini">
          <span class="l">🔧 Anti-detect (metadata)</span>
          <span class="is-cfg-toggle ${p.anti_detect ? 'on' : 'off'}" data-act="anti">${p.anti_detect ? '✓ ativo' : 'desligado'}</span>
        </div>
        <div class="is-cfg-mini">
          <span class="l">🖼️ Moldura ${hasAddon ? '' : proTag}</span>
          <div style="display:flex;gap:4px;align-items:center">
            <span class="is-cfg-toggle ${lockedClass} ${p.apply_frame ? 'on' : 'off'}" data-act="frame-on">${p.apply_frame ? '✓ ativa' : 'desligada'}</span>
            ${p.apply_frame && hasAddon ? `<select class="is-cfg-select" data-act="frame-sel"><option value="">— escolher —</option>${framesOpts}</select>` : ''}
          </div>
        </div>
        <div class="is-cfg-mini">
          <span class="l">💧 Marca d'água ${hasAddon ? '' : proTag}</span>
          <div style="display:flex;gap:4px;align-items:center">
            <span class="is-cfg-toggle ${lockedClass} ${p.apply_watermark ? 'on' : 'off'}" data-act="wm-on">${p.apply_watermark ? '✓ ativa' : 'desligada'}</span>
            ${p.apply_watermark && hasAddon ? `<select class="is-cfg-select" data-act="wm-sel"><option value="">— escolher —</option>${wmOpts}</select>` : ''}
          </div>
        </div>
        <div style="font-size:10px;color:#6b7488;margin-top:8px;text-align:center;display:flex;gap:6px;align-items:center;justify-content:center">
          <span>Ou abre o popup pra mais opções</span>
          <span class="is-cfg-toggle" data-act="refresh-presets" title="Recarregar molduras/watermarks do seu painel">↻ Recarregar</span>
        </div>
      `;
      if (bodyEl) bodyEl.innerHTML = html;

      // Wire dos handlers de cada controle inline
      bodyEl?.querySelectorAll('[data-act]').forEach(el => {
        el.addEventListener(el.tagName === 'SELECT' ? 'change' : 'click', (e) => handleCfgAction(el, e));
      });

      // Abre expandido por default só na primeira carga
      if (!STATE.cfgStripUserCollapsed && strip && !strip.classList.contains('open')) {
        strip.classList.add('open');
      }
    });
  }

  // Handler unificado pros controles inline do strip de configs
  function handleCfgAction(el, e) {
    const act = el.dataset.act;
    const val = el.dataset.val;
    const p = STATE._cfgPreview || {};
    const hasAddon = !!p.has_addon_tools;

    if (act === 'dest') {
      chrome.runtime.sendMessage({ type: 'PATCH_SETTINGS', patch: { destination: val } }, () => loadConfigStrip());
      return;
    }
    if (act === 'anti') {
      chrome.runtime.sendMessage({ type: 'PATCH_SETTINGS', patch: { anti_detect: !p.anti_detect } }, () => loadConfigStrip());
      return;
    }
    if (act === 'frame-on') {
      if (!hasAddon) {
        alert('🔒 Moldura é uma feature do plano Pro/Anual. Abre o popup pra ver os planos.');
        return;
      }
      chrome.runtime.sendMessage({ type: 'PATCH_SETTINGS', patch: { apply_frame: !p.apply_frame } }, () => loadConfigStrip());
      return;
    }
    if (act === 'wm-on') {
      if (!hasAddon) {
        alert('🔒 Marca d\'água é uma feature do plano Pro/Anual. Abre o popup pra ver os planos.');
        return;
      }
      chrome.runtime.sendMessage({ type: 'PATCH_SETTINGS', patch: { apply_watermark: !p.apply_watermark } }, () => loadConfigStrip());
      return;
    }
    if (act === 'frame-sel') {
      chrome.runtime.sendMessage({ type: 'PATCH_SETTINGS', patch: { frame_preset_id: el.value || null } }, () => loadConfigStrip());
      return;
    }
    if (act === 'wm-sel') {
      chrome.runtime.sendMessage({ type: 'PATCH_SETTINGS', patch: { watermark_preset_id: el.value || null } }, () => loadConfigStrip());
      return;
    }
    if (act === 'refresh-presets') {
      el.textContent = '↻ Recarregando...';
      chrome.runtime.sendMessage({ type: 'INVALIDATE_PRESETS_CACHE' }, () => {
        loadConfigStrip();
        setTimeout(() => { if (el) el.textContent = '↻ Recarregar'; }, 600);
      });
      return;
    }
  }

  function toggle() {
    STATE.expanded = !STATE.expanded;
    STATE.panel.querySelector('#is-panel').classList.toggle('open', STATE.expanded);
  }

  function clear() {
    STATE.items.clear();
    render();
    // Recarrega o strip de configs ativas (usuário pode ter mudado settings no popup
    // entre uma sessão de perfil e outra)
    loadConfigStrip();
  }

  function toggleAll() {
    const checks = STATE.listEl.querySelectorAll('input[type="checkbox"]');
    const allOn = Array.from(checks).every(c => c.checked);
    checks.forEach(c => { c.checked = !allOn; });
    updateFooter();
  }

  // Rescan manual foi removido em v1.1.11 — agora basta dar F5 que a extensão
  // re-lista do zero (interceptamos desde o primeiro request graças ao
  // document_start+MAIN world introduzido na v1.1.10).

  function triggerAutoScroll() {
    if (typeof STATE.onAutoScroll === 'function') STATE.onAutoScroll(!STATE.autoScrolling);
  }

  function triggerImport() {
    if (typeof STATE.onImport !== 'function') return;
    const selectedIds = [];
    STATE.listEl.querySelectorAll('input[type="checkbox"]:checked').forEach(c => {
      selectedIds.push(c.dataset.id);
    });
    if (!selectedIds.length) return;
    const itemsOut = selectedIds.map(id => STATE.items.get(id)).filter(Boolean);
    showImportModal(itemsOut);
  }

  // ── Modal de confirmação ────────────────────────────────────────────
  function showImportModal(items) {
    STATE.pendingImport = items;
    const bg = STATE.panel.querySelector('#is-modal-bg');
    const title = STATE.panel.querySelector('#is-modal-title');
    const body = STATE.panel.querySelector('#is-modal-body');
    const confirmBtn = STATE.panel.querySelector('#is-modal-confirm');
    title.textContent = `Importar ${items.length} ${items.length === 1 ? 'vídeo' : 'vídeos'}`;
    body.innerHTML = '<div style="text-align:center;padding:24px;color:#a8b0c0">Carregando configurações...</div>';
    confirmBtn.disabled = true;
    bg.style.display = 'flex';

    chrome.runtime.sendMessage({ type: 'GET_IMPORT_PREVIEW' }, (r) => {
      if (chrome.runtime.lastError || !r?.ok) {
        body.innerHTML = `<div style="padding:14px;color:#fca5a5">Erro lendo configurações: ${escapeHtml(r?.error || chrome.runtime.lastError?.message || 'desconhecido')}</div>`;
        return;
      }
      const p = r.preview || {};
      const rowOn = (lbl, val, on) => `<div class="is-cfg-row"><span class="lbl">${lbl}</span><span class="val ${on ? 'on' : 'off'}">${val}</span></div>`;
      const rows = [];
      rows.push(rowOn('📁 Onde salvar', '💾 Pasta Downloads', true));
      rows.push(rowOn('🔧 Anti-detect (metadata)', p.anti_detect ? 'ativo' : 'desligado', !!p.anti_detect));
      rows.push(rowOn('🖼️ Moldura', p.apply_frame ? (p.frame_name || 'ativa') : 'desligada', !!p.apply_frame));
      rows.push(rowOn('💧 Marca d\'água', p.apply_watermark ? (p.watermark_name || 'ativa') : 'desligada', !!p.apply_watermark));
      rows.push(rowOn('📜 Auto-scroll', p.auto_scroll ? 'ativo' : 'desligado', !!p.auto_scroll));
      body.innerHTML = rows.join('') +
        `<div class="is-modal-hint">Pra mudar essas opções abre o popup da extensão (ícone 🧩 no Chrome).</div>`;
      confirmBtn.disabled = false;
    });
  }

  function closeImportModal() {
    STATE.panel.querySelector('#is-modal-bg').style.display = 'none';
    STATE.pendingImport = null;
  }

  function confirmImportModal() {
    const items = STATE.pendingImport;
    closeImportModal();
    if (items?.length && typeof STATE.onImport === 'function') {
      STATE.onImport(items);
    }
  }

  function updateBadge() {
    STATE.badgeEl.textContent = String(STATE.items.size);
  }

  function updateFooter() {
    const checks = STATE.listEl.querySelectorAll('input[type="checkbox"]:checked').length;
    STATE.panel.querySelector('#is-foot-info').textContent = `${checks} selecionado${checks === 1 ? '' : 's'}`;
    STATE.panel.querySelector('#is-import').disabled = checks === 0;
  }

  function render() {
    updateBadge();
    if (!STATE.listEl) return;
    if (STATE.items.size === 0) {
      STATE.listEl.innerHTML = `<div class="is-empty">Abra um perfil (<b>${STATE.platform === 'tiktok' ? '/@usuario' : '/usuario'}</b>) e role pra coletar os vídeos.<br>O painel não captura do feed.</div>`;
      updateFooter();
      return;
    }
    const items = Array.from(STATE.items.values());
    STATE.listEl.innerHTML = items.map(it => `
      <div class="is-item">
        ${it._status
          ? `<span style="width:18px;text-align:center;color:#a8b0c0;font-size:13px">${statusEmoji(it._status)}</span>`
          : `<input type="checkbox" data-id="${escapeAttr(it._key)}">`
        }
        ${it.cover
          ? `<img class="is-thumb" src="${escapeAttr(it.cover)}" referrerpolicy="no-referrer" decoding="async" alt="" onerror="this.outerHTML='&lt;div class=&quot;is-thumb placeholder&quot;&gt;🎬&lt;/div&gt;'">`
          : `<div class="is-thumb placeholder">🎬</div>`}
        <div class="is-meta">
          <b>${(it.kind || 'video').toUpperCase()}</b>
          <div class="author">@${escapeHtml(it.author || '?')}</div>
          <div class="desc" title="${escapeAttr(it._error || it.desc || '')}">${escapeHtml(it._error ? `❌ ${it._error}` : (it.desc || '').slice(0, 60))}</div>
        </div>
        ${it._status
          ? `<div class="is-status ${escapeAttr(it._status)}">${statusLabel(it._status)}</div>`
          : `<div class="is-kind">${formatDur(it.duration_ms)}</div>`
        }
      </div>
    `).join('');
    STATE.listEl.querySelectorAll('input[type="checkbox"]').forEach(c => {
      c.addEventListener('change', updateFooter);
    });
    updateFooter();
  }

  function statusEmoji(s) {
    if (s === 'done') return '✅';
    if (s === 'failed' || s === 'blocked') return '❌';
    return '<span class="is-spin"></span>';
  }
  function statusLabel(s) {
    const labels = {
      queued: 'na fila',
      downloading: '<span class="is-spin"></span>baixando',
      processing: '<span class="is-spin"></span>processando',
      uploading: '<span class="is-spin"></span>salvando',
      done: 'ok',
      failed: 'falhou',
      blocked: 'cota'
    };
    return labels[s] || s;
  }

  // Status terminais (job acabou — sucesso ou falha definitiva)
  const TERMINAL_STATUSES = new Set(['done', 'failed', 'blocked']);

  // Handler do beforeunload pra avisar o user que fechar/navegar interrompe downloads.
  // Browser modernos ignoram a string custom e mostram texto genérico — o que importa
  // é retornar um valor truthy pra disparar o diálogo nativo de confirmação.
  function beforeUnloadHandler(e) {
    const msg = 'Tem downloads acontecendo. Se você sair desta página, os vídeos não vão ser baixados nem processados. Tem certeza?';
    e.preventDefault();
    e.returnValue = msg;
    return msg;
  }
  let _unloadGuardOn = false;
  function setUnloadGuard(active) {
    if (active === _unloadGuardOn) return;
    _unloadGuardOn = active;
    if (active) window.addEventListener('beforeunload', beforeUnloadHandler, { capture: true });
    else window.removeEventListener('beforeunload', beforeUnloadHandler, { capture: true });
  }

  // ── Atualiza status de cada item baseado em snapshot da fila do SW ──────
  function applyJobStatuses(jobs) {
    let changed = false;
    let anyActive = false;
    for (const job of jobs || []) {
      const item = STATE.items.get(job.id);
      if (item) {
        const prevStatus = item._status;
        const prevError = item._error;
        item._status = job.status || null;
        item._error = job.error || null;
        if (prevStatus !== item._status || prevError !== item._error) changed = true;
      }
      // Mesmo se o job já não está mais nesse panel (user limpou items), conta
      // pra ativar o guard se ainda há trabalho na fila do SW.
      if (job?.status && !TERMINAL_STATUSES.has(job.status)) anyActive = true;
    }
    setUnloadGuard(anyActive);
    if (changed) render();
  }

  function escapeHtml(s) { return String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c])); }
  function escapeAttr(s) { return escapeHtml(s); }
  function formatDur(ms) {
    if (!ms) return '';
    const sec = Math.round(ms / 1000);
    if (sec < 60) return sec + 's';
    return Math.floor(sec / 60) + ':' + String(sec % 60).padStart(2, '0');
  }

  function addItems(items) {
    let added = 0;
    for (const it of items) {
      if (!it?.id) continue;
      const key = `${it.platform}:${it.id}`;
      if (STATE.items.has(key)) continue;
      STATE.items.set(key, { ...it, _key: key });
      added++;
    }
    if (added > 0) render();
    return added;
  }

  function setAutoScrollState(active) {
    STATE.autoScrolling = active;
    const btn = STATE.panel?.querySelector('#is-autoscroll');
    if (btn) btn.textContent = active ? '⏸ Parar scroll' : '⤵ Auto-scroll';
  }

  // Visibilidade do painel inteiro — controlado pelo switch ON/OFF no popup.
  // Quando OFF: esconde FAB+panel, e addItems vira no-op (captura também bloqueada).
  let _extEnabled = true;
  async function loadEnabledFlag() {
    try {
      const s = await chrome.storage.local.get('is_settings');
      _extEnabled = (s['is_settings']?.extension_enabled) !== false;
    } catch (_) { _extEnabled = true; }
    applyEnabledVisibility();
  }
  function applyEnabledVisibility() {
    if (!STATE.panel) return;
    STATE.panel.style.display = _extEnabled ? '' : 'none';
  }
  // Wrap o addItems pra bloquear quando OFF
  const _addItemsRaw = addItems;
  function addItemsGated(items) {
    if (!_extEnabled) return 0;
    return _addItemsRaw(items);
  }
  // Listener da mensagem do popup
  try {
    chrome.runtime.onMessage.addListener((msg) => {
      if (msg?.type === 'IS_EXT_ENABLED_CHANGED') {
        _extEnabled = !!msg.enabled;
        applyEnabledVisibility();
      }
    });
  } catch (_) {}

  window.__IS_PANEL__ = {
    init({ platform, onImport, onAutoScroll }) {
      STATE.platform = platform;
      STATE.onImport = onImport;
      STATE.onAutoScroll = onAutoScroll;
      const start = () => { buildPanel(); loadEnabledFlag(); };
      if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', start, { once: true });
      } else {
        start();
      }
    },
    addItems: addItemsGated,
    getItems() { return Array.from(STATE.items.values()); },
    clear,
    setAutoScrollState,
    applyJobStatuses
  };
})();
