// 05 · The Names — the human layer. The manifest aesthetic made literal.

function TabNames() {
  const [search, setSearch] = React.useState('');
  const [scrollPaused, setScrollPaused] = React.useState(false);
  const scrollRef = React.useRef(null);

  const records = window.manifestFull;

  const filtered = React.useMemo(() => {
    if (!search) return records;
    const q = search.toLowerCase();
    return records.filter(r =>
      r.name.toLowerCase().includes(q) ||
      r.origin.toLowerCase().includes(q) ||
      r.year.toString().includes(q) ||
      r.destination.toLowerCase().includes(q)
    );
  }, [search, records]);

  // Auto-scroll effect
  React.useEffect(() => {
    if (scrollPaused || search) return;
    const el = scrollRef.current;
    if (!el) return;
    const interval = setInterval(() => {
      el.scrollTop += 1;
      if (el.scrollTop >= el.scrollHeight - el.clientHeight) {
        el.scrollTop = 0;
      }
    }, 60);
    return () => clearInterval(interval);
  }, [scrollPaused, search]);

  return (
    <div style={{ padding: '32px 56px 80px' }}>
      <Eyebrow id="05 · THE NAMES"
        title="The human layer. The manifest aesthetic made literal."
        right="National Archives · Ellis Island · 1892–1957" />

      {/* Search bar */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24,
        border: '1px solid #2A2218', background: '#1E1810', padding: '12px 16px',
      }}>
        <span className="mono" style={{ color: '#5A4E3A', fontSize: 10, letterSpacing: 0.2, textTransform: 'uppercase' }}>
          SEARCH
        </span>
        <input
          type="text"
          value={search}
          onChange={e => setSearch(e.target.value)}
          placeholder="Surname, country, year, or destination…"
          className="mono"
          style={{
            flex: 1, background: 'transparent', border: 'none', outline: 'none',
            color: '#D4C8B8', fontSize: 13, letterSpacing: 0.05,
            fontFamily: "'Space Mono', monospace",
          }}
        />
        {search && (
          <span className="mono" style={{ color: '#C9A84C', fontSize: 10, cursor: 'pointer' }}
            onClick={() => setSearch('')}>
            {filtered.length} results {'×'}
          </span>
        )}
      </div>

      {/* Manifest display */}
      <div style={{ border: '1px solid #2A2218', background: '#F2EBD9' }}>
        {/* Header row */}
        <div style={{
          display: 'grid', gridTemplateColumns: '2.5fr 1.2fr 0.5fr 0.6fr 1.2fr',
          padding: '10px 12px', borderBottom: '2px solid #C9A84C',
        }}>
          <span className="mono" style={{ color: '#100C08', fontSize: 10, letterSpacing: 0.2, textTransform: 'uppercase', fontWeight: 700 }}>Name</span>
          <span className="mono" style={{ color: '#100C08', fontSize: 10, letterSpacing: 0.2, textTransform: 'uppercase', fontWeight: 700 }}>Country of Origin</span>
          <span className="mono" style={{ color: '#100C08', fontSize: 10, letterSpacing: 0.2, textTransform: 'uppercase', fontWeight: 700, textAlign: 'right' }}>Age</span>
          <span className="mono" style={{ color: '#100C08', fontSize: 10, letterSpacing: 0.2, textTransform: 'uppercase', fontWeight: 700, textAlign: 'right' }}>Year</span>
          <span className="mono" style={{ color: '#100C08', fontSize: 10, letterSpacing: 0.2, textTransform: 'uppercase', fontWeight: 700, textAlign: 'right' }}>Destination</span>
        </div>

        {/* Scrolling records */}
        <div ref={scrollRef}
          onMouseEnter={() => setScrollPaused(true)}
          onMouseLeave={() => setScrollPaused(false)}
          style={{
            maxHeight: 520, overflowY: 'auto', overflowX: 'hidden',
            background: `
              repeating-linear-gradient(
                to bottom,
                transparent 0px,
                transparent 27px,
                rgba(201,168,76,0.12) 27px,
                rgba(201,168,76,0.12) 28px
              )
            `,
          }}>
          {filtered.map((r, i) => (
            <div key={i} style={{
              display: 'grid', gridTemplateColumns: '2.5fr 1.2fr 0.5fr 0.6fr 1.2fr',
              padding: '5px 12px', height: 28,
              background: search && r.name.toLowerCase().includes(search.toLowerCase())
                ? 'rgba(201,168,76,0.15)'
                : (i % 2 === 0 ? 'rgba(16,12,8,0.02)' : 'transparent'),
            }}>
              <span className="mono" style={{ color: '#100C08', fontSize: 12 }}>{r.name}</span>
              <span className="mono" style={{ color: '#3A3020', fontSize: 11, fontVariant: 'all-small-caps', letterSpacing: 0.1 }}>{r.origin}</span>
              <span className="mono" style={{ color: '#3A3020', fontSize: 11, textAlign: 'right' }}>{r.age}</span>
              <span className="mono" style={{ color: '#5A4E1A', fontSize: 11, textAlign: 'right', fontWeight: 700 }}>{r.year}</span>
              <span className="mono" style={{ color: '#3A3020', fontSize: 11, textAlign: 'right' }}>{r.destination}</span>
            </div>
          ))}
        </div>
      </div>

      <div className="mono" style={{ color: '#5A4E3A', fontSize: 10, marginTop: 12, textAlign: 'center', letterSpacing: 0.15 }}>
        ILLUSTRATIVE SAMPLE {'·'} {records.length.toLocaleString()} RECORDS SHOWN {'·'} FULL DATASET: 10,000 MANIFEST ENTRIES FROM NATIONAL ARCHIVES
      </div>

      {/* Name Diffusion section */}
      <NameDiffusionPanel />
    </div>
  );
}

