// screens-b.jsx — Mortgage application screens 4-7
// Income, Co-applicant, Review, Approved

const { useState: useStateB, useEffect: useEffectB } = React;

// ─────────────────────────────────────────────────────────────
// 4. INCOME / ECONOMY — auto-pulled from Skatteetaten
// ─────────────────────────────────────────────────────────────
function IncomeScreen({ state, setState, onNext, onBack }) {
  const [loaded, setLoaded] = useStateB(false);
  const [expanded, setExpanded] = useStateB(false);

  useEffectB(() => {
    const t = setTimeout(() => setLoaded(true), 900);
    return () => clearTimeout(t);
  }, []);

  const { income, otherDebt, employer, employmentType } = state;
  const A = window.APPLICANT;

  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 }}>
          Din økonomi
        </div>
        <div style={{ fontSize: 15, color: BB.fg2, marginTop: 10 }}>
          Hentet direkte fra Skatteetaten og Gjeldsregisteret. Gjennomsjekk at det stemmer.
        </div>
      </div>

      {!loaded && (
        <div style={{ padding: '24px 20px 0' }}>
          {[1,2,3].map(i => (
            <div key={i} className="bb-shimmer" style={{ height: 72, borderRadius: 10, marginBottom: 10 }}/>
          ))}
        </div>
      )}

      {loaded && (
        <>
          {/* Source banner */}
          <div style={{
            margin: '20px 16px 0', padding: '10px 14px', borderRadius: 10,
            background: 'rgba(9,38,214,0.12)', border: `1px solid rgba(9,38,214,0.35)`,
            display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <div style={{
              width: 22, height: 22, borderRadius: 999, background: BB.royal,
              display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
            }}>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none">
                <path d="M5 12l4 4 10-10" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </div>
            <div style={{ flex: 1, fontSize: 13, color: BB.fg }}>
              Hentet fra <b>Skatteetaten</b> · Oppdatert 19. april 2026
            </div>
          </div>

          {/* Income card */}
          <div style={{ padding: '16px 16px 0' }}>
            <Card>
              <div style={{ fontSize: 13, color: BB.fg3, textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700 }}>
                Årsinntekt 2025
              </div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 6 }}>
                <span style={{ fontSize: 36, fontWeight: 500, color: BB.fg, letterSpacing: '-0.02em', fontVariantNumeric: 'tabular-nums' }}>
                  {fmtKr(income)}
                </span>
                <span style={{ fontSize: 16, color: BB.fg2 }}>kr</span>
              </div>
              <div style={{
                marginTop: 14, paddingTop: 14, borderTop: `1px solid ${BB.divider}`,
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                <div style={{
                  width: 36, height: 36, borderRadius: 10, background: BB.surface2,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', color: BB.fg, fontWeight: 700, flexShrink: 0,
                }}>E</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 15, color: BB.fg, fontWeight: 500 }}>{A.employer.name}</div>
                  <div style={{ fontSize: 12, color: BB.fg3, marginTop: 2 }}>{A.employer.type} · {A.employer.role} · siden {A.employer.since}</div>
                </div>
                <button onClick={() => setExpanded(!expanded)} style={{
                  background: 'none', border: 'none', color: BB.pink, fontSize: 13, fontWeight: 500, cursor: 'pointer',
                }}>
                  {expanded ? 'Skjul' : 'Detaljer'}
                </button>
              </div>
              {expanded && (
                <div style={{ marginTop: 10, paddingTop: 10, borderTop: `1px solid ${BB.divider}` }}>
                  <KVRow label="Fastlønn" value={`${fmtKr(A.income.base)} kr`}/>
                  <KVRow label="Bonus 2025" value={`${fmtKr(A.income.bonus)} kr`}/>
                  <KVRow label="Overtid & tillegg" value={`${fmtKr(A.income.overtime)} kr`}/>
                  <KVRow label="Feriepenger (12%)" value={`${fmtKr(A.income.holiday)} kr`} border={false}/>
                </div>
              )}
            </Card>
          </div>

          {/* Debt card */}
          <div style={{ padding: '12px 16px 0' }}>
            <Card>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <div style={{ fontSize: 13, color: BB.fg3, textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700 }}>
                  Annen gjeld
                </div>
                <div style={{ fontSize: 11, color: BB.green, fontWeight: 700 }}>● INGEN</div>
              </div>
              {A.debts.length === 0 ? (
                <div style={{
                  marginTop: 10, padding: '18px 16px', borderRadius: 10, background: BB.surface2,
                  display: 'flex', alignItems: 'center', gap: 12,
                }}>
                  <div style={{
                    width: 36, height: 36, borderRadius: 999, background: 'rgba(133,255,134,0.15)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                  }}>
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                      <path d="M5 12l5 5L20 7" stroke={BB.green} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14, color: BB.fg, fontWeight: 500 }}>Ingen usikret gjeld</div>
                    <div style={{ fontSize: 12, color: BB.fg3, marginTop: 2 }}>
                      Gjeldsregisteret har ingen registreringer på deg.
                    </div>
                  </div>
                </div>
              ) : (
                <>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 6 }}>
                    <span style={{ fontSize: 28, fontWeight: 500, color: BB.fg, letterSpacing: '-0.02em', fontVariantNumeric: 'tabular-nums' }}>
                      {fmtKr(otherDebt)}
                    </span>
                    <span style={{ fontSize: 14, color: BB.fg2 }}>kr</span>
                  </div>
                  <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {A.debts.map(d => (
                      <DebtRow key={d.name} issuer={d.name} amount={d.amount} rate={d.rate} flag={d.flag}/>
                    ))}
                  </div>
                </>
              )}

              <div style={{
                marginTop: 12, fontSize: 12, color: BB.fg3, display: 'flex', alignItems: 'center', gap: 6,
              }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill={BB.fg3}>
                  <circle cx="12" cy="12" r="10" opacity="0.3"/>
                  <text x="12" y="17" textAnchor="middle" fontSize="14" fill={BB.fg} fontWeight="700">i</text>
                </svg>
                Fra Gjeldsregisteret · sjekket nå
              </div>
            </Card>
          </div>

          {/* Deposits / savings card */}
          <div style={{ padding: '12px 16px 0' }}>
            <Card>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <div style={{ fontSize: 13, color: BB.fg3, textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700 }}>
                  Sparing og innskudd
                </div>
                <div style={{ fontSize: 11, color: BB.fg3 }}>6 kontoer</div>
              </div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 6 }}>
                <span style={{ fontSize: 28, fontWeight: 500, color: BB.fg, letterSpacing: '-0.02em', fontVariantNumeric: 'tabular-nums' }}>
                  {fmtKr(A.deposits.total)}
                </span>
                <span style={{ fontSize: 14, color: BB.fg2 }}>kr</span>
              </div>
              <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 6 }}>
                {A.deposits.accounts.map(a => (
                  <div key={a.name} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '6px 0' }}>
                    <div>
                      <div style={{ fontSize: 14, color: BB.fg }}>{a.name}</div>
                      <div style={{ fontSize: 11, color: BB.fg3, marginTop: 1 }}>{a.issuer}</div>
                    </div>
                    <div style={{ fontSize: 14, color: BB.fg, fontVariantNumeric: 'tabular-nums', fontWeight: 500 }}>
                      {fmtKr(a.amount)} kr
                    </div>
                  </div>
                ))}
              </div>
            </Card>
          </div>

          {/* Children / dependents */}
          <div style={{ padding: '12px 16px 0' }}>
            <Card padding={0}>
              <div style={{ padding: '16px 18px', display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 15, color: BB.fg, fontWeight: 500 }}>Barn du forsørger</div>
                  <div style={{ fontSize: 12, color: BB.fg3, marginTop: 2 }}>Påvirker månedlige utgifter</div>
                </div>
                <Stepper value={state.children} onChange={v => setState({ children: v })}/>
              </div>
            </Card>
          </div>

          {/* Approval indicator */}
          <div style={{
            margin: '18px 16px 0', padding: 18, borderRadius: 10, background: BB.surface,
            border: `1px solid ${BB.line}`,
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <span style={{ fontSize: 14, color: BB.fg2 }}>Lånekapasitet</span>
              <span style={{ fontSize: 12, color: BB.green, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                ● Godkjent
              </span>
            </div>
            <div style={{ fontSize: 26, fontWeight: 500, color: BB.fg, marginTop: 4, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.02em' }}>
              {fmtKr(income * 5)} kr
            </div>
            <div style={{ fontSize: 12, color: BB.fg3, marginTop: 4 }}>
              Basert på 5× inntekt — du søker om {fmtKr(state.amount)} kr
            </div>
            <div style={{
              marginTop: 10, height: 6, borderRadius: 999, background: BB.surface2, overflow: 'hidden',
            }}>
              <div style={{
                width: `${Math.min(100, (state.amount / (income * 5)) * 100)}%`,
                height: '100%', background: BB.green, borderRadius: 999,
                transition: 'width 0.4s ease',
              }}/>
            </div>
          </div>

          <div style={{ padding: '24px 16px 0' }}>
            <PrimaryButton onClick={onNext}>Dette stemmer →</PrimaryButton>
            <button style={{
              width: '100%', marginTop: 10, padding: '12px', background: 'none',
              border: 'none', color: BB.fg2, fontSize: 14, cursor: 'pointer',
            }}>Korriger tallene</button>
          </div>
        </>
      )}
    </div>
  );
}

function DebtRow({ issuer, amount, rate, flag }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', padding: '10px 12px',
      background: BB.surface2, borderRadius: 10, gap: 10,
    }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 14, color: BB.fg, fontWeight: 500 }}>{issuer}</div>
        <div style={{ fontSize: 12, color: flag ? BB.amber : BB.fg3, marginTop: 2 }}>
          {fmtPct(rate, 1)} % rente {flag && '· høy'}
        </div>
      </div>
      <div style={{ fontSize: 15, color: BB.fg, fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>
        {fmtKr(amount)} kr
      </div>
    </div>
  );
}

