// screens-a.jsx — Mortgage application screens 1-4
// Intro, BankID, Property, Loan details

const { useState, useEffect, useRef } = React;

// ─────────────────────────────────────────────────────────────
// 0. PORTFOLIO / START — hero rate calculator + "Apply" CTA
// ─────────────────────────────────────────────────────────────
function PortfolioScreen({ state, setState, onNext }) {
  const { amount, propertyValue, term } = state;
  const A = window.APPLICANT;
  // Bulder's actual rate logic: loan-to-value tiers + volume discount
  const ltv = amount / propertyValue;
  const baseRate = ltv <= 0.60 ? 5.14 : ltv <= 0.75 ? 5.34 : 5.69;
  const volumeBonus = amount >= 2_000_000 ? -0.10 : 0;
  const rate = baseRate + volumeBonus;
  const monthly = annuity(amount, rate / 100, term * 12);

  return (
    <div className="bb-screen-enter" style={{ background: BB.bg, minHeight: '100%', paddingBottom: 40, paddingTop: STATUS_PAD }}>
      {/* Hero */}
      <div style={{ padding: '24px 20px 8px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 24 }}>
          <BulderMark size={26} color={BB.pink}/>
          <span style={{ fontSize: 18, fontWeight: 700, color: BB.fg, letterSpacing: '-0.01em' }}>Bulder</span>
          <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{
              width: 28, height: 28, borderRadius: 999,
              background: 'linear-gradient(135deg, #E4D4FF 0%, #FFCCD0 100%)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 12, fontWeight: 700, color: '#0F1729',
            }}>N</div>
          </div>
        </div>
        <div style={{ fontSize: 13, color: BB.pink, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8 }}>
          Hei, {A.identity.firstName} 👋
        </div>
        <div style={{ fontSize: 30, fontWeight: 700, color: BB.fg, letterSpacing: '-0.02em', lineHeight: 1.1 }}>
          Flytt boliglånet<br/>fra <span style={{ color: BB.pink }}>DNB</span> på 10 min.
        </div>
        <div style={{ fontSize: 15, color: BB.fg2, marginTop: 12, lineHeight: 1.5 }}>
          Du er allerede Bulder-kunde, så dette går fort. Signér med BankID og vi ordner resten.
        </div>
      </div>

      {/* Rate calculator */}
      <div style={{ margin: '24px 16px 0', background: BB.surface, borderRadius: 10, padding: 20 }}>
        <div style={{ fontSize: 11, color: BB.fg3, textTransform: 'uppercase', fontWeight: 700, letterSpacing: '0.05em' }}>
          Beregn din rente
        </div>

        {/* Amount */}
        <div style={{ marginTop: 14 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
            <span style={{ fontSize: 14, color: BB.fg2 }}>Lånebeløp</span>
            <span style={{ fontSize: 22, fontWeight: 500, color: BB.fg, fontVariantNumeric: 'tabular-nums' }}>
              {fmtKr(amount)} <span style={{ fontSize: 14, color: BB.fg3 }}>kr</span>
            </span>
          </div>
          <RangeSlider min={500000} max={15000000} step={50000} value={amount} onChange={v => setState({ amount: v })}/>
        </div>

        {/* Property value */}
        <div style={{ marginTop: 18 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
            <span style={{ fontSize: 14, color: BB.fg2 }}>Boligverdi</span>
            <span style={{ fontSize: 22, fontWeight: 500, color: BB.fg, fontVariantNumeric: 'tabular-nums' }}>
              {fmtKr(propertyValue)} <span style={{ fontSize: 14, color: BB.fg3 }}>kr</span>
            </span>
          </div>
          <RangeSlider min={1000000} max={20000000} step={50000} value={propertyValue} onChange={v => setState({ propertyValue: v })}/>
        </div>

        {/* Term */}
        <div style={{ marginTop: 18 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
            <span style={{ fontSize: 14, color: BB.fg2 }}>Nedbetalingstid</span>
            <span style={{ fontSize: 17, fontWeight: 500, color: BB.fg, fontVariantNumeric: 'tabular-nums' }}>{term} år</span>
          </div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {[15, 20, 25, 30].map(y => (
              <Chip key={y} selected={term === y} onClick={() => setState({ term: y })}>{y} år</Chip>
            ))}
          </div>
        </div>

        {/* LTV indicator */}
        <div style={{
          marginTop: 18, padding: 12, borderRadius: 10, background: BB.surface2,
          display: 'flex', alignItems: 'center', gap: 10,
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" style={{ flexShrink: 0 }}>
            <circle cx="12" cy="12" r="10" stroke={BB.green} strokeWidth="2"/>
            <path d="M8 12.5l2.5 2.5L16 9.5" stroke={BB.green} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          <div style={{ fontSize: 13, color: BB.fg2, flex: 1 }}>
            Belåningsgrad <b style={{ color: BB.fg }}>{Math.round(ltv * 100)} %</b>
            {ltv <= 0.60 && <span style={{ color: BB.green, marginLeft: 6 }}>· beste rente</span>}
            {ltv > 0.60 && ltv <= 0.75 && <span style={{ color: BB.fg3, marginLeft: 6 }}>· god rente</span>}
            {ltv > 0.75 && <span style={{ color: BB.amber, marginLeft: 6 }}>· høyere rente</span>}
          </div>
        </div>
      </div>

      {/* Result */}
      <div style={{ margin: '16px 16px 0', padding: 20, borderRadius: 10, background: BB.pink, color: '#fff' }}>
        <div style={{ fontSize: 12, textTransform: 'uppercase', fontWeight: 700, letterSpacing: '0.05em', opacity: 0.8 }}>
          Din rente hos Bulder
        </div>
        <div key={rate} className="bb-number-flash" style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 4 }}>
          <span style={{ fontSize: 54, fontWeight: 500, letterSpacing: '-0.03em', fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>
            {fmtPct(rate)}
          </span>
          <span style={{ fontSize: 24 }}>%</span>
          <span style={{ fontSize: 14, opacity: 0.8, marginLeft: 'auto' }}>nom. rente</span>
        </div>
        <div style={{
          marginTop: 16, paddingTop: 14,
          borderTop: '1px solid rgba(255,255,255,0.18)',
          display: 'flex', justifyContent: 'space-between',
        }}>
          <div>
            <div style={{ fontSize: 12, opacity: 0.8 }}>Pr. måned</div>
            <div key={monthly} className="bb-number-flash" style={{ fontSize: 22, fontWeight: 500, fontVariantNumeric: 'tabular-nums', marginTop: 2 }}>
              {fmtKr(monthly)} kr
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 12, opacity: 0.8 }}>Effektiv rente</div>
            <div style={{ fontSize: 17, fontWeight: 500, marginTop: 2, fontVariantNumeric: 'tabular-nums' }}>
              {fmtPct(rate + 0.18)} %
            </div>
          </div>
        </div>
      </div>

      {/* Social proof */}
      <div style={{ padding: '24px 20px 12px', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ display: 'flex' }}>
          {[0,1,2,3].map(i => (
            <div key={i} style={{
              width: 28, height: 28, borderRadius: 999,
              background: ['#E4D4FF','#FFCCD0','#CCFFCC','#FFF8BF'][i],
              marginLeft: i === 0 ? 0 : -8,
              border: `2px solid ${BB.bg}`,
            }}/>
          ))}
        </div>
        <div style={{ fontSize: 13, color: BB.fg2 }}>
          <b style={{ color: BB.fg }}>127 312</b> har flyttet lånet til Bulder
        </div>
      </div>

      {/* CTA */}
      <div style={{ padding: '12px 16px 0' }}>
        <PrimaryButton onClick={onNext}>Søk boliglån <span style={{ marginLeft: 4 }}>→</span></PrimaryButton>
        <div style={{ textAlign: 'center', fontSize: 12, color: BB.fg3, marginTop: 14, lineHeight: 1.5 }}>
          Effektiv rente {fmtPct(rate + 0.18)} %, {fmtKr(amount)} kr over {term} år.<br/>
          Totalt {fmtKr(monthly * term * 12)} kr. Rentetak forutsetter BSU eller lønn inn.
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 1. BANKID AUTH
// ─────────────────────────────────────────────────────────────
function BankIDScreen({ state, setState, onNext, onBack }) {
  const A = window.APPLICANT;
  const [phase, setPhase] = useState('input'); // input → sending → approved
  const fnr = state.fnr || A.identity.fnr;
  const phone = state.phone || A.identity.phone;

  const maskedFnr = fnr.replace(/\s/g, '').slice(0, 6) + ' •••••';
  const maskedPhone = '••• ' + phone.replace(/\D/g, '').slice(-4, -2) + ' ' + phone.replace(/\D/g, '').slice(-2);

  const startBankID = () => {
    setPhase('sending');
    setState({ fnr, phone });
    setTimeout(() => setPhase('approved'), 2400);
    setTimeout(() => onNext(), 3600);
  };

  return (
    <div className="bb-screen-enter" style={{ background: BB.bg, minHeight: '100%', paddingBottom: 40, paddingTop: STATUS_PAD }}>
      <div style={{ padding: '12px 20px 0' }}>
        <GlyphBack onClick={onBack}/>
      </div>

      {phase === 'input' && (
        <>
          <div style={{ padding: '16px 20px 0' }}>
            <div style={{ fontSize: 28, fontWeight: 700, color: BB.fg, letterSpacing: '-0.02em', lineHeight: 1.15 }}>
              Velkommen tilbake,<br/>{A.identity.firstName}.
            </div>
            <div style={{ fontSize: 15, color: BB.fg2, marginTop: 10, lineHeight: 1.5 }}>
              Bekreft med BankID så henter vi inntekt fra Skatteetaten og bolig fra Kartverket.
            </div>
          </div>

          <div style={{ padding: '24px 16px 0' }}>
            <div style={{ background: BB.surface, borderRadius: 10, padding: 4 }}>
              <div style={{ padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 14, borderBottom: `1px solid ${BB.divider}` }}>
                <div style={{
                  width: 42, height: 42, borderRadius: 999,
                  background: 'linear-gradient(135deg, #E4D4FF 0%, #FFCCD0 100%)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 16, fontWeight: 700, color: '#0F1729', flexShrink: 0,
                }}>{A.identity.firstName[0]}{A.identity.lastName[0]}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 15, color: BB.fg, fontWeight: 500 }}>{A.identity.fullName}</div>
                  <div style={{ fontSize: 12, color: BB.fg3, marginTop: 2 }}>Kunde siden 2019</div>
                </div>
                <span style={{ padding: '3px 8px', borderRadius: 999, background: 'rgba(133,255,134,0.15)', color: BB.green, fontSize: 11, fontWeight: 700 }}>
                  ● PÅLOGGET
                </span>
              </div>
              <div style={{ padding: '12px 18px', display: 'flex', justifyContent: 'space-between', fontSize: 13, color: BB.fg3 }}>
                <span>Fødselsnummer</span>
                <span style={{ color: BB.fg, fontFamily: 'ui-monospace, Menlo, monospace', letterSpacing: '0.05em' }}>{maskedFnr}</span>
              </div>
              <div style={{ padding: '4px 18px 12px', display: 'flex', justifyContent: 'space-between', fontSize: 13, color: BB.fg3 }}>
                <span>Mobilnummer</span>
                <span style={{ color: BB.fg, fontFamily: 'ui-monospace, Menlo, monospace' }}>+47 {maskedPhone}</span>
              </div>
            </div>
            <button style={{
              width: '100%', marginTop: 10, padding: '10px', background: 'none',
              border: 'none', color: BB.fg3, fontSize: 13, cursor: 'pointer',
            }}>Ikke meg? Logg inn som annen bruker</button>
          </div>

          <div style={{ padding: '16px 20px 0', display: 'flex', alignItems: 'flex-start', gap: 10 }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" style={{ marginTop: 2, flexShrink: 0 }}>
              <rect x="4" y="10" width="16" height="11" rx="2" stroke={BB.fg3} strokeWidth="1.8"/>
              <path d="M8 10V7a4 4 0 0 1 8 0v3" stroke={BB.fg3} strokeWidth="1.8"/>
            </svg>
            <div style={{ fontSize: 12, color: BB.fg3, lineHeight: 1.5 }}>
              Kryptert forbindelse. Vi deler aldri fødselsnummeret ditt med tredjepart.
            </div>
          </div>

          <div style={{ padding: '16px 16px 0' }}>
            <PrimaryButton onClick={startBankID}>
              <span style={{
                display: 'inline-flex', alignItems: 'center', gap: 8, fontWeight: 500,
              }}>
                Fortsett med <b style={{ fontWeight: 700 }}>BankID</b>
              </span>
            </PrimaryButton>
          </div>
        </>
      )}

      {phase === 'sending' && (
        <div style={{
          padding: '60px 20px 0', display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center',
        }}>
          <div style={{
            width: 110, height: 110, borderRadius: 999, background: BB.surface,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            position: 'relative',
          }}>
            <div style={{
              position: 'absolute', inset: 0, borderRadius: 999,
              border: `3px solid ${BB.pink}`, borderTopColor: 'transparent',
              animation: 'bulderSpin 1.2s linear infinite',
            }}/>
            <div style={{ fontSize: 34, fontWeight: 700, color: BB.fg }}>BankID</div>
          </div>
          <div style={{ fontSize: 22, fontWeight: 700, color: BB.fg, marginTop: 32, letterSpacing: '-0.01em' }}>
            Åpne BankID-appen
          </div>
          <div style={{ fontSize: 15, color: BB.fg2, marginTop: 10, maxWidth: 280, lineHeight: 1.5 }}>
            Vi har sendt deg et varsel. Godkjenn for å fortsette.
          </div>
          <div style={{
            marginTop: 24, padding: '10px 16px', borderRadius: 999,
            background: BB.surface, fontSize: 13, color: BB.fg2,
            fontFamily: 'ui-monospace, Menlo, monospace',
            letterSpacing: '0.1em',
          }}>
            Kontrollkode: <b style={{ color: BB.fg, marginLeft: 6 }}>TRYGG · HUS · ROLIG</b>
          </div>
        </div>
      )}

      {phase === 'approved' && (
        <div style={{
          padding: '60px 20px 0', display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center',
        }}>
          <svg width="100" height="100" viewBox="0 0 100 100">
            <circle cx="50" cy="50" r="45" fill={BB.green}/>
            <path d="M30 52 L45 67 L72 38" stroke="#0F1729" strokeWidth="6" strokeLinecap="round" strokeLinejoin="round" fill="none"
              style={{ strokeDasharray: 60, animation: 'bulderCheckDraw 0.5s ease-out forwards' }}/>
          </svg>
          <div style={{ fontSize: 22, fontWeight: 700, color: BB.fg, marginTop: 24 }}>Verifisert</div>
          <div style={{ fontSize: 15, color: BB.fg2, marginTop: 8 }}>Henter inntekt fra Skatteetaten …</div>
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 2. PROPERTY — Auto-detected from Kartverket (owner match)
// ─────────────────────────────────────────────────────────────
function PropertyScreen({ state, setState, onNext, onBack }) {
  const [detecting, setDetecting] = useState(!state.property?.confirmed);
  const [selected, setSelected] = useState(state.property || null);

  useEffect(() => {
    if (!detecting) return;
    const t = setTimeout(() => {
      setSelected({ ...state.property, confirmed: true });
      setDetecting(false);
    }, 1200);
    return () => clearTimeout(t);
  }, []);

  const A = window.APPLICANT;
  const p = A.property;

  return (
    <div className="bb-screen-enter" style={{ background: BB.bg, minHeight: '100%', paddingBottom: 40, paddingTop: STATUS_PAD }}>
      <div style={{ padding: '12px 20px 0' }}>
        <GlyphBack onClick={onBack}/>
      </div>

      <div style={{ padding: '16px 20px 0' }}>
        <div style={{ fontSize: 28, fontWeight: 700, color: BB.fg, letterSpacing: '-0.02em', lineHeight: 1.15 }}>
          Vi fant boligen din
        </div>
        <div style={{ fontSize: 15, color: BB.fg2, marginTop: 10 }}>
          Hentet fra Kartverket og Eiendomsverdi mot ditt fødselsnummer.
        </div>
      </div>

      {detecting && (
        <div style={{ padding: '20px 20px 0' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16, color: BB.fg3, fontSize: 13 }}>
            <Spinner size={14} color={BB.pink}/> Slår opp mot Kartverket …
          </div>
          <div className="bb-shimmer" style={{ height: 200, borderRadius: 10 }}/>
          <div className="bb-shimmer" style={{ height: 160, borderRadius: 10, marginTop: 12 }}/>
        </div>
      )}

      {!detecting && selected && (
        <div style={{ padding: '20px 16px 0' }}>
          {/* Hero */}
          <div style={{
            borderRadius: 10, overflow: 'hidden', position: 'relative',
            background: `linear-gradient(180deg, rgba(15,23,41,0) 30%, rgba(15,23,41,0.92) 100%), url(https://images.unsplash.com/photo-1572120360610-d971b9d7767c?w=700) center/cover`,
            padding: 18, minHeight: 220, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
          }}>
            <div style={{ position: 'absolute', top: 14, right: 14, display: 'flex', gap: 6 }}>
              <span style={{
                padding: '4px 10px', borderRadius: 999, background: 'rgba(15,23,41,0.6)',
                backdropFilter: 'blur(8px)', fontSize: 11, color: '#fff', fontWeight: 600,
              }}>● Din bolig</span>
            </div>
            <div style={{ fontSize: 11, color: '#fff', opacity: 0.7, textTransform: 'uppercase', fontWeight: 700, letterSpacing: '0.05em' }}>
              Verditakst · Eiendomsverdi
            </div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 4 }}>
              <span style={{ fontSize: 34, fontWeight: 500, color: '#fff', fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.02em', lineHeight: 1 }}>
                {fmtKr(p.value)}
              </span>
              <span style={{ fontSize: 17, color: '#fff', opacity: 0.8 }}>kr</span>
              <span style={{ marginLeft: 'auto', padding: '3px 8px', borderRadius: 999, background: BB.green, color: '#0F1729', fontSize: 11, fontWeight: 700 }}>
                +{Math.round(((p.value - p.purchasePrice) / p.purchasePrice) * 100)} %
              </span>
            </div>
            <div style={{ fontSize: 14, color: '#fff', opacity: 0.85, marginTop: 6 }}>
              {p.address}, {p.city}
            </div>
          </div>

          {/* Facts */}
          <div style={{ marginTop: 14, background: BB.surface, borderRadius: 10, padding: '4px 18px' }}>
            <KVRow label="Boligtype" value={`${p.estateType} · ${p.ownership.split(' · ')[0]}`}/>
            <KVRow label="Eierandel" value={p.ownerFraction + ' (med Sandra)'}/>
            <KVRow label="Primærrom" value={`${p.usageArea} m²`}/>
            <KVRow label="Byggeår" value={p.buildYear}/>
            <KVRow label="Kjøpspris (2019)" value={`${fmtKr(p.purchasePrice)} kr`}/>
            <KVRow label="Fellesgjeld" value={`${fmtKr(p.sharedDebt)} kr`}/>
            <KVRow label="Energimerke" value={
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                <span style={{
                  width: 20, height: 20, borderRadius: 4, background: '#E74C3C',
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  color: '#fff', fontSize: 11, fontWeight: 700,
                }}>{p.energyLabel}</span>
              </span>
            } border={false}/>
          </div>

          {/* Current mortgage — DNB */}
          <div style={{ marginTop: 14, padding: 16, borderRadius: 10, background: BB.surface, border: `1px solid ${BB.line}` }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{
                width: 36, height: 36, borderRadius: 8, background: '#00343E',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: '#fff', fontWeight: 700, fontSize: 13, letterSpacing: '0.02em', flexShrink: 0,
              }}>DNB</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 15, color: BB.fg, fontWeight: 500 }}>Pant registrert hos DNB</div>
                <div style={{ fontSize: 12, color: BB.fg3, marginTop: 2 }}>
                  {fmtKr(p.currentMortgage.amount)} kr · tinglyst 6. feb 2020
                </div>
              </div>
              <span style={{ padding: '4px 8px', borderRadius: 999, background: 'rgba(254,77,91,0.15)', color: BB.pink, fontSize: 11, fontWeight: 700 }}>
                FLYTTES
              </span>
            </div>
          </div>
        </div>
      )}

      <div style={{ padding: '24px 16px 0' }}>
        <PrimaryButton
          onClick={() => { setState({ propertyValue: p.value, property: { ...p, addr: p.address, confirmed: true } }); onNext(); }}
          disabled={detecting}>
          Ja, dette er riktig →
        </PrimaryButton>
        <button style={{
          width: '100%', marginTop: 10, padding: '12px', background: 'none',
          border: 'none', color: BB.fg2, fontSize: 14, cursor: 'pointer',
        }}>Jeg skal låne til en annen bolig</button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 3. LOAN DETAILS — amount, term, purpose
// ─────────────────────────────────────────────────────────────
function LoanScreen({ state, setState, onNext, onBack }) {
  const { amount, propertyValue, term, purpose, currentRate, kundeutbytte } = state;
  const ltv = amount / propertyValue;
  const baseRate = ltv <= 0.60 ? 5.14 : ltv <= 0.75 ? 5.34 : 5.69;
  const volumeBonus = amount >= 2_000_000 ? -0.10 : 0;
  const rate = baseRate + volumeBonus;
  const monthly = annuity(amount, rate / 100, term * 12);
  const monthlySavings = purpose === 'flytte' ? Math.round(annuity(amount, currentRate / 100, term * 12) - monthly) : 0;
  // Kundeutbytte — capped at 4M combined loan + innskudd for a couple. 2026 est. ~0.35%.
  // For Nicolai+Sandra: ~min(loan, 4M) covered -> est 13 300 kr/year (his half ~6 650).
  // Simple model: 0.35% of min(amount, 4_000_000) capped at 14000 per person (28000 couple)
  const A = window.APPLICANT;
  const hasSpouse = A.identity.maritalStatus === 'Gift';
  const loanForUtbytte = Math.min(amount, hasSpouse ? 4_000_000 : 2_000_000);
  const depositForUtbytte = Math.min(A.deposits.total, hasSpouse ? 4_000_000 : 2_000_000);
  const yearlyUtbytte = kundeutbytte
    ? Math.min(Math.round((loanForUtbytte + depositForUtbytte) * 0.0035), hasSpouse ? 28000 : 14000)
    : 0;
  const monthlyUtbytte = Math.round(yearlyUtbytte / 12);
  const totalSavings = monthlySavings + monthlyUtbytte;

  return (
    <div className="bb-screen-enter" style={{ background: BB.bg, minHeight: '100%', paddingBottom: 40, paddingTop: STATUS_PAD }}>
      <div style={{ padding: '12px 20px 0' }}>
        <GlyphBack onClick={onBack}/>
      </div>

      <div style={{ padding: '16px 20px 0' }}>
        <div style={{ fontSize: 28, fontWeight: 700, color: BB.fg, letterSpacing: '-0.02em', lineHeight: 1.15 }}>
          Hva trenger du?
        </div>
      </div>

      {/* Purpose */}
      <div style={{ padding: '20px 20px 0' }}>
        <div style={{ fontSize: 13, color: BB.fg3, marginBottom: 10, textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700 }}>
          Hva gjelder det?
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {[
            { k: 'flytte', label: 'Flytte boliglån til Bulder', hint: 'Samme bolig, lavere rente' },
            { k: 'kjope',  label: 'Kjøpe ny bolig',               hint: 'Finansieringsbevis · 48 timer' },
            { k: 'refi',   label: 'Refinansiere og frigjøre',     hint: 'Øke lånet mot samme bolig' },
          ].map(o => (
            <button key={o.k} onClick={() => setState({ purpose: o.k })} style={{
              display: 'flex', alignItems: 'center', gap: 14,
              padding: '14px 16px', borderRadius: 10,
              background: BB.surface,
              border: `1.5px solid ${purpose === o.k ? BB.pink : 'transparent'}`,
              cursor: 'pointer', textAlign: 'left', width: '100%',
              color: BB.fg, transition: 'border-color 0.15s ease',
            }}>
              <div style={{
                width: 22, height: 22, borderRadius: 999,
                border: `2px solid ${purpose === o.k ? BB.pink : BB.fg3}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                flexShrink: 0,
              }}>
                {purpose === o.k && <div style={{ width: 10, height: 10, borderRadius: 999, background: BB.pink }}/>}
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 15, fontWeight: 500 }}>{o.label}</div>
                <div style={{ fontSize: 12, color: BB.fg3, marginTop: 2 }}>{o.hint}</div>
              </div>
            </button>
          ))}
        </div>
      </div>

      {/* Amount + term sliders */}
      <div style={{ padding: '24px 16px 0' }}>
        <div style={{ background: BB.surface, borderRadius: 10, padding: 20 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
            <span style={{ fontSize: 14, color: BB.fg2 }}>Lånebeløp</span>
            <span style={{ fontSize: 24, fontWeight: 500, color: BB.fg, fontVariantNumeric: 'tabular-nums' }}>
              {fmtKr(amount)} <span style={{ fontSize: 14, color: BB.fg3 }}>kr</span>
            </span>
          </div>
          <RangeSlider min={500000} max={Math.min(propertyValue * 0.85, 15000000)} step={50000} value={amount}
            onChange={v => setState({ amount: v })}/>

          <div style={{ marginTop: 20 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
              <span style={{ fontSize: 14, color: BB.fg2 }}>Nedbetalingstid</span>
              <span style={{ fontSize: 17, fontWeight: 500, color: BB.fg, fontVariantNumeric: 'tabular-nums' }}>{term} år</span>
            </div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {[10, 15, 20, 25, 30].map(y => (
                <Chip key={y} selected={term === y} onClick={() => setState({ term: y })}>{y}</Chip>
              ))}
            </div>
          </div>
        </div>

        {/* Current loan details (only if "flytte") */}
        {purpose === 'flytte' && (
          <div style={{ marginTop: 14, background: BB.surface, borderRadius: 10, padding: 20 }}>
            <div style={{ fontSize: 13, color: BB.fg3, marginBottom: 14, textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700 }}>
              Dagens lån
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
              <span style={{ fontSize: 14, color: BB.fg2 }}>Nåværende rente</span>
              <span style={{ fontSize: 20, fontWeight: 500, color: BB.fg, fontVariantNumeric: 'tabular-nums' }}>
                {fmtPct(currentRate)} %
              </span>
            </div>
            <RangeSlider min={2} max={9} step={0.01} value={currentRate} onChange={v => setState({ currentRate: v })} suffix="%"/>
            <div style={{ fontSize: 13, color: BB.fg3, marginTop: 10 }}>
              Hos <span style={{ color: BB.fg }}>DNB Boliglån</span> · kontonr 1234 56 78901
            </div>
          </div>
        )}
      </div>

      {/* Savings banner */}
      {purpose === 'flytte' && monthlySavings > 100 && (
        <div style={{ margin: '14px 16px 0' }}>
          <div style={{
            padding: 18, borderRadius: kundeutbytte ? '10px 10px 0 0' : 10,
            background: BB.green, color: '#0F1729',
            display: 'flex', alignItems: 'center', gap: 14,
          }}>
            <div style={{
              width: 42, height: 42, borderRadius: 999, background: 'rgba(15,23,41,0.1)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
            }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
                <path d="M7 17L17 7M17 7H9M17 7V15" stroke="#0F1729" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', opacity: 0.6 }}>
                Du sparer hos Bulder
              </div>
              <div style={{ fontSize: 22, fontWeight: 500, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.01em' }}>
                {fmtKr(totalSavings)} kr <span style={{ fontSize: 14, opacity: 0.6 }}>/ mnd</span>
              </div>
              <div style={{ fontSize: 12, opacity: 0.7, marginTop: 2 }}>
                {fmtKr(totalSavings * 12)} kr i året · {fmtKr(totalSavings * term * 12)} kr totalt
              </div>
            </div>
          </div>

          {/* Kundeutbytte toggle */}
          <div style={{
            padding: '14px 18px', borderRadius: '0 0 10px 10px',
            background: '#0F1729', color: '#fff',
            display: 'flex', alignItems: 'center', gap: 12,
            border: `1px solid ${BB.line}`, borderTop: 'none',
          }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 8 }}>
                Regn med kundeutbytte
                <span style={{ fontSize: 10, padding: '2px 6px', borderRadius: 4, background: BB.pink, color: '#fff', fontWeight: 700, letterSpacing: '0.04em' }}>
                  NYTT
                </span>
              </div>
              <div style={{ fontSize: 12, color: BB.fg3, marginTop: 3, lineHeight: 1.4 }}>
                {kundeutbytte
                  ? <>+{fmtKr(yearlyUtbytte)} kr / år · din andel som eier av Sparebanken Norge</>
                  : <>Du deler overskuddet når vi tjener penger. Utbetales i april.</>
                }
              </div>
            </div>
            <Toggle on={kundeutbytte} onChange={v => setState({ kundeutbytte: v })}/>
          </div>
        </div>
      )}

      {/* Live rate */}
      <div style={{ marginTop: 14 }}>
        <RateSummary amount={amount} term={term} rate={rate} monthly={monthly}/>
      </div>

      <div style={{ padding: '24px 16px 0' }}>
        <PrimaryButton onClick={onNext} disabled={!purpose}>Fortsett →</PrimaryButton>
      </div>
    </div>
  );
}

Object.assign(window, {
  PortfolioScreen, BankIDScreen, PropertyScreen, LoanScreen,
});
