// FundDetail.jsx — detail page, explore, buy, sell, projection

const { useState: useStateD, useMemo: useMemoD } = React;

// ─── DETALJ ────────────────────────────────────────────────────
function DetailScreen({ fundId, nav, chartStyle, setChartStyle }) {
  const fund = FUNDS.find(f => f.id === fundId);
  const [period, setPeriod] = useStateD('1Å');
  const [hoverIdx, setHoverIdx] = useStateD(null);
  const [showFeeBreakdown, setShowFeeBreakdown] = useStateD(false);

  const series = fund.series[period];
  const periodPct = (series[series.length - 1] - series[0]) / series[0];
  const shownIdx = hoverIdx ?? series.length - 1;
  const shownPct = (series[shownIdx] - series[0]) / series[0];

  const Chart = chartStyle === 'bar' ? BarChart : AreaChart;

  // Yearly fee in kr (illustrative on 100 000 kr)
  const illustrativeAmount = 100000;
  const yearlyFeeKr = illustrativeAmount * (fund.fee / 100);
  const marketYearlyFeeKr = illustrativeAmount * (fund.marketFee / 100);
  const savings = marketYearlyFeeKr - yearlyFeeKr;

  return (
    <div style={{ background: BB.bg, minHeight: '100%', paddingBottom: 120 }}>
      <ScreenHeader title={fund.short} onBack={() => nav('back')}/>

      {/* Fund identity */}
      <div style={{ padding: '8px 20px 20px', display: 'flex', alignItems: 'center', gap: 14 }}>
        <FundMark fund={fund} size={52}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 20, fontWeight: 700, color: BB.fg, letterSpacing: '-0.01em' }}>{fund.name}</div>
          <div style={{ fontSize: 13, color: BB.fg3, marginTop: 2 }}>{fund.tagline}</div>
        </div>
      </div>

      {/* Hero value / change */}
      {fund.owned && (
        <div style={{ padding: '0 20px 16px' }}>
          <div style={{ fontSize: 12, color: BB.fg3, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>
            Dine beholdninger
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 6 }}>
            <div style={{ fontSize: 44, fontWeight: 400, color: BB.fg, letterSpacing: '-0.03em', lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>
              {fmtNok(fund.owned.valueNok)}
              <span style={{ fontSize: 20, color: BB.fg2, marginLeft: 6 }}>kr</span>
            </div>
          </div>
          <div style={{ marginTop: 6, fontSize: 13, color: BB.fg3 }}>
            {fund.owned.shares.toFixed(3).replace('.', ',')} andeler · Innskutt {fmtNok(fund.owned.costNok)} kr
          </div>
        </div>
      )}

      {/* Big chart */}
      <div style={{ padding: '0 20px 8px', display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <div style={{ fontSize: 13, color: BB.fg2 }}>
          {hoverIdx != null ? `Punkt ${hoverIdx + 1}/${series.length}` : `Utvikling ${period}`}
        </div>
        <div style={{
          fontSize: 16, fontWeight: 600,
          color: shownPct >= 0 ? BB.green : BB.pink,
          fontVariantNumeric: 'tabular-nums',
        }}>{fmtPct(shownPct, 2)}</div>
      </div>
      <div style={{ padding: '0 8px' }}>
        <Chart data={series} height={170} color={fund.color} negColor={BB.pink}
          onHover={setHoverIdx} activeIdx={hoverIdx}/>
      </div>
      <div style={{ padding: '8px 16px 4px' }}>
        <PeriodTabs value={period} onChange={setPeriod}/>
      </div>
      <div style={{ padding: '8px 16px 0', display: 'flex', justifyContent: 'flex-end' }}>
        <div style={{ width: 160 }}><ChartToggle value={chartStyle} onChange={setChartStyle}/></div>
      </div>

      {/* Returns table */}
      <div style={{ margin: '20px 16px 0', background: BB.surface, borderRadius: 14, overflow: 'hidden' }}>
        <div style={{ padding: '12px 16px 8px', fontSize: 12, color: BB.fg3, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>
          Avkastning
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 1, background: 'rgba(255,255,255,0.05)' }}>
          {PERIODS.map(p => (
            <div key={p} style={{ background: BB.surface, padding: '12px 16px' }}>
              <div style={{ fontSize: 11, color: BB.fg3, fontWeight: 600 }}>{p}</div>
              <div style={{ fontSize: 15, fontWeight: 600, color: fund.perf[p] >= 0 ? BB.green : BB.pink,
                fontVariantNumeric: 'tabular-nums', marginTop: 3 }}>
                {fmtPct(fund.perf[p], 1)}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Rettferdig — costs */}
      <div style={{ margin: '20px 16px 0', background: BB.surface, borderRadius: 14, padding: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ fontSize: 12, color: BB.fg3, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>Kostnad</div>
          <div style={{ fontSize: 10, padding: '3px 8px', borderRadius: 4, background: 'rgba(133,255,134,0.15)', color: BB.green, fontWeight: 700, letterSpacing: '0.04em' }}>
            INGEN SKJULTE GEBYRER
          </div>
        </div>

        <div style={{ marginTop: 14 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 4 }}>
            <div style={{ fontSize: 14, color: BB.fg }}>Årlig forvaltningsgebyr</div>
            <div style={{ fontSize: 20, fontWeight: 500, color: BB.fg, fontVariantNumeric: 'tabular-nums' }}>
              {fmtPctNoSign(fund.fee/100, 2)}
            </div>
          </div>
          <div style={{ fontSize: 12, color: BB.fg3 }}>Av beholdning — trekkes daglig</div>
        </div>

        {/* Bar compare */}
        <div style={{ marginTop: 16, padding: '12px 14px', background: BB.surface2, borderRadius: 10 }}>
          <div style={{ fontSize: 12, color: BB.fg2, marginBottom: 10 }}>På 100 000 kr i året</div>
          <div style={{ marginBottom: 10 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 4 }}>
              <span style={{ color: BB.fg }}>Bulder</span>
              <span style={{ color: BB.green, fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>{fmtNok(yearlyFeeKr)} kr</span>
            </div>
            <div style={{ height: 8, background: 'rgba(255,255,255,0.05)', borderRadius: 4, overflow: 'hidden' }}>
              <div style={{ height: '100%', width: `${(fund.fee / fund.marketFee) * 100}%`, background: BB.green, borderRadius: 4 }}/>
            </div>
          </div>
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 4 }}>
              <span style={{ color: BB.fg2 }}>Markedssnitt</span>
              <span style={{ color: BB.fg2, fontVariantNumeric: 'tabular-nums' }}>{fmtNok(marketYearlyFeeKr)} kr</span>
            </div>
            <div style={{ height: 8, background: 'rgba(255,255,255,0.05)', borderRadius: 4, overflow: 'hidden' }}>
              <div style={{ height: '100%', width: '100%', background: 'rgba(255,255,255,0.2)', borderRadius: 4 }}/>
            </div>
          </div>
          <div style={{ marginTop: 12, padding: '10px 12px', background: 'rgba(133,255,134,0.1)', borderRadius: 8 }}>
            <div style={{ fontSize: 13, color: BB.fg }}>
              Du sparer <span style={{ color: BB.green, fontWeight: 700 }}>{fmtNok(savings)} kr</span> i året
            </div>
            <div style={{ fontSize: 11, color: BB.fg3, marginTop: 2 }}>Sammenlignet med markedssnittet på {fmtPctNoSign(fund.marketFee/100, 2)}</div>
          </div>
        </div>
      </div>

      {/* Key facts */}
      <div style={{ margin: '16px 16px 0', background: BB.surface, borderRadius: 14, padding: 16 }}>
        <div style={{ fontSize: 12, color: BB.fg3, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600, marginBottom: 12 }}>
          Nøkkeltall
        </div>
        <FactRow label="Risiko" right={<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><RiskDots risk={fund.risk}/><span style={{ color: BB.fg, fontSize: 13, fontVariantNumeric: 'tabular-nums' }}>{fund.risk}/7</span></div>}/>
        <FactRow label="Morningstar" right={<Stars n={fund.morningstar}/>}/>
        <FactRow label="Antall selskaper" right={<span style={{ color: BB.fg, fontSize: 14, fontVariantNumeric: 'tabular-nums' }}>{fmtNok(fund.holdings)}</span>}/>
        <FactRow label="Valuta" right={<span style={{ color: BB.fg, fontSize: 14 }}>{fund.currency}</span>}/>
        <FactRow label="Minste kjøp" right={<span style={{ color: BB.fg, fontSize: 14 }}>100 kr</span>} last/>
      </div>

      {/* Sectors — allocation */}
      <div style={{ margin: '16px 16px 0', background: BB.surface, borderRadius: 14, padding: 16 }}>
        <div style={{ fontSize: 12, color: BB.fg3, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600, marginBottom: 14 }}>
          Sammensetning
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <Donut parts={fund.sectors} size={92} thickness={14}/>
          <div style={{ flex: 1 }}>
            {fund.sectors.map(s => (
              <div key={s.name} style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                <div style={{ width: 8, height: 8, borderRadius: 2, background: s.color }}/>
                <div style={{ flex: 1, fontSize: 12, color: BB.fg2 }}>{s.name}</div>
                <div style={{ fontSize: 12, color: BB.fg, fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>{(s.pct*100).toFixed(0)} %</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Top holdings */}
      <div style={{ margin: '16px 16px 0', background: BB.surface, borderRadius: 14, padding: 16 }}>
        <div style={{ fontSize: 12, color: BB.fg3, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600, marginBottom: 12 }}>
          Største plasseringer
        </div>
        {fund.top.map((h, i) => (
          <div key={h.name} style={{ display: 'flex', alignItems: 'center', padding: '10px 0',
            borderBottom: i < fund.top.length - 1 ? '1px solid rgba(255,255,255,0.05)' : 'none' }}>
            <div style={{ width: 22, fontSize: 12, color: BB.fg3, fontVariantNumeric: 'tabular-nums' }}>{i+1}</div>
            <div style={{ flex: 1, fontSize: 14, color: BB.fg }}>{h.name}</div>
            <div style={{ fontSize: 13, color: BB.fg2, fontVariantNumeric: 'tabular-nums' }}>{h.pct.toFixed(1).replace('.', ',')} %</div>
          </div>
        ))}
      </div>

      {/* About */}
      <div style={{ margin: '16px 16px 0', background: BB.surface, borderRadius: 14, padding: 16 }}>
        <div style={{ fontSize: 12, color: BB.fg3, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600, marginBottom: 8 }}>Om fondet</div>
        <div style={{ fontSize: 14, color: BB.fg2, lineHeight: 1.5 }}>{fund.desc}</div>
      </div>

      {/* Bottom action bar */}
      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '12px 16px 32px',
        background: 'linear-gradient(180deg, rgba(15,23,41,0) 0%, rgba(15,23,41,0.95) 40%)', display: 'flex', gap: 10 }}>
        {fund.owned && (
          <PrimaryButton variant="ghost" onClick={() => nav('sell', fund.id)}>Selg</PrimaryButton>
        )}
        <PrimaryButton onClick={() => nav('buy', fund.id)}>{fund.owned ? 'Kjøp mer' : 'Kjøp'}</PrimaryButton>
      </div>
    </div>
  );
}

function FactRow({ label, right, last }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', padding: '10px 0',
      borderBottom: last ? 'none' : '1px solid rgba(255,255,255,0.05)' }}>
      <div style={{ flex: 1, fontSize: 14, color: BB.fg2 }}>{label}</div>
      {right}
    </div>
  );
}

// ─── UTFORSK ───────────────────────────────────────────────────
function UtforskScreen({ nav }) {
  const [query, setQuery] = useStateD('');
  const filtered = FUNDS.filter(f =>
    f.name.toLowerCase().includes(query.toLowerCase()) ||
    f.tagline.toLowerCase().includes(query.toLowerCase())
  );

  return (
    <div style={{ background: BB.bg, minHeight: '100%', paddingBottom: 100 }}>
      <ScreenHeader title="Utforsk" onBack={() => nav('back')}/>

      <div style={{ padding: '0 16px 12px' }}>
        <div style={{ position: 'relative' }}>
          <svg style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)' }} width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={BB.fg3} strokeWidth="2" strokeLinecap="round"><circle cx="11" cy="11" r="7"/><path d="M20 20l-3.5-3.5"/></svg>
          <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Søk i Bulder-fond" style={{
            width: '100%', padding: '12px 14px 12px 38px', borderRadius: 10,
            background: BB.surface, border: 'none', color: BB.fg, fontSize: 15,
            fontFamily: 'inherit', outline: 'none',
          }}/>
        </div>
      </div>

      <div style={{ padding: '8px 20px 8px', fontSize: 12, color: BB.fg3, letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 700 }}>
        Bulders indeksfond
      </div>

      <div style={{ padding: '0 16px' }}>
        {filtered.map(f => (
          <ExploreCard key={f.id} fund={f} onClick={() => nav('detail', f.id)}/>
        ))}
      </div>

      <div style={{ margin: '16px 16px 0', padding: 16, background: BB.surface, borderRadius: 14 }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: BB.fg }}>Savner du et fond?</div>
        <div style={{ fontSize: 13, color: BB.fg3, marginTop: 4, lineHeight: 1.45 }}>
          Vi satser på bredde og lav pris. Ønsker du flere fond? Si fra.
        </div>
      </div>
    </div>
  );
}

function ExploreCard({ fund, onClick }) {
  return (
    <div onClick={onClick} style={{
      marginBottom: 10, background: BB.surface, borderRadius: 14, padding: 16, cursor: 'pointer',
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 12 }}>
        <FundMark fund={fund} size={44}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 15, fontWeight: 600, color: BB.fg }}>{fund.name}</div>
          <div style={{ fontSize: 12, color: BB.fg3, marginTop: 2 }}>{fund.tagline}</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontSize: 11, color: BB.fg3, fontWeight: 600 }}>1 ÅR</div>
          <div style={{ fontSize: 15, fontWeight: 600, color: fund.perf['1Å'] >= 0 ? BB.green : BB.pink, fontVariantNumeric: 'tabular-nums', marginTop: 2 }}>
            {fmtPct(fund.perf['1Å'], 1)}
          </div>
        </div>
      </div>
      <div style={{ margin: '0 -4px' }}>
        <AreaChart data={fund.series['1Å']} height={56} width={320} color={fund.color} negColor={BB.pink}/>
      </div>
      <div style={{ display: 'flex', gap: 14, marginTop: 10, fontSize: 11 }}>
        <Meta label="Gebyr" value={fmtPctNoSign(fund.fee/100, 2)}/>
        <Meta label="Risiko" value={`${fund.risk}/7`}/>
        <Meta label="Selskaper" value={fmtNok(fund.holdings)}/>
      </div>
    </div>
  );
}

