/* Desktop · Predictive Yield Ledger */

function DesktopLedger() {
  const { alertState } = useGA();
  const [selPlot, setSelPlot] = React.useState('K3-B');

  const plots = [
    { id: 'K3-A', name: 'North Slope',   crop: 'Saperavi', area: '1.2 ha', yieldF: 7.1, yieldA: 6.4, qual: 'A+', confidence: 92, harvest: 'Sep 18 — 24', dir: 'up' },
    { id: 'K3-B', name: 'Lower Ridge',   crop: 'Saperavi', area: '1.4 ha', yieldF: alertState === 'frost' ? 5.2 : 6.0, yieldA: 6.4, qual: alertState === 'frost' ? 'A' : 'A+', confidence: 78, harvest: 'Sep 21 — 27', dir: 'down', risk: true },
    { id: 'K3-C', name: 'South Terrace', crop: 'Saperavi', area: '1.0 ha', yieldF: 6.8, yieldA: 6.4, qual: 'A+', confidence: 89, harvest: 'Sep 16 — 22', dir: 'up' },
    { id: 'K3-D', name: 'East Block',    crop: 'Saperavi', area: '1.2 ha', yieldF: alertState === 'drought' ? 4.4 : 5.6, yieldA: 6.4, qual: alertState === 'drought' ? 'B' : 'A', confidence: 71, harvest: 'Sep 24 — 30', dir: 'down', risk: alertState !== 'calm' },
  ];

  return (
    <DesktopShell active="ledger" kicker="K3 · KAKHETI"
      breadcrumb={['Saperavi K-3', 'Yield Ledger', 'Season 2026']}
      right={
        <>
          <Pill color="ghost" size="sm">SEASON · 2026</Pill>
          <Pill color="ghost" size="sm">EXPORT XBRL</Pill>
        </>
      }>
      <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 18, height: 'calc(100% - 0px)' }}>
        {/* Top stats */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12 }}>
          <KPICard k="FORECAST · TOTAL" v="30.7" suffix="tonnes" spark={[28,28,29,29,30,30,30,31,30.7]} c="yellow" big />
          <KPICard k="VS 5-YR AVG" v={`+${alertState === 'calm' ? 7.4 : 1.2}`} suffix="%" spark={[5,5.5,6,6.5,7,7,7.4]} c="green" />
          <KPICard k="GRADE · MEAN" v="A+" suffix="" spark={[3,3,3.2,3.5,3.7,4,4]} c="yellow" />
          <KPICard k="REVENUE EST" v="₾312k" suffix="GEL" spark={[280,290,295,300,310,308,312]} c="ink" />
          <KPICard k="HARVEST · MID" v="Sep 21" suffix="±3 days" spark={[15,16,18,19,20,21,21]} c="ink" />
        </div>

        {/* Main: table + detail */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18, flex: 1, minHeight: 0 }}>
          <DPanel
            kicker="LEDGER · SEASON 2026"
            title="Yield Forecast · per Plot"
            subtitle="AI-driven forecast vs historical · click to drill"
            right={<Pill color="ghost" size="sm">SORT · CONFIDENCE</Pill>}
            padBody={0}
            style={{ minHeight: 0 }}>
            <LedgerTable plots={plots} selected={selPlot} onSelect={setSelPlot} />
          </DPanel>

          <DPanel
            kicker={`DETAIL · PLOT ${selPlot}`}
            title={plots.find(p => p.id === selPlot)?.name + ' · Forecast Distribution'}
            subtitle="Monte Carlo · 10,000 runs over weather × soil scenarios"
            style={{ minHeight: 0 }}>
            <ForecastDetail plot={plots.find(p => p.id === selPlot)} alertState={alertState} />
          </DPanel>
        </div>
      </div>
    </DesktopShell>
  );
}

