// Result + Register screens
const T = window.TB;

// ─── Result Screen ────────────────────────────────────
function ResultScreen({ go, answers, mobile = false }) {
  const profile = deriveProfile(answers);
  return (
    <div style={{ minHeight: '100%', background: T.surface, fontFamily: T.font, color: T.ink2 }}>
      {/* Top */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: mobile ? '16px 20px' : '20px 40px',
        background: '#fff',
        borderBottom: `1px solid ${T.borderSoft}`,
      }}>
        <Logo size={mobile ? 18 : 20}/>
        <Badge tone="mint" icon={Icon.check}>Preliminary profile ready</Badge>
      </div>

      <div style={{
        padding: mobile ? '28px 20px 40px' : '48px 40px 56px',
        maxWidth: 980, margin: '0 auto', width: '100%', boxSizing: 'border-box',
      }}>
        {/* Headline */}
        <div style={{
          fontFamily: T.mono, fontSize: 11, color: T.muted,
          textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 10,
        }}>Your preliminary tax profile · Case CR-2189</div>
        <h1 style={{
          fontSize: mobile ? 30 : 42, fontWeight: 600,
          letterSpacing: -1, lineHeight: 1.1,
          color: T.ink, margin: '0 0 12px', textWrap: 'pretty',
        }}>{profile.headline}</h1>
        <p style={{ fontSize: 16, color: T.ink3, lineHeight: 1.55, maxWidth: 640, margin: '0 0 32px' }}>
          {profile.subline}
        </p>

        {/* Top stats */}
        <div style={{
          display: 'grid', gap: 14,
          gridTemplateColumns: mobile ? '1fr' : 'repeat(3, 1fr)',
          marginBottom: 18,
        }}>
          <StatCard
            label="Estimated refund"
            value={profile.refundRange}
            sub="Range based on your answers · Verified after document review"
            tone="mint"
            icon={Icon.euro}
            big
          />
          <StatCard
            label="Filing requirement"
            value={profile.mustFile ? 'Required' : 'Optional'}
            sub={profile.filingNote}
            tone={profile.mustFile ? 'amber' : 'mint'}
            icon={Icon.flag}
          />
          <StatCard
            label="Complexity"
            value={profile.complexity}
            sub={profile.complexityNote}
            tone={profile.complexity === 'High' ? 'rose' : profile.complexity === 'Medium' ? 'amber' : 'mint'}
            icon={Icon.chart}
          />
        </div>

        {/* Detail panels */}
        <div style={{
          display: 'grid', gap: 14,
          gridTemplateColumns: mobile ? '1fr' : '1.1fr 1fr',
        }}>
          {/* Documents */}
          <Card pad={24}>
            <SectionHead title="Documents you'll need" sub={`${profile.docs.length} items · personalised`} icon={Icon.doc}/>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 14 }}>
              {profile.docs.map(d => (
                <DocRow key={d.t} doc={d}/>
              ))}
            </div>
          </Card>

          {/* Why it matters / next steps */}
          <Card pad={24}>
            <SectionHead title="Recommended next steps" sub="Based on what you told us" icon={Icon.spark}/>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 14 }}>
              {profile.nextSteps.map((s, i) => (
                <div key={i} style={{
                  display: 'flex', gap: 12, padding: '12px 14px',
                  borderRadius: 12, border: `1px solid ${T.borderSoft}`,
                  background: T.surface,
                }}>
                  <div style={{
                    width: 26, height: 26, borderRadius: 999, flexShrink: 0,
                    background: '#fff', color: T.ink,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontFamily: T.mono, fontSize: 11, fontWeight: 600,
                    border: `1px solid ${T.border}`,
                  }}>{i + 1}</div>
                  <div>
                    <div style={{ fontSize: 14, fontWeight: 600, color: T.ink, marginBottom: 2 }}>{s.t}</div>
                    <div style={{ fontSize: 13, color: T.muted, lineHeight: 1.45 }}>{s.d}</div>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </div>

        {/* Advisor preview */}
        {profile.needsAdvisor && (
          <Card pad={24} style={{ marginTop: 14 }}>
            <SectionHead
              title="Advisors that match your profile"
              sub={`${profile.advisors.length} verified matches · You'll review before sharing anything`}
              icon={Icon.user}
            />
            <div style={{
              display: 'grid', gap: 12, marginTop: 16,
              gridTemplateColumns: mobile ? '1fr' : 'repeat(3, 1fr)',
            }}>
              {profile.advisors.map(a => <AdvisorCard key={a.n} a={a}/>)}
            </div>
          </Card>
        )}

        {/* CTA banner */}
        <div style={{
          marginTop: 22,
          background: T.ink, color: '#fff',
          borderRadius: 20, padding: mobile ? '24px 22px' : '32px 36px',
          position: 'relative', overflow: 'hidden',
        }}>
          <div style={{
            position: 'absolute', top: '-50%', right: '-10%',
            width: 360, height: 360, borderRadius: 999,
            background: 'radial-gradient(circle, rgba(58,210,159,0.28), transparent 65%)',
          }}/>
          <div style={{ position: 'relative', display: mobile ? 'block' : 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 32 }}>
            <div style={{ maxWidth: 480 }}>
              <div style={{ fontFamily: T.mono, fontSize: 11, color: 'rgba(255,255,255,0.6)', textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 8 }}>
                Save & continue
              </div>
              <h3 style={{ fontSize: mobile ? 22 : 26, fontWeight: 600, letterSpacing: -0.5, lineHeight: 1.2, margin: '0 0 10px' }}>
                Save your preliminary profile securely.
              </h3>
              <p style={{ fontSize: 14.5, color: 'rgba(255,255,255,0.75)', lineHeight: 1.55, margin: 0 }}>
                Create a secure account to save this profile, upload documents,
                and (optionally) get matched with the right advisor.
              </p>
            </div>
            <div style={{ marginTop: mobile ? 20 : 0, flexShrink: 0 }}>
              <Button variant="mint" size="lg" onClick={() => go('register')} iconRight={Icon.arrow}>
                Create secure account
              </Button>
              <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.55)', marginTop: 10, textAlign: mobile ? 'left' : 'right' }}>
                Email · password · GDPR consent · 30 sec
              </div>
            </div>
          </div>
        </div>

        {/* Reassurance */}
        <div style={{
          marginTop: 24, display: 'flex', gap: 22, flexWrap: 'wrap',
          fontSize: 12.5, color: T.muted,
        }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <span style={{ color: T.mintInk }}>{Icon.shield}</span> Your answers are stored encrypted
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <span style={{ color: T.mintInk }}>{Icon.check}</span> Nothing is shared without your explicit consent
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <span style={{ color: T.mintInk }}>{Icon.globe}</span> EU-only servers · Frankfurt
          </span>
        </div>
      </div>
    </div>
  );
}

function SectionHead({ title, sub, icon }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <div style={{
        width: 34, height: 34, borderRadius: 10,
        background: T.mintSoft, color: T.mintInk,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>{icon}</div>
      <div>
        <div style={{ fontSize: 15, fontWeight: 600, color: T.ink, letterSpacing: -0.2 }}>{title}</div>
        {sub && <div style={{ fontSize: 12.5, color: T.muted, marginTop: 1 }}>{sub}</div>}
      </div>
    </div>
  );
}

function StatCard({ label, value, sub, tone, icon, big }) {
  const tones = {
    mint: { bg: T.mintSoft, c: T.mintInk },
    amber: { bg: T.amberSoft, c: '#8A5A0F' },
    rose: { bg: T.roseSoft, c: '#A23541' },
    blue: { bg: T.blueSoft, c: '#2B5BD7' },
  }[tone] || { bg: T.surface, c: T.ink2 };
  return (
    <div style={{
      background: '#fff', borderRadius: 18,
      border: `1px solid ${T.border}`,
      padding: 22,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
        <div style={{
          fontFamily: T.mono, fontSize: 11, color: T.muted,
          textTransform: 'uppercase', letterSpacing: 0.7,
        }}>{label}</div>
        <div style={{
          width: 28, height: 28, borderRadius: 8,
          background: tones.bg, color: tones.c,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>{icon}</div>
      </div>
      <div style={{
        fontSize: big ? 30 : 24, fontWeight: 600,
        color: T.ink, letterSpacing: -0.8, lineHeight: 1.1,
      }}>{value}</div>
      {sub && (
        <div style={{ fontSize: 12.5, color: T.muted, marginTop: 8, lineHeight: 1.45 }}>{sub}</div>
      )}
    </div>
  );
}

function DocRow({ doc }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '10px 12px', borderRadius: 12,
      border: `1px solid ${T.borderSoft}`,
    }}>
      <div style={{
        width: 28, height: 28, borderRadius: 8,
        background: T.surface, color: T.ink2,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>{Icon.doc}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13.5, fontWeight: 500, color: T.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{doc.t}</div>
        <div style={{ fontSize: 12, color: T.muted, marginTop: 1 }}>{doc.s}</div>
      </div>
      <Badge tone={doc.req ? 'amber' : 'neutral'}>{doc.req ? 'Required' : 'Optional'}</Badge>
    </div>
  );
}

function AdvisorCard({ a }) {
  return (
    <div style={{
      padding: 16, borderRadius: 14,
      border: `1px solid ${T.border}`, background: T.surface,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
        <div style={{
          width: 40, height: 40, borderRadius: 999, flexShrink: 0,
          background: a.color, color: T.ink,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontWeight: 600, fontSize: 14,
        }}>{a.n.split(' ').map(w => w[0]).slice(0,2).join('')}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: T.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.n}</div>
          <div style={{ fontSize: 11.5, color: T.muted, marginTop: 1 }}>{a.l}</div>
        </div>
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, marginBottom: 12 }}>
        {a.tags.map(t => <Badge key={t} tone="neutral" style={{ fontSize: 11 }}>{t}</Badge>)}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ fontFamily: T.mono, fontSize: 13, color: T.mintInk, fontWeight: 600 }}>{a.match}% match</div>
        <span style={{ fontSize: 12, color: T.muted }}>{a.price}</span>
      </div>
    </div>
  );
}

// ─── Derive profile from answers ────────────────────────
function deriveProfile(a) {
  const it = a.income_types || [];
  const status = a.status;
  const hasComplex = it.includes('rsu') || it.includes('crypto') || it.includes('foreign') || it.includes('rental') || status === 'freelance' || status === 'founder';
  const highComplex = (it.includes('rsu') && it.includes('foreign')) || status === 'founder';
  const complexity = highComplex ? 'High' : hasComplex ? 'Medium' : 'Low';
  const refundLow = complexity === 'High' ? 1800 : complexity === 'Medium' ? 1240 : 720;
  const refundHigh = complexity === 'High' ? 4200 : complexity === 'Medium' ? 1860 : 1180;

  const mustFile = status === 'freelance' || status === 'founder' || it.includes('foreign') || it.includes('rental') || (a.living_in_germany === 'left');

  const docs = [
    { t: 'Lohnsteuerbescheinigung 2024', s: 'Annual wage statement from employer', req: it.includes('salary') || status === 'employee' },
    { t: 'Steuer-ID (Tax ID)', s: '11-digit identifier from your local tax office', req: true },
    it.includes('rsu') && { t: 'RSU vesting statements', s: 'From your equity admin (Carta, Schwab, etc.)', req: true },
    it.includes('crypto') && { t: 'Crypto transaction history', s: 'CSV from exchanges + on-chain wallets', req: true },
    it.includes('foreign') && { t: 'Foreign income statements', s: 'For double-taxation relief (Anlage AUS)', req: true },
    it.includes('rental') && { t: 'Rental income records', s: 'Anlage V — income and expenses per property', req: true },
    status === 'freelance' && { t: 'Income & expense records', s: 'Einnahmen-Überschuss-Rechnung (EÜR)', req: true },
    { t: 'Insurance contributions (KV/PV)', s: 'Annual statement from your insurer', req: false },
    { t: 'Commute records', s: 'Pendlerpauschale — distance to work', req: false },
  ].filter(Boolean);

  const helpWith = a.help_with || [];
  const needsAdvisor = a.advisor !== 'diy' && (complexity !== 'Low' || helpWith.includes('match'));

  const advisors = [
    { n: 'Lena Reinhardt', l: 'Steuerberaterin · Berlin Mitte', match: 98, tags: ['Tech/RSU', 'English', 'Remote'], price: 'From €280', color: '#E8F3FF' },
    { n: 'Steuerkanzlei Nord', l: 'Boutique firm · Hamburg', match: 94, tags: ['Expat focus', 'EN/DE', 'Same-day'], price: 'From €240', color: T.sand },
    { n: 'Jonas Albrecht', l: 'Steuerberater · Munich', match: 89, tags: ['Founder', 'GmbH', 'VC-friendly'], price: 'From €310', color: '#FCE8EA' },
  ];

  let headline, subline;
  if (complexity === 'High') {
    headline = "You have a complex case — and that usually means there's real money to claim back.";
    subline = "We've structured what applies to you, flagged the moving parts, and shortlisted advisors who handle exactly this kind of case.";
  } else if (complexity === 'Medium') {
    headline = "Your case is manageable — but worth doing properly.";
    subline = "A short list of documents, a sensible refund estimate, and (if you want) advisors who specialise in your situation.";
  } else {
    headline = "Good news — your case is straightforward.";
    subline = "You're likely owed a refund, and a few simple documents can get you there. Here's everything you need.";
  }

  return {
    headline, subline,
    refundRange: `€${refundLow.toLocaleString()}–${refundHigh.toLocaleString()}`,
    mustFile,
    filingNote: mustFile ? 'Pflichtveranlagung — required by law' : 'Antragsveranlagung — refund still possible',
    complexity,
    complexityNote: complexity === 'High'
      ? 'Multiple jurisdictions or business income'
      : complexity === 'Medium' ? 'Has equity, foreign, or self-emp factors' : 'Salary-only or simple investments',
    docs,
    nextSteps: [
      { t: 'Save your preliminary profile', d: 'A secure account so you can come back to this exact state.' },
      { t: 'Upload your documents', d: 'Encrypted at rest. Only you control who sees them.' },
      needsAdvisor
        ? { t: 'Review your matched advisors', d: 'You stay in control — approve each one before they see your case.' }
        : { t: 'Continue self-service filing', d: "We'll guide you through ELSTER-ready exports." },
      { t: 'File before July 31', d: 'Our reminders + checklist keep you on track.' },
    ],
    needsAdvisor,
    advisors,
  };
}

// ─── Register screen ──────────────────────────────────
function RegisterScreen({ go, mobile = false }) {
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [consent, setConsent] = React.useState(true);
  const valid = email.includes('@') && password.length >= 8 && consent;

  return (
    <div style={{
      minHeight: '100%', background: T.surface, fontFamily: T.font, color: T.ink2,
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: mobile ? '16px 20px' : '20px 40px', background: '#fff',
        borderBottom: `1px solid ${T.borderSoft}`,
      }}>
        <Logo size={mobile ? 18 : 20}/>
        <button onClick={() => go('result')} style={{
          background: 'none', border: 0, cursor: 'pointer',
          fontFamily: T.font, fontSize: 13, color: T.muted,
        }}>Back to results</button>
      </div>

      <div style={{
        flex: 1, display: mobile ? 'block' : 'grid',
        gridTemplateColumns: mobile ? undefined : '1fr 1fr',
        maxWidth: mobile ? '100%' : 1120, width: '100%',
        margin: '0 auto', padding: mobile ? 0 : '40px',
        gap: 56, boxSizing: 'border-box', alignItems: 'center',
      }}>
        {/* Left — value summary */}
        <div style={{ padding: mobile ? '28px 20px 8px' : 0 }}>
          <div style={{ fontFamily: T.mono, fontSize: 11, color: T.muted, textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 10 }}>
            Step 8 of 8 · Save your profile
          </div>
          <h1 style={{
            fontSize: mobile ? 28 : 38, fontWeight: 600,
            letterSpacing: -0.9, lineHeight: 1.1,
            color: T.ink, margin: '0 0 14px', textWrap: 'pretty',
          }}>Your preliminary tax profile is ready.</h1>
          <p style={{ fontSize: 16, color: T.ink3, lineHeight: 1.55, margin: '0 0 24px', maxWidth: 460 }}>
            Create a secure account to save it, upload documents, and connect with the
            right tax expert when you're ready.
          </p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {[
              { i: Icon.shield, t: 'Encrypted at rest — Frankfurt servers' },
              { i: Icon.check, t: 'Nothing shared without your consent' },
              { i: Icon.user, t: 'Optional advisor matching · You choose' },
              { i: Icon.bell, t: 'Deadline reminders so nothing slips' },
            ].map(x => (
              <div key={x.t} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{
                  width: 26, height: 26, borderRadius: 8,
                  background: T.mintSoft, color: T.mintInk,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>{x.i}</div>
                <span style={{ fontSize: 14, color: T.ink3 }}>{x.t}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Right — form */}
        <div style={{ padding: mobile ? '24px 20px 40px' : 0 }}>
          <Card pad={mobile ? 24 : 32} style={{ boxShadow: '0 20px 60px rgba(11,27,59,0.08)' }}>
            <h3 style={{ fontSize: 20, fontWeight: 600, color: T.ink, letterSpacing: -0.4, margin: '0 0 6px' }}>
              Create your secure account
            </h3>
            <p style={{ fontSize: 13.5, color: T.muted, margin: '0 0 22px' }}>
              Takes 30 seconds. No payment required.
            </p>

            <div style={{ display: 'flex', gap: 8, marginBottom: 18 }}>
              <SocialBtn label="Continue with Google" />
              <SocialBtn label="Apple" iconOnly />
            </div>

            <div style={{
              display: 'flex', alignItems: 'center', gap: 12, margin: '0 0 18px',
              fontSize: 12, color: T.faint,
            }}>
              <div style={{ flex: 1, height: 1, background: T.borderSoft }}/>
              or use email
              <div style={{ flex: 1, height: 1, background: T.borderSoft }}/>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <Field
                label="Email address"
                type="email" value={email}
                onChange={e => setEmail(e.target.value)}
                placeholder="you@example.com"
                required
              />
              <Field
                label="Password"
                type="password" value={password}
                onChange={e => setPassword(e.target.value)}
                placeholder="At least 8 characters"
                hint={password.length > 0 && password.length < 8 ? 'A few more characters — almost there.' : 'We never store this in plain text.'}
                required
              />
            </div>

            <label style={{
              display: 'flex', alignItems: 'flex-start', gap: 10,
              marginTop: 18, cursor: 'pointer',
            }}>
              <input
                type="checkbox" checked={consent}
                onChange={e => setConsent(e.target.checked)}
                style={{ marginTop: 3, accentColor: T.ink }}
              />
              <span style={{ fontSize: 12.5, color: T.muted, lineHeight: 1.5 }}>
                I agree to the Tax Bridge <a style={{ color: T.ink2, textDecoration: 'underline' }}>Terms</a> and{' '}
                <a style={{ color: T.ink2, textDecoration: 'underline' }}>Privacy Policy (DSGVO)</a>.
                My data stays in the EU and is never shared without my explicit consent.
              </span>
            </label>

            <div style={{ marginTop: 20 }}>
              <Button variant="primary" size="lg" full disabled={!valid} iconRight={Icon.arrow}
                onClick={() => go('dashboard')}>
                Save profile & continue
              </Button>
            </div>

            <div style={{
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              marginTop: 16, fontSize: 11.5, color: T.muted,
            }}>
              <span style={{ color: T.mintInk }}>{Icon.lock}</span>
              <span>AES-256 encryption · Two-factor available on next step</span>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

function SocialBtn({ label, iconOnly }) {
  return (
    <button style={{
      flex: iconOnly ? '0 0 auto' : 1, padding: '11px 14px',
      background: '#fff', border: `1px solid ${T.border}`, borderRadius: 12,
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
      fontFamily: T.font, fontSize: 14, fontWeight: 500, color: T.ink2,
      cursor: 'pointer',
    }}>
      {/* simple "G" */}
      <span style={{
        width: 18, height: 18, borderRadius: 999,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 11, fontWeight: 700, color: T.ink, background: '#F4F4F6',
      }}>{iconOnly ? '' : 'G'}</span>
      {!iconOnly && label}
      {iconOnly && (
        <svg width="14" height="16" viewBox="0 0 14 16" fill={T.ink}>
          <path d="M11 8.5c0-2.2 1.8-3.2 1.9-3.3-1-1.5-2.6-1.7-3.2-1.7-1.4-.15-2.7.8-3.4.8-.7 0-1.8-.78-3-.76C1.65 3.6.1 4.55 0 7c-.1 1.7.7 4.6 1.9 6.2.6.8 1.3 1.7 2.2 1.65.9-.03 1.2-.55 2.3-.55 1.1 0 1.4.55 2.3.53.95-.02 1.55-.8 2.13-1.6.67-.94.95-1.85.96-1.9-.02-.01-1.83-.7-1.85-2.8zM9 2c.5-.65.9-1.5.8-2.4-.78.03-1.7.5-2.25 1.15C7.1 1.3 6.6 2.15 6.7 3c.85.07 1.75-.4 2.3-1z"/>
        </svg>
      )}
    </button>
  );
}

Object.assign(window, { ResultScreen, RegisterScreen, deriveProfile });