function Meta({ label, value }) {
  return (
    <div>
      <div style={{ color: BB.fg3, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', fontSize: 10 }}>{label}</div>
      <div style={{ color: BB.fg, fontSize: 13, fontWeight: 500, fontVariantNumeric: 'tabular-nums', marginTop: 2 }}>{value}</div>
    </div>
  );
}

// ─── KJØP ─────────────────────────────────────────────────────
function BuyScreen({ fundId, nav }) {
  const fund = FUNDS.find(f => f.id === fundId);
  const [amount, setAmount] = useStateD('1000');
  const [freq, setFreq] = useStateD('one'); // 'one' | 'monthly'
  const [step, setStep] = useStateD('amount'); // 'amount' | 'review' | 'done'

  const num = parseInt((amount || '0').replace(/\D/g, '')) || 0;
  const valid = num >= 100;
  const fee10yr = num * (fund.fee / 100) * 10;

  const setPreset = v => setAmount(String(v));

  if (step === 'done') {
    return (
      <div style={{ background: BB.bg, minHeight: '100%', paddingBottom: 100, position: 'relative' }}>
        <ScreenHeader title="Kvittering" onBack={() => nav('oversikt')}/>
        <div style={{ padding: '40px 20px', textAlign: 'center' }}>
          <div style={{ width: 72, height: 72, borderRadius: 999, background: 'rgba(133,255,134,0.15)',
            margin: '0 auto 20px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke={BB.green} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M5 12l5 5 9-11"/>
            </svg>
          </div>
          <div style={{ fontSize: 24, fontWeight: 700, color: BB.fg, letterSpacing: '-0.01em' }}>Kjøp registrert</div>
          <div style={{ fontSize: 14, color: BB.fg3, marginTop: 8, lineHeight: 1.5, padding: '0 20px' }}>
            Kjøpet gjennomføres til neste kurs. Det tar normalt 1–3 virkedager.
          </div>
          <div style={{ margin: '24px 16px 0', padding: 16, background: BB.surface, borderRadius: 14, textAlign: 'left' }}>
            <KVRow label="Fond" value={fund.name}/>
            <KVRow label="Beløp" value={`${fmtNok(num)} kr`}/>
            <KVRow label="Type" value={freq === 'one' ? 'Engangskjøp' : 'Månedlig spareavtale'} last/>
          </div>
          <div style={{ padding: '24px 16px 0' }}>
            <PrimaryButton onClick={() => nav('oversikt')}>Ferdig</PrimaryButton>
          </div>
        </div>
      </div>
    );
  }

  if (step === 'review') {
    return (
      <div style={{ background: BB.bg, minHeight: '100%', paddingBottom: 120, position: 'relative' }}>
        <ScreenHeader title="Bekreft kjøp" onBack={() => setStep('amount')}/>
        <div style={{ padding: '10px 20px 20px', textAlign: 'center' }}>
          <div style={{ fontSize: 13, color: BB.fg3, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>Du kjøper for</div>
          <div style={{ fontSize: 52, fontWeight: 400, color: BB.fg, letterSpacing: '-0.03em', lineHeight: 1, marginTop: 10, fontVariantNumeric: 'tabular-nums' }}>
            {fmtNok(num)}<span style={{ fontSize: 22, color: BB.fg2, marginLeft: 6 }}>kr</span>
          </div>
          <div style={{ fontSize: 13, color: BB.fg2, marginTop: 8 }}>{freq === 'one' ? 'Engangskjøp' : 'Hver måned'}</div>
        </div>

        <div style={{ margin: '0 16px', padding: 16, background: BB.surface, borderRadius: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <FundMark fund={fund} size={40}/>
            <div>
              <div style={{ fontSize: 15, fontWeight: 600, color: BB.fg }}>{fund.name}</div>
              <div style={{ fontSize: 12, color: BB.fg3, marginTop: 2 }}>{fund.tagline}</div>
            </div>
          </div>
        </div>

        <div style={{ margin: '14px 16px 0', padding: 16, background: BB.surface, borderRadius: 14 }}>
          <KVRow label="Fra konto" value="Bruks · 1234 56 78901"/>
          <KVRow label="Gebyr per år" value={`${fmtPctNoSign(fund.fee/100, 2)} · ${fmtNok(num * fund.fee / 100)} kr`}/>
          <KVRow label="På 10 år (anslag)" value={`${fmtNok(fee10yr)} kr`} last/>
        </div>

        <div style={{ margin: '14px 16px 0', padding: '12px 14px', background: 'rgba(9,38,214,0.12)', borderRadius: 10 }}>
          <div style={{ fontSize: 12, color: BB.fg2, lineHeight: 1.5 }}>
            Fond er risiko. Historisk avkastning er ingen garanti for framtidig. Du kan tape hele eller deler av beløpet.
          </div>
        </div>

        <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '12px 16px 32px',
          background: 'linear-gradient(180deg, rgba(15,23,41,0) 0%, rgba(15,23,41,0.95) 40%)', display: 'flex', gap: 10 }}>
          <PrimaryButton variant="ghost" onClick={() => setStep('amount')}>Tilbake</PrimaryButton>
          <PrimaryButton onClick={() => setStep('done')}>Bekreft</PrimaryButton>
        </div>
      </div>
    );
  }

  // amount step
  return (
    <div style={{ background: BB.bg, minHeight: '100%', paddingBottom: 120, position: 'relative' }}>
      <ScreenHeader title={`Kjøp ${fund.short}`} onBack={() => nav('back')}/>

      <div style={{ padding: '10px 20px 16px', textAlign: 'center' }}>
        <div style={{ fontSize: 13, color: BB.fg3 }}>Beløp</div>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'center', gap: 6, marginTop: 8 }}>
          <input value={amount} onChange={e => setAmount(e.target.value.replace(/\D/g, ''))}
            inputMode="numeric"
            style={{
              fontSize: 56, fontWeight: 400, color: BB.fg, background: 'transparent',
              border: 'none', outline: 'none', textAlign: 'right', width: Math.max(80, (amount.length || 1) * 32),
              fontFamily: 'inherit', letterSpacing: '-0.03em',
              fontVariantNumeric: 'tabular-nums',
            }}/>
          <span style={{ fontSize: 22, color: BB.fg2 }}>kr</span>
        </div>
        {!valid && <div style={{ fontSize: 12, color: BB.pink, marginTop: 6 }}>Minste kjøp er 100 kr</div>}
      </div>

      <div style={{ padding: '0 16px', display: 'flex', gap: 8, justifyContent: 'center' }}>
        {[500, 1000, 5000, 10000].map(v => (
          <button key={v} onClick={() => setPreset(v)} style={{
            padding: '8px 14px', borderRadius: 999, background: BB.surface, border: 'none',
            color: BB.fg, fontSize: 13, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
            fontVariantNumeric: 'tabular-nums',
          }}>{fmtNok(v)}</button>
        ))}
      </div>

      <div style={{ padding: '24px 16px 0' }}>
        <div style={{ fontSize: 12, color: BB.fg3, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600, marginBottom: 8 }}>Hvor ofte</div>
        <div style={{ display: 'flex', gap: 8 }}>
          <FreqChip active={freq === 'one'} label="En gang" sub="Engangskjøp" onClick={() => setFreq('one')}/>
          <FreqChip active={freq === 'monthly'} label="Hver måned" sub="Spareavtale" onClick={() => setFreq('monthly')}/>
        </div>
      </div>

      <div style={{ margin: '20px 16px 0', padding: 16, background: BB.surface, borderRadius: 14 }}>
        <KVRow label="Gebyr per år" value={`${fmtNok(num * fund.fee / 100)} kr (${fmtPctNoSign(fund.fee/100, 2)})`}/>
        <KVRow label="Fra konto" value="Bruks · 1234 56 78901" last/>
      </div>

      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '12px 16px 32px',
        background: 'linear-gradient(180deg, rgba(15,23,41,0) 0%, rgba(15,23,41,0.95) 40%)' }}>
        <PrimaryButton onClick={() => valid && setStep('review')} style={{ opacity: valid ? 1 : 0.4 }}>
          Fortsett
        </PrimaryButton>
      </div>
    </div>
  );
}

function FreqChip({ active, label, sub, onClick }) {
  return (
    <button onClick={onClick} style={{
      flex: 1, padding: 14, borderRadius: 12,
      background: active ? 'rgba(9,38,214,0.15)' : BB.surface,
      border: `1.5px solid ${active ? BB.royal : 'transparent'}`,
      color: BB.fg, textAlign: 'left', cursor: 'pointer', fontFamily: 'inherit',
    }}>
      <div style={{ fontSize: 14, fontWeight: 600, color: BB.fg }}>{label}</div>
      <div style={{ fontSize: 12, color: BB.fg3, marginTop: 2 }}>{sub}</div>
    </button>
  );
}

function KVRow({ label, value, last }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      padding: '10px 0', borderBottom: last ? 'none' : '1px solid rgba(255,255,255,0.05)' }}>
      <div style={{ fontSize: 13, color: BB.fg2 }}>{label}</div>
      <div style={{ fontSize: 14, color: BB.fg, fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>{value}</div>
    </div>
  );
}

// ─── SELL ─────────────────────────────────────────────────────
function SellScreen({ fundId, nav }) {
  const fund = FUNDS.find(f => f.id === fundId);
  const [amount, setAmount] = useStateD('');
  const [step, setStep] = useStateD('amount');

  const num = parseInt((amount || '0').replace(/\D/g, '')) || 0;
  const valid = num >= 100 && num <= fund.owned.valueNok;
  const tooMuch = num > fund.owned.valueNok;

  if (step === 'done') {
    return (
      <div style={{ background: BB.bg, minHeight: '100%', paddingBottom: 100 }}>
        <ScreenHeader title="Kvittering" onBack={() => nav('oversikt')}/>
        <div style={{ padding: '40px 20px', textAlign: 'center' }}>
          <div style={{ width: 72, height: 72, borderRadius: 999, background: 'rgba(133,255,134,0.15)',
            margin: '0 auto 20px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke={BB.green} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M5 12l5 5 9-11"/>
            </svg>
          </div>
          <div style={{ fontSize: 24, fontWeight: 700, color: BB.fg }}>Salg registrert</div>
          <div style={{ fontSize: 14, color: BB.fg3, marginTop: 8, lineHeight: 1.5, padding: '0 20px' }}>
            Pengene er på konto innen 3 virkedager.
          </div>
          <div style={{ padding: '24px 16px 0' }}>
            <PrimaryButton onClick={() => nav('oversikt')}>Ferdig</PrimaryButton>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ background: BB.bg, minHeight: '100%', paddingBottom: 120, position: 'relative' }}>
      <ScreenHeader title={`Selg ${fund.short}`} onBack={() => nav('back')}/>

      <div style={{ padding: '10px 20px 16px', textAlign: 'center' }}>
        <div style={{ fontSize: 13, color: BB.fg3 }}>Beløp å selge</div>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'center', gap: 6, marginTop: 8 }}>
          <input value={amount} onChange={e => setAmount(e.target.value.replace(/\D/g, ''))}
            placeholder="0" inputMode="numeric"
            style={{
              fontSize: 56, fontWeight: 400, color: BB.fg, background: 'transparent',
              border: 'none', outline: 'none', textAlign: 'right', width: Math.max(80, ((amount || '0').length) * 32),
              fontFamily: 'inherit', letterSpacing: '-0.03em',
              fontVariantNumeric: 'tabular-nums',
            }}/>
          <span style={{ fontSize: 22, color: BB.fg2 }}>kr</span>
        </div>
        <div style={{ fontSize: 12, color: tooMuch ? BB.pink : BB.fg3, marginTop: 6 }}>
          Tilgjengelig: {fmtNok(fund.owned.valueNok)} kr
        </div>
      </div>

      <div style={{ padding: '0 16px', display: 'flex', gap: 8, justifyContent: 'center' }}>
        {[0.25, 0.5, 1].map(p => (
          <button key={p} onClick={() => setAmount(String(Math.round(fund.owned.valueNok * p)))} style={{
            padding: '8px 14px', borderRadius: 999, background: BB.surface, border: 'none',
            color: BB.fg, fontSize: 13, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
          }}>{p === 1 ? 'Alt' : `${p*100} %`}</button>
        ))}
      </div>

      <div style={{ margin: '24px 16px 0', padding: 16, background: BB.surface, borderRadius: 14 }}>
        <KVRow label="Til konto" value="Bruks · 1234 56 78901"/>
        <KVRow label="Tid til konto" value="1–3 virkedager" last/>
      </div>

      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '12px 16px 32px',
        background: 'linear-gradient(180deg, rgba(15,23,41,0) 0%, rgba(15,23,41,0.95) 40%)' }}>
        <PrimaryButton onClick={() => valid && setStep('done')} style={{ opacity: valid ? 1 : 0.4 }}>
          Selg for {fmtNok(num)} kr
        </PrimaryButton>
      </div>
    </div>
  );
}