function Stepper({ value, onChange }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, background: BB.surface2, borderRadius: 999, padding: 4 }}>
      <button onClick={() => onChange(Math.max(0, value - 1))} style={{
        width: 28, height: 28, borderRadius: 999, background: BB.surface3, border: 'none',
        color: BB.fg, fontSize: 18, cursor: 'pointer', lineHeight: 1,
      }}>−</button>
      <span style={{ minWidth: 18, textAlign: 'center', fontSize: 16, color: BB.fg, fontVariantNumeric: 'tabular-nums' }}>{value}</span>
      <button onClick={() => onChange(Math.min(9, value + 1))} style={{
        width: 28, height: 28, borderRadius: 999, background: BB.pink, border: 'none',
        color: '#fff', fontSize: 18, cursor: 'pointer', lineHeight: 1,
      }}>+</button>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 5. CO-APPLICANT (optional)
// ─────────────────────────────────────────────────────────────
function CoApplicantScreen({ state, setState, onNext, onBack }) {
  const { coApplicant } = state;
  const [invited, setInvited] = useStateB(!!coApplicant);

  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 }}>
          Skal dere søke<br/>sammen?
        </div>
        <div style={{ fontSize: 15, color: BB.fg2, marginTop: 10 }}>
          To inntekter gir ofte bedre rente og høyere lånekapasitet.
        </div>
      </div>

      {!invited && (
        <>
          <div style={{ padding: '24px 16px 0', display: 'flex', flexDirection: 'column', gap: 10 }}>
            <OptionCard
              selected={state.coApplicantChoice === 'yes'}
              onClick={() => setState({ coApplicantChoice: 'yes' })}
              icon={
                <div style={{ display: 'flex' }}>
                  <Avatar color="#9361F8" initial="M"/>
                  <Avatar color="#FE4D5B" initial="K" offset/>
                </div>
              }
              title="Ja, vi søker sammen"
              subtitle="Vi henter BankID fra medsøker etterpå"
            />
            <OptionCard
              selected={state.coApplicantChoice === 'no'}
              onClick={() => setState({ coApplicantChoice: 'no' })}
              icon={<Avatar color="#0926D6" initial="M"/>}
              title="Nei, jeg søker alene"
              subtitle="Bare din inntekt blir vurdert"
            />
          </div>

          {state.coApplicantChoice === 'yes' && (
            <div style={{ padding: '24px 20px 0' }}>
              <TextField
                label="Medsøkers mobilnummer"
                value={state.coApplicantPhone || ''}
                onChange={e => setState({ coApplicantPhone: e.target.value.replace(/\D/g,'').slice(0,10) })}
                placeholder="Vi sender en invitasjon"
                inputMode="numeric"
                prefix="+47"
                autoFocus
              />
              <div style={{
                marginTop: 12, padding: 12, borderRadius: 10, background: BB.surface,
                display: 'flex', gap: 10, alignItems: 'flex-start',
              }}>
                <div style={{
                  width: 22, height: 22, borderRadius: 999, background: BB.royal,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                  color: '#fff', fontSize: 13, fontWeight: 700,
                }}>i</div>
                <div style={{ fontSize: 13, color: BB.fg2, lineHeight: 1.5 }}>
                  Medsøker får en lenke på SMS, signerer med BankID og ferdig. Søknaden din er allerede lagret.
                </div>
              </div>
            </div>
          )}
        </>
      )}

      <div style={{ padding: '24px 16px 0' }}>
        <PrimaryButton
          onClick={() => {
            if (state.coApplicantChoice === 'yes' && state.coApplicantPhone) {
              setState({ coApplicant: { phone: state.coApplicantPhone, name: 'Kari Nordmann' } });
            }
            onNext();
          }}
          disabled={!state.coApplicantChoice || (state.coApplicantChoice === 'yes' && (state.coApplicantPhone || '').length < 8)}
        >
          Fortsett →
        </PrimaryButton>
      </div>
    </div>
  );
}

