// Hero widgets: price chart + regional heatmap.

// ── Sparkline / area chart ──────────────────────────────────────────────────
function PriceChart({ symbol = 'ALF.PRM' }) {
  const { SERIES, HAY_GRADES } = window.HAYSCOUT_DATA;
  const [active, setActive] = React.useState(symbol);
  const series = SERIES[active] || SERIES['ALF.PRM'];
  const [hover, setHover] = React.useState(null);

  const grade = HAY_GRADES.find((g) => g.sym === active);
  const w = 560, h = 220, padL = 44, padR = 16, padT = 18, padB = 26;
  const min = Math.min(...series), max = Math.max(...series);
  const span = max - min || 1;

  const xAt = (i) => padL + (i / (series.length - 1)) * (w - padL - padR);
  const yAt = (v) => padT + (1 - (v - min) / span) * (h - padT - padB);

  const path = series.map((v, i) => `${i === 0 ? 'M' : 'L'}${xAt(i).toFixed(1)},${yAt(v).toFixed(1)}`).join(' ');
  const area = `${path} L${xAt(series.length - 1).toFixed(1)},${(h - padB).toFixed(1)} L${xAt(0).toFixed(1)},${(h - padB).toFixed(1)} Z`;

  const onMove = (e) => {
    const r = e.currentTarget.getBoundingClientRect();
    const px = ((e.clientX - r.left) / r.width) * w;
    if (px < padL || px > w - padR) { setHover(null); return; }
    const i = Math.round(((px - padL) / (w - padL - padR)) * (series.length - 1));
    setHover({ i, v: series[i] });
  };

  const last = series[series.length - 1];
  const first = series[0];
  const pct = ((last - first) / first) * 100;

  // Y-axis ticks
  const ticks = [0, 0.25, 0.5, 0.75, 1].map((t) => min + span * t);

  const symbols = ['ALF.PRM', 'ALF.SUP', 'GRS.PRM', 'TIM.1ST'];

  return (
    <>
      <style>{`
        .chart-card {
          background: #fbf8ee;
          border: 1px solid var(--line);
          border-radius: var(--r-lg);
          padding: 18px 20px 16px;
          position: relative;
          overflow: hidden;
        }
        .chart-card::after {
          /* corner accent */
          content: ""; position: absolute; right: -40px; top: -40px;
          width: 120px; height: 120px;
          background: radial-gradient(circle, rgba(232,144,32,.15), transparent 70%);
          pointer-events: none;
        }
        .chart-hd { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; }
        .chart-title { font-family: 'JetBrains Mono', monospace; font-size: 11px; font-weight: 600;
          color: var(--ink-3); text-transform: uppercase; letter-spacing: 0.08em; }
        .chart-grade { font-size: 22px; font-weight: 600; color: var(--ink); margin-top: 2px; line-height: 1.1; }
        .chart-price-row { display: flex; align-items: baseline; gap: 10px; margin-top: 8px; }
        .chart-price { font-family: 'JetBrains Mono', monospace; font-size: 28px; font-weight: 600; color: var(--ink);
          font-variant-numeric: tabular-nums; }
        .chart-price-unit { font-size: 12px; color: var(--ink-3); }
        .chart-pct { font-family: 'JetBrains Mono', monospace; font-size: 13px; font-weight: 600;
          padding: 2px 7px; border-radius: 4px;
          font-variant-numeric: tabular-nums; }
        .chart-pct.up { color: var(--green); background: rgba(91, 123, 42, 0.1); }
        .chart-pct.down { color: var(--red); background: rgba(176, 69, 40, 0.1); }
        .chart-tabs {
          display: flex; gap: 2px;
          padding: 3px;
          background: var(--paper-2);
          border-radius: 6px;
        }
        .chart-tabs button {
          font-family: 'JetBrains Mono', monospace; font-size: 10.5px; font-weight: 600;
          padding: 5px 9px; border: 0; background: transparent;
          color: var(--ink-3); border-radius: 4px;
          letter-spacing: 0.04em;
        }
        .chart-tabs button.active { background: var(--ink); color: var(--paper); }
        .chart-svg { display: block; width: 100%; margin-top: 14px; cursor: crosshair; }
        .chart-axis { font-family: 'JetBrains Mono', monospace; font-size: 9.5px; fill: var(--ink-4); }
        .chart-foot { display: flex; justify-content: space-between; align-items: center;
          margin-top: 10px; padding-top: 10px; border-top: 1px dashed var(--line);
          font-family: 'JetBrains Mono', monospace; font-size: 10.5px; color: var(--ink-3); letter-spacing: 0.04em; }
      `}</style>
      <div className="chart-card">
        <div className="chart-hd">
          <div>
            <div className="chart-title">Spot price · 90d</div>
            <div className="chart-grade">{grade.name}</div>
            <div className="chart-price-row">
              <span className="chart-price">${(hover ? hover.v : last).toFixed(2)}</span>
              <span className="chart-price-unit">/ ton FOB</span>
              <span className={'chart-pct ' + (pct >= 0 ? 'up' : 'down')}>
                {pct >= 0 ? '+' : ''}{pct.toFixed(2)}%
              </span>
            </div>
          </div>
          <div className="chart-tabs">
            {symbols.map((s) => (
              <button key={s} className={s === active ? 'active' : ''} onClick={() => setActive(s)}>{s}</button>
            ))}
          </div>
        </div>

        <svg className="chart-svg" viewBox={`0 0 ${w} ${h}`} onMouseMove={onMove} onMouseLeave={() => setHover(null)}>
          <defs>
            <linearGradient id="areaFill" x1="0" x2="0" y1="0" y2="1">
              <stop offset="0%"   stopColor="#c2730b" stopOpacity="0.28" />
              <stop offset="100%" stopColor="#c2730b" stopOpacity="0" />
            </linearGradient>
          </defs>
          {/* y-axis grid */}
          {ticks.map((t, i) => (
            <g key={i}>
              <line x1={padL} x2={w - padR} y1={yAt(t)} y2={yAt(t)} stroke="rgba(45,33,16,0.08)" strokeDasharray="2 3" />
              <text className="chart-axis" x={padL - 6} y={yAt(t) + 3} textAnchor="end">${t.toFixed(0)}</text>
            </g>
          ))}
          {/* x-axis labels */}
          {[0, 30, 60, 89].map((i) => (
            <text key={i} className="chart-axis" x={xAt(i)} y={h - 8} textAnchor="middle">
              {i === 0 ? '90d ago' : i === 89 ? 'today' : `${90 - i}d`}
            </text>
          ))}
          <path d={area} fill="url(#areaFill)" />
          <path d={path} fill="none" stroke="#c2730b" strokeWidth="1.5" strokeLinejoin="round" />
          {hover && (
            <g>
              <line x1={xAt(hover.i)} x2={xAt(hover.i)} y1={padT} y2={h - padB} stroke="var(--ink)" strokeDasharray="2 2" strokeWidth="0.5" />
              <circle cx={xAt(hover.i)} cy={yAt(hover.v)} r="4" fill="var(--paper)" stroke="#c2730b" strokeWidth="1.5" />
            </g>
          )}
        </svg>

        <div className="chart-foot">
          <span>SOURCE · USDA AMS + 1,240 verified loads</span>
          <span>UPDATED 14:32 CT</span>
        </div>
      </div>
    </>
  );
}

