/* ── IMPORT VIEW ─────────────────────────────────────────────────────────
   PDF upload → pdf-parse → Claude AI extraction → preview → save to Store
   ──────────────────────────────────────────────────────────────────────── */

// Wait for PDFParse global (loaded via module script in index.html)
function waitForPDFParse(timeoutMs = 15000) {
  return new Promise((resolve, reject) => {
    if (window.PDFParse) return resolve(window.PDFParse);
    let done = false;
    const handler = () => { if (!done) { done = true; resolve(window.PDFParse); } };
    window.addEventListener('pdf-parse-ready', handler, { once: true });
    setTimeout(() => {
      if (!done) {
        done = true;
        if (window.PDFParse) resolve(window.PDFParse);
        else reject(new Error('Timeout ao carregar pdf-parse. Verifique a conexão.'));
      }
    }, timeoutMs);
  });
}

function ImportView({ onMonthAdded }) {
  const [files, setFiles]         = React.useState([]);
  const [parsed, setParsed]       = React.useState([]);
  const [step, setStep]           = React.useState('upload'); // upload|parsing|preview|saving|done
  const [dragOver, setDragOver]   = React.useState(false);
  const [progress, setProgress]   = React.useState({});
  const [previewMonth, setPreviewMonth] = React.useState(null);
  const [baselineKey, setBaselineKey]   = React.useState('');
  const [msg, setMsg]             = React.useState('');
  const [mode, setMode]           = React.useState('new'); // 'new' | 'merge'
  const [mergeKey, setMergeKey]   = React.useState('');
  const [mergeStats, setMergeStats] = React.useState(null);
  const inputRef = React.useRef();

  const months = Store.getMonths();
  React.useEffect(() => {
    if (!mergeKey && months[0]) setMergeKey(months[0].key);
  }, []);

  function addFiles(fileList) {
    const pdfs = [...fileList].filter(f => f.name.toLowerCase().endsWith('.pdf'));
    setFiles(prev => {
      const existing = new Set(prev.map(f => f.name));
      return [...prev, ...pdfs.filter(f => !existing.has(f.name))];
    });
  }

  function handleDrop(e) {
    e.preventDefault(); setDragOver(false);
    addFiles(e.dataTransfer.files);
  }

  async function runParse() {
    if (!files.length) return;
    setStep('parsing');
    setMsg('');
    const results = [];
    let Lib;
    try {
      Lib = await waitForPDFParse();
    } catch (e) {
      setMsg('Erro ao carregar o leitor de PDF: ' + e.message);
      setStep('upload');
      return;
    }

    // Process in parallel batches of 4 for speed
    const BATCH = 4;
    const queue = [...files];
    async function worker() {
      while (queue.length) {
        const f = queue.shift();
        if (!f) return;
        setProgress(p => ({ ...p, [f.name]: { status: 'reading', pct: 15 } }));
        try {
          const ab = await f.arrayBuffer();
          const parser = new Lib({ data: new Uint8Array(ab) });
          const res = await parser.getText();
          setProgress(p => ({ ...p, [f.name]: { status: 'ai', pct: 50 } }));
          const data = await parsePDFWithAI(res.text, f.name);
          if (data && data.carteiraNome) {
            results.push(data);
            setProgress(p => ({ ...p, [f.name]: { status: 'ok', pct: 100, carteira: data.carteiraNome } }));
          } else {
            setProgress(p => ({ ...p, [f.name]: { status: 'error', pct: 100, msg: 'IA não conseguiu extrair' } }));
          }
        } catch (e) {
          setProgress(p => ({ ...p, [f.name]: { status: 'error', pct: 100, msg: e.message.slice(0, 80) } }));
        }
      }
    }
    await Promise.all(Array.from({ length: BATCH }, worker));

    if (results.length > 0) {
      setParsed(results);
      if (mode === 'merge' && mergeKey) {
        // Build carteiras dict matching mergeKey month's format
        const monthObj = buildMonthFromParsed(results, mergeKey);
        // Override the existing month's metadata for preview display
        const existing = Store.getMonth(mergeKey);
        setPreviewMonth({
          ...monthObj,
          key: mergeKey,
          label: existing.label,
          _mergeMode: true,
          _mergeTarget: existing,
          _newCarteiras: monthObj.carteiras,
        });
      } else {
        const bKey = baselineKey || months[0]?.key || '';
        const monthObj = buildMonthFromParsed(results, bKey);
        setPreviewMonth(monthObj);
      }
      setStep('preview');
    } else {
      setMsg('Nenhum PDF foi processado com sucesso. Verifique os arquivos.');
      setStep('upload');
    }
  }

  function confirmSave() {
    if (!previewMonth) return;
    setStep('saving');
    if (previewMonth._mergeMode) {
      const stats = Store.mergeMonth(previewMonth.key, previewMonth._newCarteiras);
      setMergeStats(stats);
    } else {
      Store.addMonth(previewMonth);
    }
    setTimeout(() => {
      setStep('done');
      onMonthAdded(previewMonth.key);
    }, 600);
  }

  function reset() {
    setFiles([]); setParsed([]); setProgress({});
    setPreviewMonth(null); setMsg(''); setStep('upload');
  }

  /* ── STEP: DONE ── */
  if (step === 'done') return (
    <div style={{ maxWidth: 600, margin: '0 auto', textAlign: 'center', paddingTop: 48 }}>
      <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--green-bg)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px', color: 'var(--green)' }}>
        <Icon.check />
      </div>
      <h2 style={{ fontFamily: 'Cormorant Garamond', marginBottom: 8 }}>Importação concluída</h2>
      <p style={{ color: 'var(--muted)', fontSize: '0.82rem', marginBottom: 24 }}>
        {mergeStats
          ? `${previewMonth?.label}: ${mergeStats.added} carteira(s) nova(s), ${mergeStats.updated} atualizada(s).`
          : `${previewMonth?.label} adicionado com ${Object.keys(previewMonth?.carteiras||{}).length} carteiras.`}
      </p>
      <button className="btn btn-primary" onClick={reset}>Importar mais PDFs</button>
    </div>
  );

  /* ── STEP: PREVIEW ── */
  if (step === 'preview' && previewMonth) {
    const cList = Object.values(previewMonth._mergeMode ? previewMonth._newCarteiras : previewMonth.carteiras);
    const isMerge = previewMonth._mergeMode;
    const existing = previewMonth._mergeTarget;
    const news = isMerge ? cList.filter(c => !existing.carteiras[c.nome]) : [];
    const updates = isMerge ? cList.filter(c => existing.carteiras[c.nome]) : [];
    return (
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
          <h2 style={{ fontFamily: 'Cormorant Garamond', fontSize: '1.5rem' }}>
            {isMerge ? `Adicionar a ${previewMonth.label}` : `Pré-visualização · ${previewMonth.label}`}
          </h2>
          <span style={{ fontSize: '0.72rem', color: 'var(--muted)' }}>{cList.length} carteiras extraídas</span>
        </div>

        <div className="kpi-strip" style={{ marginBottom: 16 }}>
          {isMerge ? (
            <>
              <div className="kpi-tile">
                <div className="kpi-tile-label">Mês destino</div>
                <div className="kpi-tile-value" style={{ fontSize: '1.3rem' }}>{existing.label}</div>
                <div className="kpi-tile-sub">{existing.totals.total} carteiras já existentes</div>
              </div>
              <div className="kpi-tile">
                <div className="kpi-tile-label">Carteiras novas</div>
                <div className="kpi-tile-value green">{news.length}</div>
                <div className="kpi-tile-sub">serão adicionadas</div>
              </div>
              <div className="kpi-tile">
                <div className="kpi-tile-label">Carteiras atualizadas</div>
                <div className="kpi-tile-value amber">{updates.length}</div>
                <div className="kpi-tile-sub">já existem, dados sobrescritos</div>
              </div>
              <div className="kpi-tile">
                <div className="kpi-tile-label">Total após importação</div>
                <div className="kpi-tile-value">{existing.totals.total + news.length}</div>
                <div className="kpi-tile-sub">carteiras no mês</div>
              </div>
            </>
          ) : (
            <>
              <div className="kpi-tile">
                <div className="kpi-tile-label">Carteiras</div>
                <div className="kpi-tile-value">{cList.length}</div>
              </div>
              <div className="kpi-tile">
                <div className="kpi-tile-label">PL Total</div>
                <div className="kpi-tile-value" style={{ fontSize: '1.3rem' }}>{fmtBRL(previewMonth.plTotal, true)}</div>
              </div>
              <div className="kpi-tile">
                <div className="kpi-tile-label">Data Extrato</div>
                <div className="kpi-tile-value" style={{ fontSize: '1.2rem' }}>{previewMonth.dataExtrato}</div>
              </div>
            </>
          )}
        </div>

        <div className="card" style={{ marginBottom: 16 }}>
          <div className="card-header"><h3>Carteiras extraídas</h3></div>
          <div style={{ overflowX: 'auto' }}>
            <table className="tbl">
              <thead>
                <tr>
                  <th>Carteira</th>
                  {isMerge && <th>Situação</th>}
                  <th className="r">PL Anterior</th>
                  <th className="r">PL Atual</th>
                  <th className="r">Variação %</th>
                  <th className="r">Rent. Mês</th>
                </tr>
              </thead>
              <tbody>
                {cList.map((c, i) => {
                  const isNew = isMerge && !existing.carteiras[c.nome];
                  return (
                    <tr key={i}>
                      <td style={{ fontWeight: 500, color: 'var(--heading)' }}>{c.nome}</td>
                      {isMerge && <td><span className="badge" style={{ background: isNew ? 'var(--green-bg)' : 'var(--amber-bg)', color: isNew ? 'var(--green)' : 'var(--amber)' }}>{isNew ? 'Nova' : 'Atualiza'}</span></td>}
                      <td className="num">{fmtBRL(c.plAnterior)}</td>
                      <td className="num">{fmtBRL(c.plAtual)}</td>
                      <td className={`num ${colorClass(c.varPct)}`}>{fmtPct(c.varPct)}</td>
                      <td className={`num ${colorClass(c.rentMes)}`}>{fmtPct(c.rentMes)}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>

        <div className="import-actions">
          <button className="btn btn-secondary" onClick={() => setStep('upload')}>← Voltar</button>
          <button className="btn btn-primary" onClick={confirmSave}>
            <Icon.check /> {isMerge ? `Adicionar ${news.length} nova(s) e atualizar ${updates.length}` : `Confirmar e salvar ${previewMonth.label}`}
          </button>
        </div>
      </div>
    );
  }

  /* ── STEP: PARSING ── */
  if (step === 'parsing') return (
    <div style={{ maxWidth: 560, margin: '0 auto' }}>
      <h2 style={{ fontFamily: 'Cormorant Garamond', marginBottom: 20 }}>Processando PDFs…</h2>
      <div className="import-file-list">
        {files.map(f => {
          const p = progress[f.name] || { status: 'aguardando', pct: 0 };
          return (
            <div className="import-file-row" key={f.name}>
              <Icon.pdf />
              <span className="import-file-name">{f.name}</span>
              <span className="import-file-status" style={{ color: p.status === 'ok' ? 'var(--green)' : p.status === 'error' ? 'var(--red)' : 'var(--muted)', fontSize: '0.72rem', minWidth: 80 }}>
                {p.status === 'ok' ? '✓ Extraído' : p.status === 'error' ? '✗ Erro' : p.status === 'ai' ? '🤖 IA…' : p.status === 'reading' ? 'Lendo…' : 'Aguardando'}
              </span>
              <div className="import-file-progress">
                <div className="import-file-progress-bar" style={{ width: `${p.pct}%`, background: p.status === 'error' ? 'var(--red)' : 'var(--navy)' }} />
              </div>
            </div>
          );
        })}
      </div>
      <p style={{ fontSize: '0.72rem', color: 'var(--muted)', marginTop: 16 }}>
        A IA extrai automaticamente carteira, PL, rentabilidade e composição de cada PDF.
      </p>
    </div>
  );

  /* ── STEP: UPLOAD ── */
  return (
    <div style={{ maxWidth: 640, margin: '0 auto' }}>
      <div className="section-hd">
        <h2>Importar PDFs</h2>
        <span className="section-sub">Books mensais do SmartBrain · um arquivo por carteira</span>
      </div>

      {msg && <div className="alert-banner" style={{ marginBottom: 16 }}><Icon.alert />{msg}</div>}

      {/* Mode selector */}
      {months.length > 0 && (
        <div style={{ marginBottom: 16, padding: 16, background: 'var(--white)', border: '1px solid var(--rule)' }}>
          <div className="label" style={{ marginBottom: 10 }}>Modo de importação</div>
          <div style={{ display: 'flex', gap: 0, border: '1px solid var(--rule)' }}>
            <button onClick={() => setMode('new')} style={{
              flex: 1, padding: '10px 14px', fontSize: '0.78rem',
              background: mode === 'new' ? 'var(--navy)' : 'var(--white)',
              color: mode === 'new' ? 'var(--white)' : 'var(--body)',
              borderRight: '1px solid var(--rule)',
              textAlign: 'left',
            }}>
              <div style={{ fontWeight: 600, marginBottom: 2 }}>Criar novo mês</div>
              <div style={{ fontSize: '0.68rem', opacity: 0.8 }}>Importa um mês inteiro de uma vez</div>
            </button>
            <button onClick={() => setMode('merge')} style={{
              flex: 1, padding: '10px 14px', fontSize: '0.78rem',
              background: mode === 'merge' ? 'var(--navy)' : 'var(--white)',
              color: mode === 'merge' ? 'var(--white)' : 'var(--body)',
              textAlign: 'left',
            }}>
              <div style={{ fontWeight: 600, marginBottom: 2 }}>Adicionar a mês existente</div>
              <div style={{ fontSize: '0.68rem', opacity: 0.8 }}>Inclui carteiras faltantes em um mês já criado</div>
            </button>
          </div>
        </div>
      )}

      {/* Baseline / Target selector */}
      {months.length > 0 && (
        <div style={{ marginBottom: 16 }}>
          {mode === 'new' ? (
            <>
              <div className="label" style={{ marginBottom: 6 }}>Mês baseline (comparação)</div>
              <select value={baselineKey} onChange={e => setBaselineKey(e.target.value)} style={{ padding: '7px 12px', border: '1px solid var(--rule)', background: 'var(--white)', fontSize: '0.82rem', color: 'var(--body)', outline: 'none' }}>
                <option value="">— automático —</option>
                {months.map(m => <option key={m.key} value={m.key}>{m.label}</option>)}
              </select>
            </>
          ) : (
            <>
              <div className="label" style={{ marginBottom: 6 }}>Mês de destino</div>
              <select value={mergeKey} onChange={e => setMergeKey(e.target.value)} style={{ padding: '7px 12px', border: '1px solid var(--rule)', background: 'var(--white)', fontSize: '0.82rem', color: 'var(--body)', outline: 'none' }}>
                {months.map(m => <option key={m.key} value={m.key}>{m.label} · {m.totals.total} carteiras</option>)}
              </select>
            </>
          )}
        </div>
      )}

      {/* Drop zone */}
      <div
        className={`import-zone${dragOver ? ' drag-over' : ''}`}
        onDragOver={e => { e.preventDefault(); setDragOver(true); }}
        onDragLeave={() => setDragOver(false)}
        onDrop={handleDrop}
        onClick={() => inputRef.current?.click()}
      >
        <div className="import-zone-icon"><Icon.import /></div>
        <div className="import-zone-title">Arraste os PDFs aqui</div>
        <div className="import-zone-sub">ou clique para selecionar · aceita múltiplos arquivos</div>
        <input ref={inputRef} type="file" accept=".pdf" multiple style={{ display: 'none' }} onChange={e => addFiles(e.target.files)} />
      </div>

      {/* File list */}
      {files.length > 0 && (
        <div className="import-file-list" style={{ marginTop: 16 }}>
          {files.map(f => (
            <div className="import-file-row" key={f.name}>
              <Icon.pdf />
              <span className="import-file-name">{f.name}</span>
              <span style={{ fontSize: '0.7rem', color: 'var(--muted)' }}>{(f.size/1024).toFixed(0)} KB</span>
              <button className="btn btn-secondary btn-sm" style={{ marginLeft: 'auto' }} onClick={() => setFiles(prev => prev.filter(x => x.name !== f.name))}>
                <Icon.close />
              </button>
            </div>
          ))}
        </div>
      )}

      {files.length > 0 && (
        <div className="import-actions">
          <button className="btn btn-secondary" onClick={() => setFiles([])}>Limpar</button>
          <button className="btn btn-primary" onClick={runParse}>
            <Icon.import /> Processar {files.length} PDF{files.length > 1 ? 's' : ''} com IA
          </button>
        </div>
      )}

      <div style={{ marginTop: 32, padding: '16px 20px', background: 'var(--paper)', border: '1px solid var(--rule)', fontSize: '0.75rem', color: 'var(--muted)', lineHeight: 1.6 }}>
        <strong style={{ color: 'var(--body)' }}>Como funciona:</strong><br />
        1. Faça o download dos Books mensais do SmartBrain (um PDF por carteira)<br />
        2. Arraste todos os PDFs de um mesmo mês aqui de uma vez<br />
        3. A IA lê cada PDF e extrai: carteira, PL, rentabilidade, asset allocation e composição<br />
        4. Revise os dados extraídos e confirme a importação<br />
        5. O mês passa a aparecer no Dashboard, Comparativo e Histórico de cada carteira
      </div>
    </div>
  );
}

Object.assign(window, { ImportView });