// Name Diffusion animated map panel
function NameDiffusionPanel() {
  const clusters = window.nameDiffusion;
  const [activeCluster, setActiveCluster] = React.useState(0);
  const [activeDecade, setActiveDecade] = React.useState(0);
  const [playing, setPlaying] = React.useState(false);

  const cluster = clusters[activeCluster];
  const decadeKeys = Object.keys(cluster.decades).sort();

  React.useEffect(() => { setActiveDecade(0); }, [activeCluster]);

  React.useEffect(() => {
    if (!playing) return;
    const t = setInterval(() => {
      setActiveDecade(i => {
        if (i >= decadeKeys.length - 1) { setPlaying(false); return i; }
        return i + 1;
      });
    }, 1200);
    return () => clearInterval(t);
  }, [playing, decadeKeys.length]);

  const currentDecade = decadeKeys[activeDecade];
  const stateData = cluster.decades[currentDecade] || {};

  // Reverse lookup: state abbrev → FIPS
  const ABBREV_TO_FIPS = {};
  Object.entries(window.STATE_FIPS).forEach(([fips, abbr]) => ABBREV_TO_FIPS[abbr] = fips);

  return (
    <div style={{ marginTop: 40 }}>
      <HRule>NAME DIFFUSION MODEL</HRule>
      <div style={{ border: '1px solid #2A2218', background: 'rgba(30,24,16,0.3)', padding: '24px 28px', marginTop: 16 }}>
        <div className="serif" style={{ color: '#D4C8B8', fontSize: 16, lineHeight: 1.6, marginBottom: 20 }}>
          How immigrant communities became American communities. Select a surname cluster and watch it spread across the map over decades.
        </div>

        {/* Cluster selector */}
        <div style={{ display: 'flex', gap: 1, marginBottom: 20, background: '#2A2218', flexWrap: 'wrap' }}>
          {clusters.map((c, i) => (
            <button key={i} onClick={() => setActiveCluster(i)} className="mono" style={{
              background: activeCluster === i ? '#C9A84C' : '#1E1810',
              color: activeCluster === i ? '#100C08' : '#8A7E6A',
              border: 'none', padding: '8px 14px', cursor: 'pointer',
              fontSize: 10, letterSpacing: 0.15, textTransform: 'uppercase',
              fontFamily: "'Space Mono', monospace", fontWeight: activeCluster === i ? 700 : 400,
            }}>
              {c.label}
            </button>
          ))}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 20 }}>
          {/* Map */}
          <div>
            <USMapSVG
              width={640} height={400} level="states"
              colorFn={(fips) => {
                const abbr = window.STATE_FIPS[fips];
                if (!abbr || !stateData[abbr]) return '#1E1810';
                const v = stateData[abbr];
                return `oklch(${(0.25 + v * 0.45).toFixed(3)} ${(0.04 + v * 0.15).toFixed(3)} 85)`;
              }}
            />
            {/* Decade scrubber */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 8 }}>
              <button onClick={() => { setActiveDecade(0); setPlaying(true); }} className="mono" style={{
                background: 'transparent', color: '#C9A84C', border: '1px solid #C9A84C',
                padding: '5px 10px', fontSize: 10, cursor: 'pointer', fontFamily: "'Space Mono', monospace",
              }}>
                {playing ? '■ PAUSE' : '▶ PLAY'}
              </button>
              <div style={{ flex: 1, display: 'flex', gap: 2 }}>
                {decadeKeys.map((d, i) => (
                  <button key={d} onClick={() => { setActiveDecade(i); setPlaying(false); }} style={{
                    flex: 1, height: 24, background: i === activeDecade ? '#C9A84C' : '#2A2218',
                    border: 'none', cursor: 'pointer', position: 'relative',
                  }}>
                    <span className="mono" style={{
                      position: 'absolute', bottom: -16, left: '50%', transform: 'translateX(-50%)',
                      color: i === activeDecade ? '#C9A84C' : '#5A4E3A', fontSize: 9,
                    }}>{d}s</span>
                  </button>
                ))}
              </div>
              <span className="mono" style={{ color: '#C9A84C', fontSize: 16, fontWeight: 700, minWidth: 50 }}>{currentDecade}s</span>
            </div>
          </div>

          {/* Sidebar */}
          <div>
            <div style={{ border: '1px solid #2A2218', background: '#1E1810', padding: '16px 20px' }}>
              <Tick color="#C9A84C">{'▌'} {cluster.label.toUpperCase()}</Tick>
              <div className="mono" style={{ color: '#8A7E6A', fontSize: 11, marginTop: 8 }}>
                Origin: <span style={{ fontVariant: 'all-small-caps', color: '#D4C8B8' }}>{cluster.origin}</span>
              </div>
              <div className="mono" style={{ color: '#8A7E6A', fontSize: 11, marginTop: 4 }}>
                Peak arrival: {cluster.peak}
              </div>
              <div className="mono" style={{ color: '#8A7E6A', fontSize: 11, marginTop: 4 }}>
                Examples: {cluster.examples.join(', ')}
              </div>
            </div>

            {/* State concentrations for current decade */}
            <div style={{ border: '1px solid #2A2218', background: '#1E1810', padding: '16px 20px', marginTop: 8 }}>
              <Tick color="#5A4E3A">{'▌'} {currentDecade}s CONCENTRATION</Tick>
              <div style={{ marginTop: 8 }}>
                {Object.entries(stateData)
                  .sort((a, b) => b[1] - a[1])
                  .slice(0, 8)
                  .map(([st, v]) => (
                    <div key={st} style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 4 }}>
                      <span className="mono" style={{ color: '#D4C8B8', fontSize: 11, width: 24 }}>{st}</span>
                      <div style={{ flex: 1, height: 5, background: '#2A2218' }}>
                        <div style={{ width: `${v * 100}%`, height: '100%', background: '#C9A84C', transition: 'width 400ms' }} />
                      </div>
                      <span className="mono" style={{ color: '#8A7E6A', fontSize: 9, width: 28, textAlign: 'right' }}>{Math.round(v * 100)}%</span>
                    </div>
                  ))}
              </div>
            </div>
            <div style={{ marginTop: 8 }}><Confidence level="candidate" /></div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { TabNames, NameDiffusionPanel });