// ── Regional demand heatmap ─────────────────────────────────────────────────
function RegionalMap() {
  const { REGIONS } = window.HAYSCOUT_DATA;
  const [hover, setHover] = React.useState(null);

  return (
    <>
      <style>{`
        .map-card {
          background: #fbf8ee;
          border: 1px solid var(--line);
          border-radius: var(--r-lg);
          padding: 18px 20px;
          position: relative;
          overflow: hidden;
        }
        .map-hd { display: flex; justify-content: space-between; align-items: flex-start; }
        .map-title { font-family: 'JetBrains Mono', monospace; font-size: 11px; font-weight: 600;
          color: var(--ink-3); text-transform: uppercase; letter-spacing: 0.08em; }
        .map-sub { font-size: 18px; font-weight: 600; color: var(--ink); margin-top: 2px; }
        .map-legend {
          display: flex; align-items: center; gap: 6px;
          font-family: 'JetBrains Mono', monospace; font-size: 10px;
          color: var(--ink-3); letter-spacing: 0.04em;
        }
        .map-legend-grad {
          width: 80px; height: 8px; border-radius: 2px;
          background: linear-gradient(to right, #efe9d8, #e89020, #8a3d05);
        }
        .map-svg { display: block; width: 100%; margin-top: 6px; aspect-ratio: 16 / 10; }
        .map-dot { cursor: crosshair; transition: r 0.15s; }
        .map-tip {
          position: absolute; pointer-events: none; z-index: 4;
          background: var(--ink); color: var(--paper);
          font-family: 'JetBrains Mono', monospace; font-size: 11px;
          padding: 7px 10px; border-radius: 6px;
          line-height: 1.3; white-space: nowrap;
          transform: translate(-50%, -110%);
        }
        .map-tip-name { font-weight: 600; margin-bottom: 2px; letter-spacing: 0.04em; }
        .map-tip-row { display: flex; justify-content: space-between; gap: 14px; color: rgba(245,241,230,.7); }
        .map-tip-val { color: var(--paper); font-variant-numeric: tabular-nums; }
        .map-foot { display: flex; justify-content: space-between; align-items: center;
          margin-top: 10px; padding-top: 10px; border-top: 1px dashed var(--line);
          font-family: 'JetBrains Mono', monospace; font-size: 10.5px; color: var(--ink-3); letter-spacing: 0.04em; }
      `}</style>
      <div className="map-card">
        <div className="map-hd">
          <div>
            <div className="map-title">Regional demand · last 7d</div>
            <div className="map-sub">Buyer pressure by state</div>
          </div>
          <div className="map-legend">
            <span>LOW</span>
            <span className="map-legend-grad" />
            <span>HIGH</span>
          </div>
        </div>

        <div style={{ position: 'relative' }}>
          <svg className="map-svg" viewBox="0 0 100 62">
            {/* Stylized US footprint — abstracted dots-only, no copyrighted geometry */}
            {Array.from({ length: 14 * 7 }).map((_, i) => {
              const cx = 6 + (i % 14) * 6.5;
              const cy = 8 + Math.floor(i / 14) * 7;
              return <circle key={i} cx={cx} cy={cy} r="0.6" fill="rgba(45,33,16,0.08)" />;
            })}
            {REGIONS.map((r) => {
              const size = 1.2 + r.demand * 2.6;
              const fill = `oklch(${0.84 - r.demand * 0.32} ${0.04 + r.demand * 0.13} 60)`;
              const isHover = hover && hover.code === r.code;
              return (
                <g key={r.code}>
                  <circle
                    className="map-dot"
                    cx={r.x * 0.94 + 3}
                    cy={r.y * 0.85 + 4}
                    r={isHover ? size + 0.5 : size}
                    fill={fill}
                    stroke={isHover ? 'var(--ink)' : 'rgba(255,255,255,0.6)'}
                    strokeWidth={isHover ? 0.4 : 0.25}
                    onMouseEnter={() => setHover(r)}
                    onMouseLeave={() => setHover(null)}
                  />
                  {r.demand > 0.75 && (
                    <text x={r.x * 0.94 + 3} y={r.y * 0.85 + 4 + 0.6}
                          fontSize="1.4" fontWeight="700"
                          fill="white" textAnchor="middle"
                          fontFamily="'JetBrains Mono', monospace"
                          style={{ pointerEvents: 'none' }}>
                      {r.code}
                    </text>
                  )}
                </g>
              );
            })}
          </svg>
          {hover && (
            <div className="map-tip" style={{
              left: `calc(${hover.x * 0.94 + 3}% )`,
              top: `${hover.y * 0.85 + 4}%`,
            }}>
              <div className="map-tip-name">{hover.name.toUpperCase()}</div>
              <div className="map-tip-row"><span>SPOT</span> <span className="map-tip-val">${hover.price}/t</span></div>
              <div className="map-tip-row"><span>7D CHG</span>
                <span className="map-tip-val" style={{ color: hover.chg >= 0 ? '#aedc6f' : '#ff9a7a' }}>
                  {hover.chg >= 0 ? '+' : ''}{hover.chg.toFixed(1)}%
                </span>
              </div>
              <div className="map-tip-row"><span>DEMAND</span> <span className="map-tip-val">{(hover.demand * 100).toFixed(0)}</span></div>
            </div>
          )}
        </div>

        <div className="map-foot">
          <span>{REGIONS.length} STATES TRACKED</span>
          <span>14,802 VERIFIED LOADS · 90D</span>
        </div>
      </div>
    </>
  );
}

window.PriceChart = PriceChart;
window.RegionalMap = RegionalMap;
