// Yield curve module — today vs 1mo ago vs 1yr ago
// Hover any point to see exact yields; toggle overlays on/off

function YieldCurve({ data }) {
  const [hover, setHover] = React.useState(null);
  const [show1m, setShow1m] = React.useState(true);
  const [show1y, setShow1y] = React.useState(true);

  if (!data || !data.tenors) return null;

  // Parse "Apr 29, 2026" → "04/29"
  const MONTHS = {Jan:"01",Feb:"02",Mar:"03",Apr:"04",May:"05",Jun:"06",
                  Jul:"07",Aug:"08",Sep:"09",Oct:"10",Nov:"11",Dec:"12"};
  const parts = data.as_of?.match(/(\w{3}) (\d{1,2}), (\d{4})/);
  const asOfLabel = parts ? `${parts[3]}/${MONTHS[parts[1]]}/${parts[2].padStart(2,"0")}` : data.as_of;

  const W = 800;
  const H = 280;
  const padL = 48, padR = 24, padT = 28, padB = 36;
  const innerW = W - padL - padR;
  const innerH = H - padT - padB;

  const tenors = data.tenors;
  const series = [
    { key: "year_ago",  label: "1Y ago",  data: data.year_ago,  color: "var(--curve-1y)",  dash: "4 4",  visible: show1y },
    { key: "month_ago", label: "1M ago",  data: data.month_ago, color: "var(--curve-1m)",  dash: "2 3",  visible: show1m },
    { key: "today",     label: asOfLabel, data: data.today,     color: "var(--curve-now)", dash: null,   visible: true },
  ];

  // Y range across visible series
  const visible = series.filter((s) => s.visible);
  const allValues = visible.flatMap((s) => tenors.map((t) => s.data?.[t]).filter((v) => v != null));
  const yMin = Math.floor(Math.min(...allValues) * 10) / 10 - 0.1;
  const yMax = Math.ceil(Math.max(...allValues) * 10) / 10 + 0.1;
  const yRange = yMax - yMin;

  const xFor = (i) => padL + (i * innerW) / (tenors.length - 1);
  const yFor = (v) => padT + innerH - ((v - yMin) / yRange) * innerH;

  // Y ticks
  const yTicks = [];
  const tickStep = yRange > 1.5 ? 0.5 : 0.25;
  for (let v = Math.ceil(yMin / tickStep) * tickStep; v <= yMax; v += tickStep) {
    yTicks.push(Number(v.toFixed(2)));
  }

  const pathFor = (s) => {
    const pts = tenors
      .map((t, i) => (s.data?.[t] != null ? `${xFor(i).toFixed(1)},${yFor(s.data[t]).toFixed(1)}` : null))
      .filter(Boolean);
    return pts.length ? "M" + pts.join(" L") : "";
  };

  return (
    <div className="yc">
      <div className="yc-head">
        <div>
          <div className="yc-title">U.S. Treasury Yield Curve</div>
          <div className="yc-sub">As of {data.as_of} · 1M to 30Y</div>
        </div>
        <div className="yc-legend">
          <button
            className={`yc-leg ${show1y ? "on" : "off"}`}
            onClick={() => setShow1y(!show1y)}
            style={{ "--leg-color": "var(--curve-1y)" }}
          >
            <span className="yc-swatch dashed" /> 1Y ago
          </button>
          <button
            className={`yc-leg ${show1m ? "on" : "off"}`}
            onClick={() => setShow1m(!show1m)}
            style={{ "--leg-color": "var(--curve-1m)" }}
          >
            <span className="yc-swatch dotted" /> 1M ago
          </button>
          <div className="yc-leg on" style={{ "--leg-color": "var(--curve-now)" }}>
            <span className="yc-swatch" /> {asOfLabel}
          </div>
        </div>
      </div>

      <div className="yc-chartwrap">
        <svg viewBox={`0 0 ${W} ${H}`} className="yc-chart" preserveAspectRatio="xMidYMid meet">
          {/* Y gridlines */}
          {yTicks.map((v) => (
            <g key={v}>
              <line x1={padL} x2={W - padR} y1={yFor(v)} y2={yFor(v)} className="yc-grid" />
              <text x={padL - 8} y={yFor(v) + 4} className="yc-axis-lab" textAnchor="end">
                {v.toFixed(2)}%
              </text>
            </g>
          ))}

          {/* X labels */}
          {tenors.map((t, i) => (
            <text key={t} x={xFor(i)} y={H - padB + 18} className="yc-axis-lab" textAnchor="middle">
              {t}
            </text>
          ))}

          {/* Curves */}
          {series.filter((s) => s.visible).map((s) => (
            <g key={s.key}>
              <path
                d={pathFor(s)}
                fill="none"
                stroke={s.color}
                strokeWidth="2"
                strokeDasharray={s.dash || undefined}
                strokeLinecap="round"
                strokeLinejoin="round"
              />
              {tenors.map((t, i) => {
                const v = s.data?.[t];
                if (v == null) return null;
                return (
                  <circle
                    key={t}
                    cx={xFor(i)}
                    cy={yFor(v)}
                    r={s.key === "today" ? 4 : 3}
                    fill={s.color}
                    stroke="var(--bg)"
                    strokeWidth={s.key === "today" ? 1.5 : 1}
                  />
                );
              })}
            </g>
          ))}

          {/* Hover hit areas */}
          {tenors.map((t, i) => (
            <rect
              key={t}
              x={xFor(i) - innerW / tenors.length / 2}
              y={padT}
              width={innerW / tenors.length}
              height={innerH}
              fill="transparent"
              onMouseEnter={() => setHover(i)}
              onMouseLeave={() => setHover(null)}
              onTouchStart={() => setHover(i)}
            />
          ))}

          {/* Hover guide */}
          {hover != null && (
            <line
              x1={xFor(hover)} x2={xFor(hover)}
              y1={padT} y2={padT + innerH}
              className="yc-hover-line"
            />
          )}
        </svg>

        {hover != null && (
          <div className="yc-tip" style={{ left: `${(xFor(hover) / W) * 100}%` }}>
            <div className="yc-tip-tenor">{tenors[hover]}</div>
            {series.filter((s) => s.visible).map((s) => (
              <div key={s.key} className="yc-tip-row">
                <span className="yc-tip-dot" style={{ background: s.color }} />
                <span className="yc-tip-lab">{s.label}</span>
                <span className="yc-tip-val">
                  {s.data?.[tenors[hover]] != null ? `${s.data[tenors[hover]].toFixed(2)}%` : "—"}
                </span>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Spread quick reads */}
      <div className="yc-spreads">
        <SpreadCell label="10Y − 2Y" data={data} a="2Y" b="10Y" />
        <SpreadCell label="10Y − 3M" data={data} a="3M" b="10Y" />
        <SpreadCell label="30Y − 5Y" data={data} a="5Y" b="30Y" />
      </div>
    </div>
  );
}

function SpreadCell({ label, data, a, b }) {
  const today = (data.today?.[b] ?? 0) - (data.today?.[a] ?? 0);
  const prior = (data.month_ago?.[b] ?? 0) - (data.month_ago?.[a] ?? 0);
  const delta = today - prior;
  const dir = delta >= 0 ? "up" : "down";
  return (
    <div className="yc-sp">
      <div className="yc-sp-lab">{label}</div>
      <div className={`yc-sp-val ${today >= 0 ? "" : "inv"}`}>
        {today >= 0 ? "+" : ""}{(today * 100).toFixed(0)} bps
      </div>
      <div className={`yc-sp-delta ${dir}`}>
        {delta >= 0 ? "+" : ""}{(delta * 100).toFixed(0)} vs 1M ago
      </div>
    </div>
  );
}

window.YieldCurve = YieldCurve;
