/* Desktop · Underwriting Console — bank/insurance view */

function DesktopUnderwriting() {
  const [selRow, setSelRow] = React.useState('SP-K3-2026');

  const portfolio = [
    { id: 'SP-K3-2026', farm: 'Saperavi · K-3',  region: 'Kakheti',   ha: 4.8, score: 92, risk: 4.6, rate: 8.2, ask: 60000, status: 'PRE-APPROVED', tone: 'green' },
    { id: 'SP-IM-2026', farm: 'Tsolikouri · I-7', region: 'Imereti',   ha: 3.2, score: 84, risk: 6.1, rate: 9.1, ask: 45000, status: 'IN REVIEW',     tone: 'yellow' },
    { id: 'SP-KV-2026', farm: 'Hazelnut · V-2',   region: 'Guria',     ha: 7.4, score: 88, risk: 5.2, rate: 8.6, ask: 95000, status: 'PRE-APPROVED', tone: 'green' },
    { id: 'SP-RA-2026', farm: 'Tangerine · A-1',  region: 'Adjara',    ha: 2.1, score: 71, risk: 9.4, rate: 11.2,ask: 32000, status: 'FLAGGED',      tone: 'amber' },
    { id: 'SP-KM-2026', farm: 'Mtskheta · M-9',   region: 'Mtskheta',  ha: 5.0, score: 79, risk: 7.0, rate: 9.8, ask: 70000, status: 'IN REVIEW',     tone: 'yellow' },
    { id: 'SP-KH-2025', farm: 'Saperavi · K-8',   region: 'Kakheti',   ha: 6.6, score: 95, risk: 3.9, rate: 7.9, ask: 110000,status: 'RENEWED',      tone: 'green' },
  ];
  const sel = portfolio.find(p => p.id === selRow);

  return (
    <DesktopShell active="underwriting" kicker="UW · DEMO"
      breadcrumb={['Bank of Georgia · AgriCash', 'Portfolio · Spring 2026']}
      right={
        <>
          <Pill color="ghost" size="sm">PORTFOLIO · 142 ACTIVE</Pill>
          <Pill color="ghost" size="sm">RISK MODEL · v2.6</Pill>
        </>
      }>
      <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 18, height: 'calc(100% - 0px)' }}>
        {/* Portfolio overview */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12 }}>
          <KPICard k="DEPLOYED · GEL" v="₾4.8M" suffix="142 farms" spark={[3.2,3.5,3.8,4,4.3,4.5,4.8]} c="yellow" big />
          <KPICard k="DEFAULT RATE · 12M" v="2.4" suffix="% target 8.0" spark={[6,5.5,5,4.5,3.8,3,2.4]} c="green" />
          <KPICard k="AVG RATE" v="8.6" suffix="%" spark={[12.5,12,11,10,9.5,9,8.6]} c="ink" />
          <KPICard k="WEIGHTED HEALTH" v="86" suffix="/ 100" spark={[78,80,82,84,85,86,86]} c="yellow" />
          <KPICard k="OPEN ALERTS" v="14" suffix="2 critical" spark={[20,18,16,14,12,14,14]} c="amber" />
        </div>

        {/* Body: portfolio table + soil passport panel */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18, flex: 1, minHeight: 0 }}>
          {/* portfolio table */}
          <DPanel
            kicker="PORTFOLIO · SPRING 2026"
            title="Soil Passports · 6 active applications"
            subtitle="Live underwriting · backed by sensor data"
            right={
              <div style={{ display: 'flex', gap: 6 }}>
                <Pill color="ghost" size="sm">REGION ▾</Pill>
                <Pill color="ghost" size="sm">STATUS ▾</Pill>
              </div>
            }
            padBody={0}>
            <PortfolioTable portfolio={portfolio} selected={selRow} onSelect={setSelRow} />
          </DPanel>

          {/* Detail */}
          <DPanel
            kicker={`PASSPORT · ${selRow}`}
            title={sel.farm}
            subtitle={`${sel.region} · ${sel.ha} ha · ${sel.id}`}
            right={<Pill color={sel.tone} size="sm">{sel.status}</Pill>}>
            <PassportDetail farm={sel} />
          </DPanel>
        </div>
      </div>
    </DesktopShell>
  );
}

