// 03 · The Flow — where people came from, where they went, and how that changed.
// Uses d3-sankey for proper flow layout.

function TabFlow() {
  const [decade, setDecade] = React.useState('2010s');
  const decades = ['1900s', '1960s', '1980s', '2010s'];
  const flow = window.sankeyData[decade];
  const [hover, setHover] = React.useState(null);
  const [mode, setMode] = React.useState('sankey'); // 'sankey' | 'map'

  const W = 960, H = 520, margin = { l: 120, r: 120, t: 10, b: 10 };

  // Country-to-region helper
  const countryRegion = (name) => {
    if (['MEXICO','CUBA','EL SALVADOR','DOMINICAN REP.','HAITI','GUATEMALA','HONDURAS','COLOMBIA','JAMAICA','BRAZIL'].includes(name)) return 'Latin America';
    if (['CHINA','INDIA','PHILIPPINES','KOREA','VIETNAM','JAPAN','PAKISTAN','BANGLADESH','IRAN','TAIWAN'].includes(name)) return 'Asia';
    if (['ITALY','RUSSIA','AUSTRIA-HUNGARY','GREECE','ROMANIA','POLAND','SERBIA','CROATIA'].includes(name)) return 'Southern/Eastern Europe';
    if (['GREAT BRITAIN','IRELAND','GERMANY','SCANDINAVIA','FRANCE','NETHERLANDS','NORWAY','SWEDEN','DENMARK','SCOTLAND','WALES','CANADA'].includes(name)) return 'Northern/Western Europe';
    return 'Other';
  };

  // Build sankey layout
  const { nodes, links, paths } = React.useMemo(() => {
    const allNames = [...new Set([...flow.origins, ...flow.destinations])];
    const nodeMap = {};
    const nodeArr = allNames.map((name, i) => { nodeMap[name] = i; return { name }; });
    const linkArr = flow.flows.map(([s, t, v]) => ({
      source: nodeMap[s], target: nodeMap[t], value: v,
    }));

    // Use d3-sankey if available
    if (window.d3 && window.d3.sankey) {
      const layout = window.d3.sankey()
        .nodeId(d => d.index)
        .nodeWidth(14)
        .nodePadding(12)
        .nodeAlign(window.d3.sankeyJustify)
        .extent([[margin.l, margin.t], [W - margin.r, H - margin.b]]);

      const graph = layout({
        nodes: nodeArr.map((n, i) => ({ ...n, index: i })),
        links: linkArr.map(l => ({ ...l })),
      });

      const linkPath = window.d3.sankeyLinkHorizontal();
      const pathData = graph.links.map(l => ({
        d: linkPath(l),
        width: Math.max(1, l.width),
        source: allNames[l.source.index],
        target: allNames[l.target.index],
        value: l.value,
        color: window.regionColor(countryRegion(allNames[l.source.index])),
      }));

      return { nodes: graph.nodes, links: graph.links, paths: pathData };
    }

    // Fallback: manual layout (same as before but cleaner)
    const originNodes = flow.origins;
    const destNodes = flow.destinations;
    const originTotals = {}, destTotals = {};
    flow.flows.forEach(([s, t, v]) => {
      originTotals[s] = (originTotals[s] || 0) + v;
      destTotals[t] = (destTotals[t] || 0) + v;
    });
    const total = Object.values(originTotals).reduce((a, b) => a + b, 0);
    const usableH = H - margin.t - margin.b;

    let oy = margin.t;
    const oPos = originNodes.map(n => {
      const h = Math.max(8, (originTotals[n] / total) * (usableH - 6 * originNodes.length));
      const p = { name: n, x0: margin.l, x1: margin.l + 14, y0: oy, y1: oy + h };
      oy += h + 6;
      return p;
    });
    let dy = margin.t;
    const dPos = destNodes.map(n => {
      const h = Math.max(8, ((destTotals[n] || 1) / total) * (usableH - 6 * destNodes.length));
      const p = { name: n, x0: W - margin.r - 14, x1: W - margin.r, y0: dy, y1: dy + h };
      dy += h + 6;
      return p;
    });

    const oOffsets = {}, dOffsets = {};
    oPos.forEach(o => oOffsets[o.name] = 0);
    dPos.forEach(d => dOffsets[d.name] = 0);

    const pathData = flow.flows.map(([s, t, v]) => {
      const src = oPos.find(o => o.name === s);
      const dst = dPos.find(d => d.name === t);
      if (!src || !dst) return null;
      const sh = (v / originTotals[s]) * (src.y1 - src.y0);
      const dh = (v / destTotals[t]) * (dst.y1 - dst.y0);
      const sy = src.y0 + oOffsets[s] + sh / 2;
      const dy2 = dst.y0 + dOffsets[t] + dh / 2;
      oOffsets[s] += sh;
      dOffsets[t] += dh;
      const sx = src.x1, dx = dst.x0;
      const cx = (sx + dx) / 2;
      return {
        d: `M${sx},${sy - sh/2} C${cx},${sy - sh/2} ${cx},${dy2 - dh/2} ${dx},${dy2 - dh/2} L${dx},${dy2 + dh/2} C${cx},${dy2 + dh/2} ${cx},${sy + sh/2} ${sx},${sy + sh/2} Z`,
        width: Math.max(1, sh),
        source: s, target: t, value: v,
        color: window.regionColor(countryRegion(s)),
      };
    }).filter(Boolean);

    return { nodes: [...oPos, ...dPos], links: [], paths: pathData };
  }, [decade]);

  // Determine if using d3-sankey or fallback
  const usingD3 = !!(window.d3 && window.d3.sankey);

  return (
    <div style={{ padding: '32px 56px 80px' }}>
      <Eyebrow id="03 · THE FLOW"
        title="Where people came from, where they went, and how that changed."
        right="DHS Yearbook · State settlement data" />

      {/* Mode + decade selectors */}
      <div style={{ display: 'flex', gap: 16, marginBottom: 24, alignItems: 'center' }}>
        <div style={{ display: 'flex', gap: 1, background: '#2A2218', border: '1px solid #2A2218' }}>
          {[{ id: 'sankey', label: 'Flow diagram' }, { id: 'map', label: 'Settlement map' }].map(m => (
            <button key={m.id} onClick={() => setMode(m.id)} className="mono" style={{
              background: mode === m.id ? '#C9A84C' : '#1E1810',
              color: mode === m.id ? '#100C08' : '#8A7E6A',
              border: 'none', padding: '10px 16px', cursor: 'pointer',
              fontSize: 11, letterSpacing: 0.2, textTransform: 'uppercase',
              fontFamily: "'Space Mono', monospace", fontWeight: mode === m.id ? 700 : 400,
            }}>
              {m.label}
            </button>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 1, background: '#2A2218', border: '1px solid #2A2218' }}>
          {decades.map(d => (
            <button key={d} onClick={() => setDecade(d)} className="mono" style={{
              background: decade === d ? '#C9A84C' : '#1E1810',
              color: decade === d ? '#100C08' : '#8A7E6A',
              border: 'none', padding: '10px 22px', cursor: 'pointer',
              fontSize: 12, letterSpacing: 0.2, textTransform: 'uppercase',
              fontFamily: "'Space Mono', monospace", fontWeight: decade === d ? 700 : 400,
            }}>
              {d}
            </button>
          ))}
        </div>
      </div>

      {mode === 'sankey' ? (
      <div style={{ display: 'grid', gridTemplateColumns: '2.2fr 1fr', gap: 24 }}>
        {/* Sankey diagram */}
        <div style={{ border: '1px solid #2A2218', background: 'rgba(30,24,16,0.3)', padding: '18px 24px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
            <span className="serif" style={{ fontSize: 19, color: '#D4C8B8' }}>
              Migration flows {'—'} {decade}
            </span>
            <Confidence level="candidate" />
          </div>

          <svg width={W} height={H} style={{ display: 'block' }}>
            {paths.map((f, i) => (
              <path key={i} d={f.d}
                fill={f.color}
                opacity={hover ? (hover === f.source || hover === f.target ? 0.65 : 0.08) : 0.35}
                stroke={f.color} strokeWidth="0.5"
                onMouseEnter={() => setHover(f.source)}
                onMouseLeave={() => setHover(null)}
                style={{ cursor: 'pointer', transition: 'opacity 200ms' }}
              />
            ))}
            {(usingD3 ? nodes : nodes).map((n, i) => {
              const isOrigin = n.x0 < W / 2;
              const label = n.name || '';
              return (
                <g key={i}>
                  <rect x={n.x0} y={n.y0} width={n.x1 - n.x0} height={n.y1 - n.y0}
                    fill={isOrigin ? window.regionColor(countryRegion(label)) : '#8A7E6A'}
                    opacity="0.9" />
                  <text
                    x={isOrigin ? n.x0 - 6 : n.x1 + 6}
                    y={(n.y0 + n.y1) / 2 + 3.5}
                    textAnchor={isOrigin ? 'end' : 'start'}
                    className="mono" fill={hover === label ? '#F2EBD9' : '#D4C8B8'}
                    fontSize="10.5" fontFamily="Space Mono"
                    style={{ fontVariant: isOrigin ? 'all-small-caps' : 'normal', fontWeight: hover === label ? 700 : 400 }}>
                    {label}
                  </text>
                </g>
              );
            })}
          </svg>
        </div>

        {/* Sidebar */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{ border: '1px solid #2A2218', background: 'rgba(30,24,16,0.5)', padding: '20px 24px' }}>
            <Tick color="#C9A84C">{'▌'} {decade.toUpperCase()}</Tick>
            <div className="serif" style={{ color: '#D4C8B8', fontSize: 15, marginTop: 12, lineHeight: 1.6 }}>
              {decade === '1900s' && 'The fat flows come from Italy and Russia into New York and Pennsylvania. Southern and Eastern Europe dominates. The peak year is 1907: 1,285,349 arrivals.'}
              {decade === '1960s' && 'The transition decade. Cuba sends refugees to Florida. Mexico begins its rise as the dominant origin. Europe is fading. The Philippines appears for the first time.'}
              {decade === '1980s' && 'The color has shifted entirely. Mexico, Philippines, Korea, China, Vietnam, India. The flows go to California and Texas, not New York. The reopening is complete.'}
              {decade === '2010s' && 'The flows come from everywhere into everywhere. Mexico remains the largest single origin but its share is declining. India and China are rising. The map is global.'}
            </div>
          </div>

          {hover && (
            <div style={{ border: '1px solid #2A2218', background: 'rgba(30,24,16,0.5)', padding: '20px 24px', animation: 'fadeUp 200ms ease' }}>
              <span className="mono" style={{ color: window.regionColor(countryRegion(hover)), fontSize: 14, fontWeight: 700, fontVariant: 'all-small-caps' }}>{hover}</span>
              <div style={{ marginTop: 10 }}>
                {flow.flows.filter(f => f[0] === hover).map(([s, t, v], i) => (
                  <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', borderBottom: '1px solid #1A1510' }}>
                    <span className="mono" style={{ color: '#8A7E6A', fontSize: 11 }}>{t}</span>
                    <span className="mono" style={{ color: '#D4C8B8', fontSize: 11, fontWeight: 700 }}>{v}k</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          <div style={{ border: '1px solid #2A2218', background: 'rgba(30,24,16,0.5)', padding: '20px 24px' }}>
            <Tick color="#C9A84C">{'▌'} M1: FLOW PREDICTION MODEL</Tick>
            <div className="serif" style={{ color: '#8A7E6A', fontSize: 13, marginTop: 10, lineHeight: 1.5 }}>
              SHAP feature importance for predicting flow volume.
            </div>
            <div style={{ marginTop: 12 }}>
              {[
                ['Existing diaspora', 0.34],
                ['US GDP growth', 0.22],
                ['Source instability', 0.19],
                ['Legislation regime', 0.15],
                ['Distance', 0.10],
              ].map(([feat, imp]) => (
                <div key={feat} style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6 }}>
                  <div style={{ flex: 1 }}>
                    <span className="mono" style={{ color: '#8A7E6A', fontSize: 10 }}>{feat}</span>
                  </div>
                  <div style={{ width: 120, height: 6, background: '#1A1510', position: 'relative' }}>
                    <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: `${imp * 100}%`, background: '#C9A84C' }} />
                  </div>
                  <span className="mono" style={{ color: '#C9A84C', fontSize: 10, width: 30, textAlign: 'right' }}>{Math.round(imp * 100)}%</span>
                </div>
              ))}
            </div>
            <div style={{ marginTop: 10 }}><Confidence level="candidate" /></div>
          </div>
        </div>
      </div>
      ) : (
      /* MAP MODE — state-level settlement choropleth */
      <div>
        <div style={{ border: '1px solid #2A2218', background: 'rgba(30,24,16,0.3)', padding: '18px 24px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
            <span className="serif" style={{ fontSize: 19, color: '#D4C8B8' }}>
              Immigrant settlement by state {'—'} {decade}
            </span>
            <Confidence level="candidate" />
          </div>
          <USMapSVG
            width={960} height={580} level="states"
            colorFn={(fips) => {
              // Color states based on destination volume in this decade's flow data
              const st = window.STATE_FIPS[fips];
              if (!st) return '#1E1810';
              const stateName = {
                'CA':'California','NY':'New York','TX':'Texas','FL':'Florida',
                'IL':'Illinois','PA':'Pennsylvania','NJ':'New Jersey','MA':'Massachusetts',
                'OH':'Ohio','VA':'Virginia','GA':'Georgia','WA':'Washington',
                'MN':'Minnesota',
              }[st];
              if (!stateName) return '#1E1810';
              const total = flow.flows.filter(f => f[1] === stateName).reduce((s, f) => s + f[2], 0);
              const maxDest = Math.max(...flow.destinations.map(d =>
                flow.flows.filter(f => f[1] === d).reduce((s, f) => s + f[2], 0)
              ));
              if (total === 0) return '#1E1810';
              const t = total / maxDest;
              return `oklch(${(0.25 + t * 0.40).toFixed(3)} ${(0.04 + t * 0.14).toFixed(3)} 85)`;
            }}
          />
        </div>
        <div className="mono" style={{ color: '#5A4E3A', fontSize: 10, marginTop: 8, textAlign: 'center' }}>
          Darker gold = higher immigrant settlement volume. Based on DHS Yearbook destination state data.
        </div>
      </div>
      )}

      {/* Region legend */}
      <div style={{ display: 'flex', gap: 24, marginTop: 16, justifyContent: 'center' }}>
        {Object.entries(window.REGION_COLORS).map(([region, color]) => (
          <div key={region} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 10, height: 10, background: color, borderRadius: 1 }} />
            <span className="mono" style={{ color: '#8A7E6A', fontSize: 10 }}>{region}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { TabFlow });
