// 08 · The Synthesis — AI-assisted cross-dataset query engine.

function SynthesisTab() {
  const [query, setQuery] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [result, setResult] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [rawOpen, setRawOpen] = React.useState(false);

  const WORKER_URL = 'https://ohy-synthesis.jeremyhaynes.workers.dev';

  const SUGGESTIONS = [
    '1924', 'Mexico', 'Hart-Celler', '1880s',
    'enforcement', 'Nobel', 'Ireland', 'China',
  ];

  // ── Context builder: match query against available window data ──
  const buildContext = (q) => {
    const lq = q.toLowerCase().trim();
    const ctx = {};

    // Year match (e.g. "1924", "2001")
    const yearMatch = lq.match(/\b(1[89]\d{2}|20[0-2]\d)\b/);
    if (yearMatch) {
      const yr = parseInt(yearMatch[1]);
      const arrival = window.arrivalData?.find(d => d.year === yr);
      if (arrival) ctx.arrival = arrival;
      const enforce = window.enforcementData?.find(d => d.year === yr);
      if (enforce) ctx.enforcement = enforce;
      const laws = window.legislationData?.filter(d => d.year === yr);
      if (laws?.length) ctx.legislation = laws;
      const ratio = window.arrivalRemovalRatio?.find(d => d.year === yr);
      if (ratio) ctx.arrivalRemovalRatio = ratio;
    }

    // Decade match (e.g. "1880s", "1920s")
    const decadeMatch = lq.match(/\b(1[89]\d|20[0-2])0s\b/);
    if (decadeMatch) {
      const decStart = parseInt(decadeMatch[1] + '0');
      const decEnd = decStart + 9;
      const arrivals = window.arrivalData?.filter(d => d.year >= decStart && d.year <= decEnd);
      if (arrivals?.length) ctx.decadeArrivals = arrivals;
      const enforcements = window.enforcementData?.filter(d => d.year >= decStart && d.year <= decEnd);
      if (enforcements?.length) ctx.decadeEnforcements = enforcements;
      const laws = window.legislationData?.filter(d => d.year >= decStart && d.year <= decEnd);
      if (laws?.length) ctx.decadeLegislation = laws;
    }

    // Country / origin match
    const countries = ['mexico', 'ireland', 'china', 'germany', 'italy', 'japan',
      'india', 'philippines', 'korea', 'vietnam', 'cuba', 'dominican republic',
      'el salvador', 'guatemala', 'haiti', 'poland', 'russia', 'uk', 'canada',
      'united kingdom', 'great britain', 'england', 'scotland'];
    const countryHit = countries.find(c => lq.includes(c));
    if (countryHit) {
      const sankey = window.sankeyData?.filter(d =>
        (d.source || d.origin || '').toLowerCase().includes(countryHit) ||
        (d.target || d.destination || '').toLowerCase().includes(countryHit)
      );
      if (sankey?.length) ctx.sankeyFlows = sankey.slice(0, 20);
      const names = window.nameDiffusion?.filter(d =>
        (d.origin || d.country || '').toLowerCase().includes(countryHit)
      );
      if (names?.length) ctx.nameDiffusion = names.slice(0, 15);
      const manifest = window.manifestFull?.filter(d =>
        (d.origin || '').toLowerCase().includes(countryHit)
      );
      if (manifest?.length) ctx.manifestRecords = manifest.slice(0, 10);
    }

    // Legislation name match
    const lawNames = ['hart-celler', 'chinese exclusion', 'immigration act',
      'quota', 'naturalization', 'ina', 'irca', 'daca', 'real id',
      'johnson-reed', 'mccarran-walter', 'bracero', 'refugee act'];
    const lawHit = lawNames.find(l => lq.includes(l));
    if (lawHit) {
      const laws = window.legislationData?.filter(d =>
        (d.name || d.title || d.law || '').toLowerCase().includes(lawHit)
      );
      if (laws?.length) ctx.legislation = laws;
    }

    // Person / manifest search
    if (window.manifestFull && !countryHit && !yearMatch && !decadeMatch && !lawHit) {
      const personHits = window.manifestFull.filter(d =>
        (d.name || '').toLowerCase().includes(lq)
      );
      if (personHits.length) ctx.manifestRecords = personHits.slice(0, 10);
    }

    // Enforcement keyword
    if (lq.includes('enforcement') || lq.includes('removal') || lq.includes('deportation') || lq.includes('detention')) {
      if (window.enforcementData) ctx.enforcementTimeline = window.enforcementData;
      if (window.arrivalRemovalRatio) ctx.ratioTimeline = window.arrivalRemovalRatio.slice(-30);
    }

    // Nobel keyword
    if (lq.includes('nobel') || lq.includes('prize')) {
      if (window.nobelTimeline) ctx.nobelTimeline = window.nobelTimeline;
    }

    // Always include eras and meta for context
    if (window.ERAS) ctx.eras = window.ERAS;
    if (window.META) ctx.meta = window.META;

    return ctx;
  };

  // ── Submit query ──
  const submit = async (q) => {
    const text = (q || query).trim();
    if (!text) return;
    setQuery(text);
    setLoading(true);
    setError(null);
    setResult(null);
    setRawOpen(false);

    const context = buildContext(text);

    try {
      const res = await fetch(WORKER_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ query: text, context }),
      });
      if (!res.ok) throw new Error(`Worker returned ${res.status}`);
      const data = await res.json();
      setResult({ ...data, _context: context });
    } catch (e) {
      setError(e.message || 'Request failed');
    } finally {
      setLoading(false);
    }
  };

  const handleKey = (e) => { if (e.key === 'Enter') submit(); };

  // ── Confidence badge ──
  const ConfidenceBadge = ({ level }) => {
    const map = {
      HIGH: { color: '#C9A84C', bg: 'rgba(201,168,76,0.1)' },
      MODERATE: { color: '#FDAE61', bg: 'rgba(253,174,97,0.1)' },
      CANDIDATE: { color: '#C0392B', bg: 'rgba(192,57,43,0.1)' },
    };
    const c = map[level] || map.MODERATE;
    return (
      <span className="mono" style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        border: `1px solid ${c.color}55`, background: c.bg,
        color: c.color, padding: '4px 10px',
        fontSize: 10, letterSpacing: 0.18, textTransform: 'uppercase',
        fontWeight: 700,
      }}>
        <span style={{ width: 6, height: 6, background: c.color, borderRadius: '50%' }} />
        {level}
      </span>
    );
  };

  return (
    <div style={{ padding: '32px 56px 80px' }}>
      <Eyebrow
        id="08 · THE SYNTHESIS"
        title="Cross-dataset query engine"
        right="AI-assisted analysis"
      />

      {/* Query input */}
      <div style={{
        border: '1px solid var(--line)', background: 'rgba(30,24,16,0.5)',
        padding: '24px 28px', marginBottom: 24,
      }}>
        <div className="mono" style={{
          color: 'var(--text-dimmer)', fontSize: 10, letterSpacing: 0.2,
          textTransform: 'uppercase', marginBottom: 12,
        }}>
          Query the record
        </div>

        <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
          <input
            type="text"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            onKeyDown={handleKey}
            placeholder="Year, country, law, person, decade..."
            aria-label="Synthesis query"
            style={{
              flex: 1, background: 'var(--bg)', border: '1px solid var(--line)',
              color: 'var(--text)', padding: '10px 14px',
              fontFamily: "'Space Mono', monospace", fontSize: 13,
              letterSpacing: 0.04, outline: 'none',
              transition: 'border-color 180ms',
            }}
            onFocus={(e) => e.target.style.borderColor = 'var(--gold)'}
            onBlur={(e) => e.target.style.borderColor = 'var(--line)'}
          />
          <button
            onClick={() => submit()}
            disabled={loading || !query.trim()}
            aria-label="Run synthesis"
            style={{
              background: loading ? 'var(--line)' : 'var(--gold)',
              color: 'var(--bg)', border: 'none', cursor: loading ? 'wait' : 'pointer',
              padding: '10px 20px',
              fontFamily: "'Space Mono', monospace", fontSize: 11,
              letterSpacing: 0.15, textTransform: 'uppercase', fontWeight: 700,
              opacity: (!query.trim() || loading) ? 0.5 : 1,
              transition: 'opacity 180ms, background 180ms',
            }}
          >
            {loading ? 'Querying...' : 'Synthesize'}
          </button>
        </div>

        {/* Suggestion chips */}
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 14 }}>
          <span className="mono" style={{
            color: 'var(--text-dimmer)', fontSize: 9, letterSpacing: 0.15,
            textTransform: 'uppercase', alignSelf: 'center',
          }}>
            Try:
          </span>
          {SUGGESTIONS.map(s => (
            <button
              key={s}
              onClick={() => submit(s)}
              style={{
                background: 'transparent', border: '1px solid var(--line)',
                color: 'var(--text-dim)', padding: '4px 10px', cursor: 'pointer',
                fontFamily: "'Space Mono', monospace", fontSize: 10,
                letterSpacing: 0.1, transition: 'border-color 180ms, color 180ms',
              }}
              onMouseEnter={(e) => { e.target.style.borderColor = 'var(--gold)'; e.target.style.color = 'var(--gold)'; }}
              onMouseLeave={(e) => { e.target.style.borderColor = 'var(--line)'; e.target.style.color = 'var(--text-dim)'; }}
            >
              {s}
            </button>
          ))}
        </div>
      </div>

      {/* Loading indicator */}
      {loading && (
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          padding: '32px 0',
        }}>
          <span style={{
            width: 8, height: 8, background: 'var(--gold)', borderRadius: '50%',
            animation: 'pulse 1.2s ease-in-out infinite',
          }} />
          <span className="mono" style={{
            color: 'var(--text-dim)', fontSize: 11, letterSpacing: 0.12,
            textTransform: 'uppercase',
          }}>
            Synthesizing across datasets...
          </span>
        </div>
      )}

      {/* Error state */}
      {error && (
        <div style={{
          border: '1px solid var(--enforce)', background: 'rgba(192,57,43,0.08)',
          padding: '16px 20px', marginBottom: 24,
        }}>
          <span className="mono" style={{
            color: 'var(--enforce)', fontSize: 11, letterSpacing: 0.1,
          }}>
            Error: {error}
          </span>
        </div>
      )}

      {/* Result display */}
      {result && (
        <div style={{ animation: 'fadeUp 500ms cubic-bezier(.2,.7,.2,1) both' }}>

          {/* Synthesis text */}
          <div style={{
            border: '1px solid var(--line)', background: 'rgba(30,24,16,0.4)',
            padding: '28px 32px', marginBottom: 20,
          }}>
            <div style={{
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              marginBottom: 16,
            }}>
              <span className="mono" style={{
                color: 'var(--gold)', fontSize: 10, letterSpacing: 0.2,
                textTransform: 'uppercase', fontWeight: 700,
              }}>
                Synthesis
              </span>
              {result.confidence && <ConfidenceBadge level={result.confidence} />}
            </div>

            <div className="serif" style={{
              color: 'var(--text)', fontSize: 16, lineHeight: 1.7,
              maxWidth: 720,
            }}>
              {result.synthesis || result.text || result.answer || 'No synthesis returned.'}
            </div>
          </div>

          {/* Sources */}
          {result.sources && result.sources.length > 0 && (
            <div style={{
              border: '1px solid var(--line)', background: 'rgba(30,24,16,0.3)',
              padding: '20px 24px', marginBottom: 20,
            }}>
              <div className="mono" style={{
                color: 'var(--text-dimmer)', fontSize: 10, letterSpacing: 0.2,
                textTransform: 'uppercase', marginBottom: 12,
              }}>
                Sources referenced
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {result.sources.map((src, i) => (
                  <span key={i} className="mono" style={{
                    border: '1px solid var(--line)', padding: '4px 10px',
                    fontSize: 10, color: 'var(--text-dim)', letterSpacing: 0.08,
                  }}>
                    {typeof src === 'string' ? src : src.name || src.label || JSON.stringify(src)}
                  </span>
                ))}
              </div>
            </div>
          )}

          {/* Collapsible raw data */}
          <div style={{
            border: '1px solid var(--line)', background: 'rgba(30,24,16,0.2)',
          }}>
            <button
              onClick={() => setRawOpen(!rawOpen)}
              aria-expanded={rawOpen}
              style={{
                width: '100%', background: 'transparent', border: 'none',
                cursor: 'pointer', padding: '14px 20px',
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              }}
            >
              <span className="mono" style={{
                color: 'var(--text-dimmer)', fontSize: 10, letterSpacing: 0.2,
                textTransform: 'uppercase',
              }}>
                Raw context data
              </span>
              <span className="mono" style={{
                color: 'var(--text-dimmer)', fontSize: 12, transition: 'transform 200ms',
                transform: rawOpen ? 'rotate(90deg)' : 'rotate(0deg)',
              }}>
                {'\u25B6'}
              </span>
            </button>
            {rawOpen && (
              <div style={{
                borderTop: '1px solid var(--line)', padding: '16px 20px',
                maxHeight: 400, overflowY: 'auto',
              }}>
                <pre className="mono" style={{
                  color: 'var(--text-dim)', fontSize: 10.5, lineHeight: 1.55,
                  whiteSpace: 'pre-wrap', wordBreak: 'break-word', margin: 0,
                }}>
                  {JSON.stringify(result._context, null, 2)}
                </pre>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Empty state */}
      {!loading && !result && !error && (
        <div style={{
          padding: '60px 0', textAlign: 'center',
        }}>
          <div className="display" style={{
            color: 'var(--text-dimmer)', fontSize: 28, fontStyle: 'italic',
            marginBottom: 12, opacity: 0.6,
          }}>
            Ask the record a question
          </div>
          <div className="serif" style={{
            color: 'var(--text-dimmer)', fontSize: 14, maxWidth: 480,
            margin: '0 auto', lineHeight: 1.6, opacity: 0.5,
          }}>
            Query by year, country of origin, legislation name, manifest person, decade, or enforcement keyword. The engine cross-references all datasets to produce a synthesis.
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { SynthesisTab });