function LedgerTable({ plots, selected, onSelect }) {
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* header row */}
      <div style={{
        display: 'grid', gridTemplateColumns: '90px 1.4fr 0.8fr 0.7fr 0.7fr 0.9fr 1fr',
        gap: 12, padding: '11px 18px',
        background: 'var(--bg-3)',
        borderBottom: '1px solid var(--line-2)',
        fontFamily: 'var(--f-mono)', fontSize: 9.5, fontWeight: 600,
        letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-3)',
      }}>
        <span>Plot</span><span>Zone · area</span><span>Yield · t/ha</span>
        <span>vs 5y</span><span>Grade</span><span>Confidence</span><span>Harvest</span>
      </div>
      <div style={{ flex: 1, overflow: 'auto' }} className="ga-scroll">
        {plots.map((p, i) => {
          const isSel = p.id === selected;
          const delta = p.yieldF - p.yieldA;
          return (
            <div key={p.id} onClick={() => onSelect(p.id)} style={{
              display: 'grid', gridTemplateColumns: '90px 1.4fr 0.8fr 0.7fr 0.7fr 0.9fr 1fr',
              gap: 12, padding: '16px 18px', alignItems: 'center',
              cursor: 'pointer',
              background: isSel ? 'rgba(255,214,10,0.06)' : 'transparent',
              borderLeft: `2px solid ${isSel ? 'var(--yellow)' : 'transparent'}`,
              borderBottom: '1px solid var(--line)',
            }}>
              <span className="ga-mono" style={{ fontWeight: 600, fontSize: 12,
                color: isSel ? 'var(--yellow)' : 'var(--ink)' }}>{p.id}</span>
              <div>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{p.name}</div>
                <div style={{ fontFamily: 'var(--f-mono)', fontSize: 10, color: 'var(--ink-3)', marginTop: 2 }}>
                  {p.crop} · {p.area}
                </div>
              </div>
              <div className="ga-mono" style={{ fontSize: 16, fontWeight: 600,
                color: p.risk ? 'var(--amber)' : 'var(--ink)' }}>{p.yieldF}</div>
              <div className="ga-mono" style={{ fontSize: 12,
                color: delta >= 0 ? 'var(--green)' : 'var(--amber)' }}>
                {delta >= 0 ? '+' : ''}{delta.toFixed(1)}
              </div>
              <span style={{
                display: 'inline-block',
                padding: '3px 7px', borderRadius: 3,
                background: p.qual === 'A+' ? 'rgba(255,214,10,0.12)' : p.qual === 'A' ? 'rgba(67,214,122,0.10)' : 'rgba(255,165,0,0.10)',
                color: p.qual === 'A+' ? 'var(--yellow)' : p.qual === 'A' ? 'var(--green)' : 'var(--amber)',
                fontFamily: 'var(--f-mono)', fontSize: 11, fontWeight: 600, width: 'fit-content',
              }}>{p.qual}</span>
              <div>
                <div style={{ position: 'relative', height: 5, background: 'var(--bg-3)', borderRadius: 3 }}>
                  <div style={{ position: 'absolute', inset: 0, width: `${p.confidence}%`,
                    background: p.confidence > 85 ? 'var(--green)' : p.confidence > 75 ? 'var(--yellow)' : 'var(--amber)',
                    borderRadius: 3 }} />
                </div>
                <span className="ga-mono" style={{ fontSize: 10.5, color: 'var(--ink-3)', marginTop: 4, display: 'inline-block' }}>{p.confidence}%</span>
              </div>
              <div className="ga-mono" style={{ fontSize: 11, color: 'var(--ink-2)' }}>{p.harvest}</div>
            </div>
          );
        })}
        {/* total row */}
        <div style={{
          display: 'grid', gridTemplateColumns: '90px 1.4fr 0.8fr 0.7fr 0.7fr 0.9fr 1fr',
          gap: 12, padding: '14px 18px', alignItems: 'center',
          background: 'var(--bg-3)',
          borderTop: '1px solid var(--line-2)',
          fontFamily: 'var(--f-mono)', fontSize: 11, fontWeight: 600,
        }}>
          <span style={{ color: 'var(--yellow)' }}>K3 · TOTAL</span>
          <span style={{ color: 'var(--ink-2)' }}>4 plots · 4.8 ha</span>
          <span className="ga-mono" style={{ fontSize: 16, color: 'var(--yellow)' }}>30.7</span>
          <span className="ga-mono" style={{ color: 'var(--green)' }}>+1.2</span>
          <span style={{ color: 'var(--yellow)' }}>A+</span>
          <span style={{ color: 'var(--ink-2)' }}>82.5%</span>
          <span style={{ color: 'var(--ink-2)' }}>Sep 16 — 30</span>
        </div>
      </div>
    </div>
  );
}