function PortfolioTable({ portfolio, selected, onSelect }) {
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{
        display: 'grid', gridTemplateColumns: '100px 1.4fr 0.9fr 0.7fr 0.7fr 0.7fr 0.9fr 0.9fr',
        gap: 10, 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>ID</span><span>Farm</span><span>Region · ha</span><span>Score</span><span>Risk</span><span>Rate</span><span>Asking</span><span>Status</span>
      </div>
      <div style={{ flex: 1, overflow: 'auto' }} className="ga-scroll">
        {portfolio.map((p, i) => {
          const isSel = p.id === selected;
          return (
            <div key={p.id} onClick={() => onSelect(p.id)} style={{
              display: 'grid', gridTemplateColumns: '100px 1.4fr 0.9fr 0.7fr 0.7fr 0.7fr 0.9fr 0.9fr',
              gap: 10, padding: '13px 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={{ fontSize: 10.5, color: isSel ? 'var(--yellow)' : 'var(--ink-2)' }}>{p.id}</span>
              <span style={{ fontSize: 12.5, fontWeight: 500 }}>{p.farm}</span>
              <div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-2)' }}>{p.region}</div>
                <div className="ga-mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>{p.ha} ha</div>
              </div>
              <div className="ga-mono" style={{ fontSize: 14, fontWeight: 600,
                color: p.score >= 85 ? 'var(--yellow)' : p.score >= 75 ? 'var(--ink)' : 'var(--amber)' }}>{p.score}</div>
              <div className="ga-mono" style={{ fontSize: 12,
                color: p.risk < 5 ? 'var(--green)' : p.risk < 7 ? 'var(--yellow)' : 'var(--amber)' }}>{p.risk}%</div>
              <div className="ga-mono" style={{ fontSize: 12 }}>{p.rate}%</div>
              <div className="ga-mono" style={{ fontSize: 12, color: 'var(--ink)' }}>₾{(p.ask/1000).toFixed(0)}k</div>
              <Pill color={p.tone} size="sm">{p.status}</Pill>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function PassportDetail({ farm }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* Score & rate */}
      <div style={{
        padding: 16,
        background: 'linear-gradient(135deg, #1A1810, #14140F)',
        border: '1px solid rgba(255,214,10,0.25)',
        borderRadius: 8,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <div className="ga-kicker">COMPLIANCE SCORE</div>
            <div className="ga-mono" style={{ fontSize: 38, fontWeight: 600, color: 'var(--yellow)',
              letterSpacing: '-0.03em', marginTop: 4 }}>{farm.score}<span style={{ fontSize: 14, color: 'var(--ink-3)' }}> / 100</span></div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="ga-kicker">INDICATIVE RATE</div>
            <div className="ga-mono" style={{ fontSize: 24, fontWeight: 600, marginTop: 4 }}>{farm.rate}%</div>
            <div style={{ fontFamily: 'var(--f-mono)', fontSize: 10, color: 'var(--green)', marginTop: 2 }}>−4.2 pp vs trad.</div>
          </div>
        </div>
        <div style={{ marginTop: 14, paddingTop: 14, borderTop: '1px dashed rgba(255,214,10,0.3)',
          display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
          <PassStatD k="DEFAULT" v={`${farm.risk}%`} />
          <PassStatD k="COLLATERAL" v={`₾${(farm.ask*1.6/1000).toFixed(0)}k`} />
          <PassStatD k="HARVEST" v="Q3 '26" />
        </div>
      </div>

      {/* Risk decomposition */}
      <div>
        <div className="ga-kicker" style={{ marginBottom: 8 }}>Risk Decomposition · 12-month</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
          {[
            ['Weather variability', 0.42, '#FFA500'],
            ['Soil compliance', 0.18, '#43D67A', 'pos'],
            ['Operator history', 0.22, '#FFD60A'],
            ['Market price · GEL', 0.12, '#4FC3FF'],
            ['Disease pressure', 0.06, '#FF453A'],
          ].map(([name, frac, c, sign]) => (
            <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 }}>
                <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>

      {/* Signed events */}
      <div>
        <div className="ga-kicker" style={{ marginBottom: 8,
          display: 'flex', justifyContent: 'space-between' }}>
          <span>Signed Events · 12-month</span>
          <span style={{ color: 'var(--ink-2)' }}>47 / 47 on time</span>
        </div>
        <div style={{ position: 'relative', height: 38, padding: 4,
          background: 'var(--bg-3)', borderRadius: 6, border: '1px solid var(--line-2)' }}>
          <div style={{ position: 'absolute', inset: 4, display: 'grid', gridTemplateColumns: 'repeat(52, 1fr)', gap: 1 }}>
            {Array.from({ length: 52 }, (_, i) => {
              const r = Math.sin(i * 1.7) * 0.5 + 0.5;
              const ok = r > 0.15;
              return <span key={i} style={{
                background: ok ? (r > 0.7 ? '#43D67A' : 'rgba(67,214,122,0.4)') : 'rgba(255,255,255,0.08)',
                borderRadius: 1,
              }} title={`week ${i+1}`}/>;
            })}
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 4,
          fontFamily: 'var(--f-mono)', fontSize: 9.5, color: 'var(--ink-3)' }}>
          <span>52w ago</span><span>26w</span><span>now</span>
        </div>
      </div>

      {/* CTA */}
      <div style={{ display: 'flex', gap: 8, marginTop: 4 }}>
        <GhostButton color="ghost" size="md" style={{ flex: 1 }}>Request docs</GhostButton>
        <GhostButton color="yellow" solid size="md" style={{ flex: 1 }}>Approve · ₾{(farm.ask/1000).toFixed(0)}k →</GhostButton>
      </div>
    </div>
  );
}

function PassStatD({ k, v }) {
  return (
    <div>
      <div className="ga-kicker" style={{ fontSize: 8.5 }}>{k}</div>
      <div className="ga-mono" style={{ fontSize: 15, fontWeight: 600, marginTop: 3, color: 'var(--ink)' }}>{v}</div>
    </div>
  );
}

Object.assign(window, { DesktopUnderwriting });
