/* SynapIA — PDF / OCR Tools Panel
   Modal flutuante com 4 abas: OCR, Dividir PDF, Comprimir, Analisar Imagem.
   NADA é salvo no servidor — tudo em memória. */

const PdfToolsPanel = ({ onClose, onInsertText }) => {
  const [tab, setTab] = React.useState('ocr');
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState('');
  const [result, setResult] = React.useState(null);
  const fileRef = React.useRef(null);

  const reset = () => { setError(''); setResult(null); };
  const switchTab = (t) => { reset(); setTab(t); if (fileRef.current) fileRef.current.value = ''; };

  // ── OCR ──────────────────────────────────────────────────────────────────
  const runOCR = async () => {
    const f = fileRef.current?.files?.[0];
    if (!f) return setError('Selecione um arquivo primeiro.');
    setBusy(true); setError(''); setResult(null);
    try {
      const fd = new FormData(); fd.append('file', f);
      const r = await fetch('/api/vision-ocr', { method: 'POST', headers: authHeaders(), body: fd });
      const j = await r.json();
      if (!j.ok) throw new Error(j.error || 'Falha no OCR');
      setResult({ type: 'text', value: j.texto, chars: j.chars, name: j.nome });
    } catch (e) { setError(e.message); }
    finally { setBusy(false); }
  };

  // ── Dividir PDF ───────────────────────────────────────────────────────────
  const runSplit = async () => {
    const f = fileRef.current?.files?.[0];
    if (!f) return setError('Selecione um PDF primeiro.');
    setBusy(true); setError(''); setResult(null);
    try {
      const fd = new FormData(); fd.append('file', f);
      const r = await fetch('/api/pdf-split', { method: 'POST', headers: authHeaders(), body: fd });
      const j = await r.json();
      if (!j.ok) throw new Error(j.error || 'Falha ao dividir');
      setResult({ type: 'split', pages: j.pages, total: j.totalPages, name: j.nome });
    } catch (e) { setError(e.message); }
    finally { setBusy(false); }
  };

  // ── Comprimir PDF ─────────────────────────────────────────────────────────
  const runCompress = async () => {
    const f = fileRef.current?.files?.[0];
    if (!f) return setError('Selecione um PDF primeiro.');
    setBusy(true); setError(''); setResult(null);
    try {
      const fd = new FormData(); fd.append('file', f);
      const r = await fetch('/api/pdf-compress', { method: 'POST', headers: authHeaders(), body: fd });
      const j = await r.json();
      if (!j.ok) throw new Error(j.error || 'Falha ao comprimir');
      setResult({ type: 'compress', base64: j.base64, original: j.originalSize, novo: j.newSize, ratio: j.reductionPercent, name: j.nome });
    } catch (e) { setError(e.message); }
    finally { setBusy(false); }
  };

  // ── Analisar Imagem ───────────────────────────────────────────────────────
  const [imgPrompt, setImgPrompt] = React.useState('');
  const runDescribe = async () => {
    const f = fileRef.current?.files?.[0];
    if (!f) return setError('Selecione uma imagem primeiro.');
    setBusy(true); setError(''); setResult(null);
    try {
      const fd = new FormData(); fd.append('file', f);
      if (imgPrompt.trim()) fd.append('prompt', imgPrompt.trim());
      const r = await fetch('/api/vision-describe', { method: 'POST', headers: authHeaders(), body: fd });
      const j = await r.json();
      if (!j.ok) throw new Error(j.error || 'Falha na análise');
      setResult({ type: 'text', value: j.descricao, name: j.nome });
    } catch (e) { setError(e.message); }
    finally { setBusy(false); }
  };

  // ── Utilitários ───────────────────────────────────────────────────────────
  const fmtSize = (b) => b > 1024*1024 ? (b/1024/1024).toFixed(2)+' MB' : (b/1024).toFixed(1)+' KB';

  const downloadB64 = (b64, name) => {
    const a = document.createElement('a');
    a.href = 'data:application/pdf;base64,' + b64;
    a.download = name;
    a.click();
  };

  const TABS = [
    { id: 'ocr',      icon: 'scan',     label: 'OCR / Texto' },
    { id: 'split',    icon: 'scissors', label: 'Dividir PDF' },
    { id: 'compress', icon: 'compress', label: 'Comprimir' },
    { id: 'vision',   icon: 'eye',      label: 'Analisar Imagem' },
  ];

  const accept = {
    ocr:      'image/*,.pdf',
    split:    '.pdf',
    compress: '.pdf',
    vision:   'image/*',
  };

  return (
    <div className="pdf-tools-overlay" onClick={e => e.target === e.currentTarget && onClose()}>
      <div className="pdf-tools-panel">
        {/* Header */}
        <div className="pdf-tools-header">
          <span className="pdf-tools-title"><I.wand size={14}/> Ferramentas PDF &amp; Visão</span>
          <button className="icon-btn" onClick={onClose}><I.x size={14}/></button>
        </div>

        {/* Tabs */}
        <div className="pdf-tools-tabs">
          {TABS.map(t => (
            <button key={t.id} className={`pdf-tab${tab === t.id ? ' active' : ''}`} onClick={() => switchTab(t.id)}>
              {I[t.icon]?.({ size: 12 })} {t.label}
            </button>
          ))}
        </div>

        {/* Body */}
        <div className="pdf-tools-body">
          {/* Upload */}
          <div className="pdf-upload-area" onClick={() => fileRef.current?.click()}>
            <I.attach size={18}/>
            <span>Clique ou arraste o arquivo aqui</span>
            <small>Aceita: {accept[tab]}</small>
          </div>
          <input ref={fileRef} type="file" accept={accept[tab]} style={{ display:'none' }}
            onChange={e => { reset(); }} />

          {/* Prompt extra p/ vision */}
          {tab === 'vision' && (
            <textarea
              className="pdf-prompt-input"
              placeholder="Instrução personalizada (opcional)…"
              value={imgPrompt}
              onChange={e => setImgPrompt(e.target.value)}
              rows={2}
            />
          )}

          {/* Botões de ação */}
          <div className="pdf-actions">
            {tab === 'ocr' && (
              <button className="btn-primary" onClick={runOCR} disabled={busy}>
                {busy ? 'Extraindo…' : <><I.scan size={13}/> Extrair texto</>}
              </button>
            )}
            {tab === 'split' && (
              <button className="btn-primary" onClick={runSplit} disabled={busy}>
                {busy ? 'Dividindo…' : <><I.scissors size={13}/> Dividir páginas</>}
              </button>
            )}
            {tab === 'compress' && (
              <button className="btn-primary" onClick={runCompress} disabled={busy}>
                {busy ? 'Comprimindo…' : <><I.compress size={13}/> Comprimir PDF</>}
              </button>
            )}
            {tab === 'vision' && (
              <button className="btn-primary" onClick={runDescribe} disabled={busy}>
                {busy ? 'Analisando…' : <><I.eye size={13}/> Analisar imagem</>}
              </button>
            )}
          </div>

          {/* Erro */}
          {error && <div className="pdf-error"><I.x size={12}/> {error}</div>}

          {/* Resultados */}
          {result && (
            <div className="pdf-result">
              {/* Texto (OCR ou Visão) */}
              {result.type === 'text' && (
                <>
                  <div className="pdf-result-meta">
                    {result.name} {result.chars ? `· ${result.chars.toLocaleString()} caracteres` : ''}
                  </div>
                  <textarea className="pdf-result-text" readOnly value={result.value} rows={12}/>
                  <div className="pdf-result-actions">
                    <button className="btn-ghost" onClick={() => navigator.clipboard?.writeText(result.value)}>
                      <I.copy size={12}/> Copiar
                    </button>
                    {onInsertText && (
                      <button className="btn-primary" onClick={() => { onInsertText(result.value); onClose(); }}>
                        <I.arrowUp size={12}/> Inserir no rascunho
                      </button>
                    )}
                  </div>
                </>
              )}

              {/* Divisão de páginas */}
              {result.type === 'split' && (
                <>
                  <div className="pdf-result-meta">
                    {result.name} · {result.total} página{result.total !== 1 ? 's' : ''}
                  </div>
                  <div className="pdf-page-grid">
                    {result.pages.map(p => (
                      <div key={p.page} className="pdf-page-card">
                        <span>Pág. {p.page}</span>
                        <small>{fmtSize(p.sizeBytes)}</small>
                        <button className="btn-ghost small" onClick={() =>
                          downloadB64(p.base64, `${result.name?.replace('.pdf','')||'doc'}_pag${p.page}.pdf`)
                        }>
                          <I.download size={11}/> Baixar
                        </button>
                      </div>
                    ))}
                  </div>
                  <button className="btn-ghost" style={{marginTop:8}} onClick={() =>
                    result.pages.forEach((p, i) => setTimeout(() =>
                      downloadB64(p.base64, `${result.name?.replace('.pdf','')||'doc'}_pag${p.page}.pdf`), i * 120))
                  }>
                    <I.download size={12}/> Baixar todas
                  </button>
                </>
              )}

              {/* Compressão */}
              {result.type === 'compress' && (
                <>
                  <div className="pdf-result-meta">
                    {result.name}<br/>
                    Original: {fmtSize(result.original)} → Novo: {fmtSize(result.novo)}
                    {result.ratio > 0 ? ` (−${result.ratio}%)` : ' (sem redução adicional)'}
                  </div>
                  <button className="btn-primary" onClick={() =>
                    downloadB64(result.base64, (result.name || 'doc.pdf').replace('.pdf', '_comprimido.pdf'))
                  }>
                    <I.download size={12}/> Baixar PDF comprimido
                  </button>
                </>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

window.PdfToolsPanel = PdfToolsPanel;
