/* ============================================================
   VENTUM STUDIO — BATCH PERSONALIZATION
   CSV-driven multi-account artifact generation.

   Workflow:
     1. User pastes/loads a CSV (headers: account_name, account_domain,
        partner_name, vertical, persona, notes — extra columns become intake.notes appendix).
     2. User picks the format to generate per account (default account_brief).
     3. Optional: enable web-search account research per row (more expensive, slower).
     4. For each row, run runStrategyAgent + runCopyAgent and collect the artifact.
     5. Show per-row status (pending/running/done/error), then download:
        · combined JSON (one document with array of {row, intake, strategy, artifact})
        · CSV summary (account, headline/hook, CTA)
     User can also "push to library" so every result becomes a restorable library entry.

   Cost note: per-row LLM cost ≈ $0.04-0.08 without research, $0.16-0.30 with.
   ============================================================ */

const { useState: bUseState, useMemo: bUseMemo } = React;

function BatchPersonalizeModal({ open, onClose, intake, onPushToLibrary }) {
  if (!open) return null;
  const BRAND = window.VENTUM_BRAND;

  const [csvText, setCsvText] = bUseState('');
  const [rows, setRows] = bUseState([]); // parsed rows from CSV
  const [format, setFormat] = bUseState('account_brief');
  const [useResearch, setUseResearch] = bUseState(false);
  const [running, setRunning] = bUseState(false);
  const [results, setResults] = bUseState([]); // [{row, status, artifact?, error?}]
  const [overallStatus, setOverallStatus] = bUseState(null); // null | 'running' | 'done' | 'error'

  const parseCsv = (text) => {
    const lines = text.split(/\r?\n/).filter(l => l.trim().length);
    if (!lines.length) return [];
    const split = (line) => {
      const out = [];
      let cur = '', q = false;
      for (let i = 0; i < line.length; i++) {
        const ch = line[i];
        if (q) {
          if (ch === '"' && line[i + 1] === '"') { cur += '"'; i++; }
          else if (ch === '"') q = false;
          else cur += ch;
        } else {
          if (ch === '"') q = true;
          else if (ch === ',') { out.push(cur.trim()); cur = ''; }
          else cur += ch;
        }
      }
      out.push(cur.trim());
      return out;
    };
    const headers = split(lines[0]).map(h => h.toLowerCase().replace(/\s+/g, '_'));
    return lines.slice(1).map(l => {
      const cells = split(l);
      const obj = {};
      headers.forEach((h, i) => { obj[h] = cells[i] || ''; });
      return obj;
    });
  };

  const loadCsv = () => {
    const parsed = parseCsv(csvText);
    setRows(parsed);
    setResults(parsed.map(r => ({ row: r, status: 'pending' })));
    setOverallStatus(null);
  };

  const loadExample = () => {
    const example = `account_name,account_domain,partner_name,vertical,persona,notes
Marriott Marquis NYC,marriott.com,Marriott,hospitality,Property GM,1966-key urban convention hotel — high compression nights drive turnover pressure
Mount Sinai West,mountsinai.org,,healthcare,EVS director,200-bed acute care — Q3 norovirus cluster informed protocol re-eval
Tyson Foods Fayetteville,tyson.com,,food,Plant manager,poultry processing line — between-shift sanitation window is the bottleneck`;
    setCsvText(example);
    setRows(parseCsv(example));
    setResults(parseCsv(example).map(r => ({ row: r, status: 'pending' })));
  };

  const runBatch = async () => {
    if (!rows.length) return;
    setRunning(true);
    setOverallStatus('running');
    // Re-init results
    const initial = rows.map(r => ({ row: r, status: 'pending' }));
    setResults(initial);

    for (let i = 0; i < rows.length; i++) {
      const row = rows[i];
      setResults(prev => prev.map((r, idx) => idx === i ? { ...r, status: 'running' } : r));
      try {
        const perIntake = {
          ...intake,
          formats: [format],
          account_name: row.account_name || '',
          account_domain: row.account_domain || '',
          partner_name: row.partner_name || '',
          vertical: row.vertical || intake.vertical || 'cross_vertical',
          persona: row.persona || intake.persona || '',
          notes: [intake.notes, row.notes, Object.entries(row).filter(([k]) => !['account_name','account_domain','partner_name','vertical','persona','notes'].includes(k)).map(([k,v]) => `${k}: ${v}`).join(' · ')].filter(Boolean).join(' — ')
        };

        if (useResearch && (row.account_name || row.partner_name)) {
          try {
            const research = await window.VentumAgents.runAccountResearch({
              account_name: row.account_name,
              account_domain: row.account_domain,
              partner_name: row.partner_name,
              partner_industry: row.vertical,
              vertical: row.vertical
            });
            perIntake.account_research = { ...research, _for: row.account_name || row.partner_name };
          } catch (e) {
            console.warn('[batch] research failed for', row.account_name, e);
          }
        }

        const strategy = await window.VentumAgents.runStrategyAgent(perIntake);
        const artifact = await window.VentumAgents.runCopyAgent(format, perIntake, strategy);

        setResults(prev => prev.map((r, idx) => idx === i ? { ...r, status: 'done', intake: perIntake, strategy, artifact } : r));
      } catch (e) {
        console.error('[batch] row failed', row.account_name, e);
        setResults(prev => prev.map((r, idx) => idx === i ? { ...r, status: 'error', error: e.message || 'failed' } : r));
      }
    }
    setRunning(false);
    setOverallStatus('done');
  };

  const downloadJSON = () => {
    const payload = {
      format,
      generated_at: new Date().toISOString(),
      use_research: useResearch,
      results: results.filter(r => r.status === 'done').map(r => ({
        account: r.row.account_name || r.row.partner_name,
        intake: r.intake,
        strategy: r.strategy,
        artifact: r.artifact
      }))
    };
    const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = `ventum-batch-${format}-${Date.now()}.json`;
    a.click();
  };

  const downloadSummaryCSV = () => {
    const esc = (v) => `"${String(v == null ? '' : v).replace(/"/g, '""')}"`;
    const lines = [['account', 'status', 'headline', 'cta', 'error'].map(esc).join(',')];
    results.forEach(r => {
      const headline = r.artifact?.headline || r.artifact?.hook || r.artifact?.subject || r.artifact?.intro_line || '';
      const cta = r.artifact?.cta || r.artifact?.cta_line || r.artifact?.cta_button || r.artifact?.primary_cta || '';
      lines.push([r.row.account_name || r.row.partner_name || '', r.status, headline, cta, r.error || ''].map(esc).join(','));
    });
    const blob = new Blob([lines.join('\n')], { type: 'text/csv' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = `ventum-batch-${format}-summary-${Date.now()}.csv`;
    a.click();
  };

  const pushAllToLibrary = () => {
    const done = results.filter(r => r.status === 'done');
    if (!done.length) {
      window.__toast && window.__toast('Nothing to save — run a batch first');
      return;
    }
    done.forEach(r => {
      onPushToLibrary({
        intake: r.intake,
        strategy: r.strategy,
        artifacts: { [format]: r.artifact }
      });
    });
    window.__toast && window.__toast(`Pushed ${done.length} batch result${done.length === 1 ? '' : 's'} to library`);
  };

  const progress = results.length ? Math.round(results.filter(r => r.status === 'done' || r.status === 'error').length / results.length * 100) : 0;
  const doneCount = results.filter(r => r.status === 'done').length;
  const errCount = results.filter(r => r.status === 'error').length;

  // Cost rough estimate
  const costPer = useResearch ? 0.22 : 0.06;
  const estCost = (rows.length * costPer).toFixed(2);

  return ReactDOM.createPortal(
    <div className="tour-mask" style={{ alignItems: 'flex-start', paddingTop: 48 }} onClick={(e) => { if (e.target === e.currentTarget && !running) onClose(); }}>
      <div style={{ width: 'min(960px, 92vw)', maxHeight: 'calc(100vh - 96px)', background: 'white', borderRadius: 4, boxShadow: '0 30px 60px -10px rgba(0,0,0,0.4)', display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--ink-10)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--ink-40)' }}>Batch personalize</div>
            <h2 style={{ fontSize: 18, margin: '4px 0 0', letterSpacing: '-0.01em' }}>Generate one artifact per account</h2>
          </div>
          <button className="drawer-close" onClick={onClose} disabled={running}>×</button>
        </div>

        <div style={{ padding: 24, overflowY: 'auto', flex: 1 }}>
          {/* Step 1 — CSV */}
          <div style={{ marginBottom: 20 }}>
            <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-60)', marginBottom: 6 }}>1 · Paste a CSV</div>
            <p style={{ fontSize: 12, color: 'var(--ink-60)', lineHeight: 1.5, marginTop: 0, marginBottom: 8 }}>
              Headers (case-insensitive): <code className="mono" style={{ background: 'var(--ink-05)', padding: '1px 4px' }}>account_name, account_domain, partner_name, vertical, persona, notes</code>. Extra columns become intake notes.
            </p>
            <textarea
              value={csvText}
              onChange={(e) => setCsvText(e.target.value)}
              placeholder="Paste CSV here…"
              rows={6}
              style={{ width: '100%', padding: '8px 10px', border: '1px solid var(--ink-10)', borderRadius: 2, fontSize: 12, fontFamily: 'var(--mono)' }}
            />
            <div style={{ display: 'flex', gap: 8, marginTop: 6 }}>
              <button className="qa-fix-btn" onClick={loadCsv} disabled={!csvText.trim()}>Parse rows</button>
              <button className="qa-fix-btn" onClick={loadExample}>Load example</button>
              {rows.length > 0 && <span style={{ alignSelf: 'center', fontSize: 11, color: 'var(--ink-60)' }}>{rows.length} row{rows.length === 1 ? '' : 's'} parsed</span>}
            </div>
          </div>

          {/* Step 2 — Format */}
          <div style={{ marginBottom: 20 }}>
            <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-60)', marginBottom: 6 }}>2 · What to generate per account</div>
            <select value={format} onChange={(e) => setFormat(e.target.value)} className="select" style={{ width: '100%' }}>
              {Object.entries(BRAND.formats).map(([k, v]) => (
                <option key={k} value={k}>{v.name} — {v.desc}</option>
              ))}
            </select>
          </div>

          {/* Step 3 — Research toggle + cost */}
          <div style={{ marginBottom: 20, display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px', background: 'var(--ink-05)', borderRadius: 2 }}>
            <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, cursor: 'pointer' }}>
              <input type="checkbox" checked={useResearch} onChange={(e) => setUseResearch(e.target.checked)} />
              Run account research per row (adds ~$0.16 each, ~30s per row)
            </label>
            {rows.length > 0 && (
              <span className="mono" style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--ink-60)' }}>
                est. ~${estCost} · {rows.length} row{rows.length === 1 ? '' : 's'}
              </span>
            )}
          </div>

          {/* Step 4 — Run */}
          <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
            <button
              onClick={runBatch}
              disabled={!rows.length || running}
              className="qa-fix-btn"
              style={{ background: '#0B1F33', color: 'white', padding: '10px 16px' }}
            >{running ? `Running… ${progress}%` : `Generate ${rows.length || ''} artifact${rows.length === 1 ? '' : 's'}`}</button>
            {overallStatus === 'done' && (
              <>
                <button onClick={downloadJSON} className="qa-fix-btn" disabled={doneCount === 0}>Download JSON</button>
                <button onClick={downloadSummaryCSV} className="qa-fix-btn" disabled={results.length === 0}>Summary CSV</button>
                <button onClick={pushAllToLibrary} className="qa-fix-btn" disabled={doneCount === 0}>Push {doneCount} to library</button>
              </>
            )}
          </div>

          {/* Results */}
          {results.length > 0 && (
            <div style={{ border: '1px solid var(--ink-10)', borderRadius: 2 }}>
              {results.map((r, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '24px 1fr auto', gap: 10, padding: '8px 12px', borderBottom: i < results.length - 1 ? '1px solid var(--ink-05)' : 'none', alignItems: 'center', fontSize: 12 }}>
                  <span className={"mono"} style={{ fontSize: 10, textAlign: 'center', color: r.status === 'done' ? '#1F5A48' : r.status === 'error' ? '#A33027' : r.status === 'running' ? '#C77800' : 'var(--ink-40)' }}>
                    {r.status === 'done' ? '✓' : r.status === 'error' ? '✗' : r.status === 'running' ? '…' : '·'}
                  </span>
                  <div>
                    <div style={{ fontWeight: 500 }}>{r.row.account_name || r.row.partner_name || `Row ${i + 1}`}</div>
                    {r.artifact && (
                      <div style={{ fontSize: 11, color: 'var(--ink-60)', marginTop: 2 }}>
                        {(r.artifact.headline || r.artifact.hook || r.artifact.subject || r.artifact.intro_line || '').slice(0, 110)}
                      </div>
                    )}
                    {r.error && <div style={{ fontSize: 11, color: '#A33027', marginTop: 2 }}>{r.error}</div>}
                  </div>
                  <span className="mono" style={{ fontSize: 10, color: 'var(--ink-40)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>{r.status}</span>
                </div>
              ))}
              {overallStatus === 'done' && (
                <div style={{ padding: '8px 12px', background: 'var(--ink-05)', fontSize: 11, color: 'var(--ink-60)', display: 'flex', justifyContent: 'space-between' }}>
                  <span>{doneCount} done · {errCount} error · {results.length - doneCount - errCount} skipped</span>
                  <span className="mono">{format}</span>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>,
    document.body
  );
}

window.BatchPersonalizeModal = BatchPersonalizeModal;