function OptionCard({ selected, onClick, icon, title, subtitle }) {
  return (
    <button onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 14,
      padding: '16px', borderRadius: 10,
      background: BB.surface,
      border: `1.5px solid ${selected ? BB.pink : 'transparent'}`,
      cursor: 'pointer', textAlign: 'left', width: '100%',
      color: BB.fg, transition: 'border-color 0.15s ease',
    }}>
      {icon}
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 16, fontWeight: 500 }}>{title}</div>
        <div style={{ fontSize: 13, color: BB.fg3, marginTop: 2 }}>{subtitle}</div>
      </div>
      <div style={{
        width: 22, height: 22, borderRadius: 999,
        border: `2px solid ${selected ? BB.pink : BB.fg3}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        {selected && <div style={{ width: 10, height: 10, borderRadius: 999, background: BB.pink }}/>}
      </div>
    </button>
  );
}

function Avatar({ color, initial, offset }) {
  return (
    <div style={{
      width: 40, height: 40, borderRadius: 999, background: color,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      color: '#fff', fontWeight: 700, fontSize: 16,
      marginLeft: offset ? -12 : 0, border: offset ? `2px solid ${BB.surface}` : 'none',
      flexShrink: 0,
    }}>{initial}</div>
  );
}

// ─────────────────────────────────────────────────────────────
// 6. REVIEW — final summary
// ─────────────────────────────────────────────────────────────
function ReviewScreen({ state, onNext, onBack }) {
  const { amount, propertyValue, term, property, income } = 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 [agree, setAgree] = useStateB(false);

  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 }}>
          Ett blikk til,<br/>så er du ferdig.
        </div>
      </div>

      {/* Hero rate card */}
      <div style={{
        margin: '24px 16px 0', padding: 22, borderRadius: 10, background: BB.pink, color: '#fff',
        position: 'relative', overflow: 'hidden',
      }}>
        {/* Bulder staircase watermark */}
        <div style={{ position: 'absolute', right: -16, bottom: -16, opacity: 0.14 }}>
          <BulderMark size={160} color="#fff"/>
        </div>
        <div style={{ position: 'relative' }}>
          <div style={{ fontSize: 12, textTransform: 'uppercase', fontWeight: 700, letterSpacing: '0.05em', opacity: 0.8 }}>
            Din tilbudte rente
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 2 }}>
            <span style={{ fontSize: 64, fontWeight: 500, letterSpacing: '-0.03em', fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>
              {fmtPct(rate)}
            </span>
            <span style={{ fontSize: 28 }}>%</span>
          </div>
          <div style={{ fontSize: 14, opacity: 0.9, marginTop: 6 }}>nominell · {fmtPct(rate + 0.18)} % effektiv</div>

          <div style={{
            marginTop: 18, padding: '14px 16px', borderRadius: 10,
            background: 'rgba(15,23,41,0.3)', backdropFilter: 'blur(8px)',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          }}>
            <div>
              <div style={{ fontSize: 12, opacity: 0.8 }}>Pr. måned</div>
              <div style={{ fontSize: 24, fontWeight: 500, fontVariantNumeric: 'tabular-nums', marginTop: 2 }}>
                {fmtKr(monthly)} kr
              </div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 12, opacity: 0.8 }}>Bindende i</div>
              <div style={{ fontSize: 17, fontWeight: 500, marginTop: 2 }}>30 dager</div>
            </div>
          </div>
        </div>
      </div>

      <SummarySection title="Lån">
        <KVRow label="Formål" value={state.purpose === 'flytte' ? 'Flytte boliglån' : state.purpose === 'kjope' ? 'Kjøpe bolig' : 'Refinansiere'}/>
        <KVRow label="Lånebeløp" value={`${fmtKr(amount)} kr`} strong/>
        <KVRow label="Nedbetalingstid" value={`${term} år`}/>
        <KVRow label="Belåningsgrad" value={`${Math.round(ltv * 100)} %`} border={false}/>
      </SummarySection>

      <SummarySection title="Bolig">
        <KVRow label="Adresse" value={property ? property.addr : 'Ikke valgt'}/>
        <KVRow label="Verditakst" value={`${fmtKr(propertyValue)} kr`} border={false}/>
      </SummarySection>

      <SummarySection title="Søker">
        <KVRow label="Navn" value="Marius Olsen"/>
        <KVRow label="Inntekt" value={`${fmtKr(income)} kr`}/>
        {state.coApplicant && <KVRow label="Medsøker" value={state.coApplicant.name}/>}
        <KVRow label="Barn" value={state.children} border={false}/>
      </SummarySection>

      {/* Terms */}
      <div style={{ padding: '18px 16px 0' }}>
        <button onClick={() => setAgree(!agree)} style={{
          display: 'flex', gap: 12, padding: 16, borderRadius: 10,
          background: BB.surface, border: 'none', width: '100%', cursor: 'pointer',
          textAlign: 'left', alignItems: 'flex-start',
        }}>
          <div style={{
            width: 22, height: 22, borderRadius: 4, flexShrink: 0, marginTop: 1,
            background: agree ? BB.pink : 'transparent',
            border: `2px solid ${agree ? BB.pink : BB.fg3}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            transition: 'all 0.15s ease',
          }}>
            {agree && (
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                <path d="M5 12l5 5 9-10" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            )}
          </div>
          <div style={{ fontSize: 13, color: BB.fg2, lineHeight: 1.5 }}>
            Jeg samtykker til at Bulder henter informasjon fra Skatteetaten, Kartverket og Gjeldsregisteret, og til <u style={{ color: BB.fg }}>standard lånevilkår</u>.
          </div>
        </button>
      </div>

      <div style={{ padding: '20px 16px 0' }}>
        <PrimaryButton onClick={onNext} disabled={!agree}>
          Signer og send inn →
        </PrimaryButton>
        <div style={{ fontSize: 12, color: BB.fg3, textAlign: 'center', marginTop: 12, lineHeight: 1.5 }}>
          Beslutning på sekunder. Du kan angre i 14 dager.
        </div>
      </div>
    </div>
  );
}