// ─── PROJECTION CALCULATOR ────────────────────────────────────
function ProjectionScreen({ nav }) {
  const [monthly, setMonthly] = useStateD(2000);
  const [years, setYears] = useStateD(10);
  const [ret, setRet] = useStateD(6); // % p.a.

  // FV of annuity monthly
  const months = years * 12;
  const r = (ret / 100) / 12;
  const fv = r === 0 ? monthly * months : monthly * ((Math.pow(1 + r, months) - 1) / r);
  const invested = monthly * months;
  const growth = fv - invested;

  // Build a projection series (yearly)
  const proj = [];
  const projInvested = [];
  for (let y = 0; y <= years; y++) {
    const m = y * 12;
    const v = r === 0 ? monthly * m : monthly * ((Math.pow(1 + r, m) - 1) / r);
    proj.push(v);
    projInvested.push(monthly * m);
  }

  // Custom dual-line chart
  const chartH = 180, chartW = 320;
  const maxY = Math.max(...proj);
  const yAt = v => 10 + (chartH - 20) - (v / (maxY || 1)) * (chartH - 20);
  const xAt = i => 10 + (i / years) * (chartW - 20);

  let valueD = '';
  proj.forEach((v, i) => { valueD += (i === 0 ? 'M' : 'L') + xAt(i).toFixed(2) + ',' + yAt(v).toFixed(2) + ' '; });
  let investedD = '';
  projInvested.forEach((v, i) => { investedD += (i === 0 ? 'M' : 'L') + xAt(i).toFixed(2) + ',' + yAt(v).toFixed(2) + ' '; });
  const areaD = valueD + `L${xAt(years).toFixed(2)},${chartH - 10} L${xAt(0).toFixed(2)},${chartH - 10} Z`;

  return (
    <div style={{ background: BB.bg, minHeight: '100%', paddingBottom: 100 }}>
      <ScreenHeader title="Hva blir det til?" onBack={() => nav('back')}/>

      <div style={{ padding: '10px 20px 8px', textAlign: 'center' }}>
        <div style={{ fontSize: 13, color: BB.fg3, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>
          Om {years} år
        </div>
        <div style={{ fontSize: 56, fontWeight: 400, color: BB.green, letterSpacing: '-0.035em', lineHeight: 1, marginTop: 8, fontVariantNumeric: 'tabular-nums' }}>
          {fmtNok(fv)}<span style={{ fontSize: 22, color: BB.fg2, marginLeft: 6 }}>kr</span>
        </div>
        <div style={{ fontSize: 13, color: BB.fg2, marginTop: 8 }}>
          {fmtNok(invested)} kr innskutt · <span style={{ color: BB.green, fontWeight: 600 }}>+ {fmtNok(growth)} i avkastning</span>
        </div>
      </div>

      {/* Projection chart */}
      <div style={{ padding: '16px 8px 0' }}>
        <svg width="100%" height={chartH} viewBox={`0 0 ${chartW} ${chartH}`}>
          <defs>
            <linearGradient id="proj-grad" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor={BB.green} stopOpacity="0.35"/>
              <stop offset="100%" stopColor={BB.green} stopOpacity="0"/>
            </linearGradient>
          </defs>
          <path d={areaD} fill="url(#proj-grad)"/>
          <path d={investedD} fill="none" stroke="rgba(255,255,255,0.4)" strokeWidth="1.8" strokeDasharray="4 4"/>
          <path d={valueD} fill="none" stroke={BB.green} strokeWidth="2.4" strokeLinecap="round"/>
          {/* endpoint */}
          <circle cx={xAt(years)} cy={yAt(proj[proj.length - 1])} r="4.5" fill={BB.green}/>
        </svg>
        <div style={{ display: 'flex', justifyContent: 'space-between', padding: '0 14px', fontSize: 11, color: BB.fg3, fontVariantNumeric: 'tabular-nums' }}>
          <span>I dag</span>
          <span>Om {years} år</span>
        </div>
      </div>

      <div style={{ padding: '12px 20px 0', display: 'flex', gap: 18, justifyContent: 'center', fontSize: 12 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <div style={{ width: 14, height: 2, background: BB.green, borderRadius: 1 }}/>
          <span style={{ color: BB.fg2 }}>Med avkastning</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <div style={{ width: 14, height: 2, background: 'rgba(255,255,255,0.4)', borderRadius: 1,
            backgroundImage: 'repeating-linear-gradient(90deg, rgba(255,255,255,0.4) 0 4px, transparent 4px 8px)' }}/>
          <span style={{ color: BB.fg2 }}>Bare innskutt</span>
        </div>
      </div>

      {/* Sliders */}
      <div style={{ margin: '24px 16px 0', padding: 16, background: BB.surface, borderRadius: 14 }}>
        <SliderRow label="Månedlig beløp" value={`${fmtNok(monthly)} kr`}
          min={100} max={15000} step={100} val={monthly} onChange={setMonthly}/>
        <SliderRow label="Antall år" value={`${years} år`}
          min={1} max={30} step={1} val={years} onChange={setYears}/>
        <SliderRow label="Forventet avkastning" value={`${ret.toFixed(1).replace('.', ',')} %`}
          min={0} max={10} step={0.5} val={ret} onChange={setRet} last/>
      </div>

      <div style={{ margin: '16px 16px 0', padding: '12px 14px', background: 'rgba(9,38,214,0.12)', borderRadius: 10 }}>
        <div style={{ fontSize: 12, color: BB.fg2, lineHeight: 1.5 }}>
          Regnestykket er et anslag. Fond svinger — noen år går det opp, andre år ned. Historisk har et globalt aksjefond gitt 6–7 % per år i gjennomsnitt.
        </div>
      </div>

      <div style={{ padding: '20px 16px' }}>
        <PrimaryButton onClick={() => nav('utforsk')}>Start en spareavtale</PrimaryButton>
      </div>
    </div>
  );
}

function SliderRow({ label, value, min, max, step, val, onChange, last }) {
  const pct = ((val - min) / (max - min)) * 100;
  return (
    <div style={{ padding: '12px 0', borderBottom: last ? 'none' : '1px solid rgba(255,255,255,0.05)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
        <div style={{ fontSize: 13, color: BB.fg2 }}>{label}</div>
        <div style={{ fontSize: 16, color: BB.fg, fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>{value}</div>
      </div>
      <div style={{ position: 'relative', height: 20 }}>
        <div style={{ position: 'absolute', top: 8, left: 0, right: 0, height: 4, background: 'rgba(255,255,255,0.08)', borderRadius: 2 }}/>
        <div style={{ position: 'absolute', top: 8, left: 0, width: `${pct}%`, height: 4, background: BB.royal, borderRadius: 2 }}/>
        <input type="range" min={min} max={max} step={step} value={val}
          onChange={e => onChange(parseFloat(e.target.value))}
          style={{
            position: 'absolute', inset: 0, width: '100%', height: '100%',
            opacity: 0, cursor: 'pointer',
          }}/>
        <div style={{
          position: 'absolute', top: 2, left: `calc(${pct}% - 8px)`,
          width: 16, height: 16, borderRadius: 999, background: '#fff',
          boxShadow: '0 2px 6px rgba(0,0,0,0.3)', pointerEvents: 'none',
        }}/>
      </div>
    </div>
  );
}

Object.assign(window, {
  DetailScreen, UtforskScreen, BuyScreen, SellScreen, ProjectionScreen,
});