function ForecastDetail({ plot, alertState }) {
  // Bell curve · monte carlo distribution
  const w = 360, h = 180;
  // make a gaussian-ish curve
  const mu = plot.yieldF, sigma = plot.risk ? 0.85 : 0.45;
  const xs = [];
  for (let i = 0; i <= 60; i++) {
    const x = mu - 3*sigma + (i/60)*6*sigma;
    const y = Math.exp(-0.5 * Math.pow((x - mu) / sigma, 2));
    xs.push([x, y]);
  }
  const yMax = 1.05;
  const xMin = mu - 3.5*sigma, xMax = mu + 3.5*sigma;
  const sx = (x) => ((x - xMin) / (xMax - xMin)) * w;
  const sy = (y) => h - (y / yMax) * h;
  const d = xs.map(([x, y], i) => `${i === 0 ? 'M' : 'L'} ${sx(x).toFixed(1)} ${sy(y).toFixed(1)}`).join(' ');
  const fill = `${d} L${w},${h} L0,${h} Z`;
  // P10, P50, P90 markers
  const p50 = mu;
  const p10 = mu - 1.28 * sigma;
  const p90 = mu + 1.28 * sigma;

  return (
    <div>
      {/* Big number */}
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 6 }}>
        <span className="ga-mono ga-tnum" style={{ fontSize: 44, fontWeight: 600, letterSpacing: '-0.03em',
          color: plot.risk ? 'var(--amber)' : 'var(--yellow)' }}>{plot.yieldF.toFixed(1)}</span>
        <span style={{ fontFamily: 'var(--f-mono)', fontSize: 13, color: 'var(--ink-3)' }}>t/ha · forecast</span>
      </div>
      <div className="ga-mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>
        {plot.area} · {plot.confidence}% confidence · {plot.harvest}
      </div>

      {/* Curve */}
      <div style={{ marginTop: 16 }}>
        <div className="ga-kicker" style={{ marginBottom: 8 }}>Probability density · t/ha</div>
        <svg width="100%" height={h + 32} viewBox={`0 0 ${w} ${h + 32}`}>
          {/* grid */}
          {[0,0.25,0.5,0.75,1].map((p, i) => (
            <line key={i} x1="0" x2={w} y1={p*h} y2={p*h} stroke="rgba(255,255,255,0.05)" strokeWidth="0.5"/>
          ))}
          <path d={fill} fill={plot.risk ? '#FFA500' : '#FFD60A'} fillOpacity="0.18"/>
          <path d={d} stroke={plot.risk ? '#FFA500' : '#FFD60A'} strokeWidth="1.6" fill="none"/>
          {/* P50 */}
          <line x1={sx(p50)} x2={sx(p50)} y1="0" y2={h} stroke="#FFD60A" strokeWidth="1.5"/>
          <line x1={sx(p10)} x2={sx(p10)} y1={h*0.7} y2={h} stroke="rgba(250,250,250,0.4)" strokeDasharray="2 2"/>
          <line x1={sx(p90)} x2={sx(p90)} y1={h*0.7} y2={h} stroke="rgba(250,250,250,0.4)" strokeDasharray="2 2"/>
          {/* labels */}
          <text x={sx(p10)} y={h+12} textAnchor="middle" fontFamily="var(--f-mono)" fontSize="9" fill="var(--ink-3)">P10</text>
          <text x={sx(p10)} y={h+22} textAnchor="middle" fontFamily="var(--f-mono)" fontSize="10" fill="var(--ink-2)">{p10.toFixed(1)}</text>
          <text x={sx(p50)} y={h+12} textAnchor="middle" fontFamily="var(--f-mono)" fontSize="9" fill="var(--yellow)">P50</text>
          <text x={sx(p50)} y={h+22} textAnchor="middle" fontFamily="var(--f-mono)" fontSize="10" fontWeight="600" fill="var(--yellow)">{p50.toFixed(1)}</text>
          <text x={sx(p90)} y={h+12} textAnchor="middle" fontFamily="var(--f-mono)" fontSize="9" fill="var(--ink-3)">P90</text>
          <text x={sx(p90)} y={h+22} textAnchor="middle" fontFamily="var(--f-mono)" fontSize="10" fill="var(--ink-2)">{p90.toFixed(1)}</text>
        </svg>
      </div>

      {/* Scenarios */}
      <div className="ga-kicker" style={{ marginTop: 16, marginBottom: 8 }}>Scenario contribution</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {[
          ['Weather · NOAA blend', 0.62, '#FFD60A'],
          ['Soil moisture · 30d', 0.21, '#FFA500'],
          ['Disease pressure · model', 0.10, '#4FC3FF'],
          ['Operator compliance', 0.07, '#43D67A'],
        ].map(([name, frac, c]) => (
          <div key={name} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ width: 130, fontFamily: 'var(--f-mono)', fontSize: 11, color: 'var(--ink-2)' }}>{name}</span>
            <span style={{ flex: 1, height: 6, background: 'var(--bg-3)', borderRadius: 3, overflow: 'hidden' }}>
              <span style={{ display: 'block', width: `${frac * 100}%`, height: '100%', background: c, borderRadius: 3 }} />
            </span>
            <span className="ga-mono" style={{ fontSize: 11, color: 'var(--ink-2)', width: 40, textAlign: 'right' }}>{(frac*100).toFixed(0)}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { DesktopLedger });