function SummarySection({ title, children }) {
  return (
    <div style={{ padding: '18px 16px 0' }}>
      <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700, color: BB.fg3, padding: '0 4px 8px' }}>
        {title}
      </div>
      <div style={{ background: BB.surface, borderRadius: 10, padding: '4px 18px' }}>{children}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 7. APPROVED / DONE
// ─────────────────────────────────────────────────────────────
function ApprovedScreen({ state, onRestart }) {
  const { amount, propertyValue, term } = 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 [step, setStep] = useStateB(0);

  useEffectB(() => {
    const timers = [
      setTimeout(() => setStep(1), 700),
      setTimeout(() => setStep(2), 1500),
      setTimeout(() => setStep(3), 2300),
      setTimeout(() => setStep(4), 3000),
    ];
    return () => timers.forEach(clearTimeout);
  }, []);

  const phases = [
    { k: 'signed',   label: 'Søknad signert' },
    { k: 'analyzed', label: 'Kredittvurdering' },
    { k: 'verified', label: 'Verifisert mot Kartverket' },
    { k: 'decision', label: 'Beslutning' },
  ];

  if (step < 4) {
    return (
      <div style={{ background: BB.bg, minHeight: '100%', paddingTop: STATUS_PAD, padding: `${STATUS_PAD}px 20px 40px` }}>
        <div style={{ marginTop: 40, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <div style={{
            width: 92, height: 92, borderRadius: 999, background: BB.surface,
            display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative',
          }}>
            <Spinner size={44} color={BB.pink}/>
          </div>
          <div style={{ fontSize: 22, fontWeight: 700, color: BB.fg, marginTop: 28, letterSpacing: '-0.01em' }}>
            Behandler søknaden
          </div>
          <div style={{ fontSize: 14, color: BB.fg3, marginTop: 6 }}>Tar vanligvis mindre enn 40 sekunder</div>
        </div>

        <div style={{ marginTop: 40, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {phases.map((p, i) => {
            const done = step > i;
            const active = step === i;
            return (
              <div key={p.k} style={{
                display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
                borderRadius: 10, background: active ? BB.surface : 'transparent',
                border: `1px solid ${active ? BB.line : 'transparent'}`,
                transition: 'all 0.3s ease',
              }}>
                <div style={{
                  width: 24, height: 24, borderRadius: 999, flexShrink: 0,
                  background: done ? BB.green : active ? BB.surface2 : BB.surface2,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  {done && (
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                      <path d="M5 12l5 5 9-10" stroke="#0F1729" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  )}
                  {active && <Spinner size={14} color={BB.pink}/>}
                </div>
                <span style={{
                  fontSize: 15, color: done ? BB.fg : active ? BB.fg : BB.fg3,
                  fontWeight: active ? 500 : 400,
                }}>{p.label}</span>
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  return (
    <div className="bb-screen-enter" style={{ background: BB.bg, minHeight: '100%', paddingBottom: 40 }}>
      {/* Celebration hero */}
      <div style={{
        padding: `${STATUS_PAD + 24}px 20px 40px`, background: BB.pink, color: '#fff',
        position: 'relative', overflow: 'hidden',
      }}>
        {/* Bulder staircase pattern */}
        <div style={{
          position: 'absolute', right: -30, top: -30, bottom: -30, width: 200, opacity: 0.14,
          display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gridTemplateRows: 'repeat(4, 1fr)', gap: 2,
        }}>
          {Array.from({length: 8}).map((_, i) => (
            <BulderMark key={i} size={80} color="#fff"/>
          ))}
        </div>
        <div style={{ position: 'relative' }}>
          <svg width="56" height="56" viewBox="0 0 100 100" style={{ display: 'block' }}>
            <circle cx="50" cy="50" r="45" fill="#fff"/>
            <path d="M30 52 L45 67 L72 38" stroke={BB.pink} strokeWidth="6" strokeLinecap="round" strokeLinejoin="round" fill="none"
              style={{ strokeDasharray: 60, animation: 'bulderCheckDraw 0.5s ease-out forwards' }}/>
          </svg>
          <div style={{ fontSize: 30, fontWeight: 700, marginTop: 22, letterSpacing: '-0.02em', lineHeight: 1.1 }}>
            Innvilget.<br/>Velkommen til Bulder.
          </div>
        </div>
      </div>

      {/* Offer card */}
      <div style={{ padding: '0 16px', marginTop: -20 }}>
        <div style={{ background: BB.surface, borderRadius: 10, padding: 22, border: `1px solid ${BB.line}`, boxShadow: '0 2px 20px rgba(0,0,0,0.3)' }}>
          <div style={{ fontSize: 11, textTransform: 'uppercase', fontWeight: 700, letterSpacing: '0.05em', color: BB.fg3 }}>
            Lånetilbud
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 6 }}>
            <span style={{ fontSize: 44, fontWeight: 500, color: BB.fg, letterSpacing: '-0.02em', fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>
              {fmtKr(amount)}
            </span>
            <span style={{ fontSize: 18, color: BB.fg2 }}>kr</span>
          </div>
          <div style={{ fontSize: 15, color: BB.fg2, marginTop: 6 }}>
            {fmtPct(rate)} % nom. rente · {term} år
          </div>

          <div style={{
            marginTop: 14, padding: '12px 14px', borderRadius: 10, background: BB.surface2,
            display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: BB.fg2,
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill={BB.amber}>
              <circle cx="12" cy="12" r="10"/>
              <path d="M12 7v5M12 16v0.5" stroke="#0F1729" strokeWidth="2.2" strokeLinecap="round"/>
            </svg>
            Tilbudet er bindende i 30 dager
          </div>
        </div>
      </div>

      {/* Next steps */}
      <div style={{ padding: '20px 16px 0' }}>
        <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700, color: BB.fg3, padding: '0 4px 8px' }}>
          Neste steg
        </div>
        <div style={{ background: BB.surface, borderRadius: 10 }}>
          <NextStep num="1" title="Signer lånedokumenter" subtitle="Med BankID · 3 min"/>
          <NextStep num="2" title="Bulder flytter lånet for deg" subtitle="Vi sier opp hos DNB · du gjør ingenting"/>
          <NextStep num="3" title="Første avdrag" subtitle="1. juni 2026" last/>
        </div>
      </div>

      <div style={{ padding: '24px 16px 0' }}>
        <PrimaryButton onClick={onRestart}>Signer dokumenter →</PrimaryButton>
        <button onClick={onRestart} style={{
          width: '100%', marginTop: 10, padding: '12px', background: 'none',
          border: 'none', color: BB.fg2, fontSize: 14, cursor: 'pointer',
        }}>Start på nytt</button>
      </div>
    </div>
  );
}

function NextStep({ num, title, subtitle, last }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 14, padding: '14px 16px',
      borderBottom: last ? 'none' : `1px solid ${BB.divider}`,
    }}>
      <div style={{
        width: 30, height: 30, borderRadius: 999, background: BB.surface2,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: BB.fg, fontSize: 14, fontWeight: 700, flexShrink: 0,
      }}>{num}</div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 15, color: BB.fg, fontWeight: 500 }}>{title}</div>
        <div style={{ fontSize: 12, color: BB.fg3, marginTop: 2 }}>{subtitle}</div>
      </div>
    </div>
  );
}

Object.assign(window, {
  IncomeScreen, CoApplicantScreen, ReviewScreen, ApprovedScreen,
});
