// 8-question tax assessment flow — supports 3 styles (conversational, cards, stepper)
const T = window.TB;

const QUESTIONS = [
  {
    id: 'living_in_germany',
    title: 'Are you currently living in Germany?',
    sub: "We'll use this to figure out which kind of tax filing applies to you.",
    type: 'single',
    short: 'living',
    options: [
      { v: 'yes', l: 'Yes — I live in Germany', s: 'Resident for tax purposes', icon: Icon.home2, color: T.mintSoft, accent: T.mintInk },
      { v: 'moving', l: 'Moving here soon', s: 'Pre-arrival planning', icon: Icon.flag, color: T.blueSoft, accent: '#2B5BD7' },
      { v: 'left', l: 'I left Germany recently', s: 'Final-year filing', icon: Icon.globe, color: T.amberSoft, accent: '#8A5A0F' },
      { v: 'no', l: 'No — I never lived in Germany', s: 'Limited tax liability only', icon: Icon.globe, color: T.roseSoft, accent: '#A23541' },
    ],
  },
  {
    id: 'status',
    title: 'What is your current work status?',
    sub: 'Pick the one that best describes you. You can change this later.',
    type: 'single',
    short: 'status',
    options: [
      { v: 'employee', l: 'Employee', s: 'Salary from a German employer', icon: Icon.briefcase, color: T.mintSoft, accent: T.mintInk },
      { v: 'freelance', l: 'Freelancer · Selbstständig', s: 'Invoicing clients directly', icon: Icon.user, color: T.blueSoft, accent: '#2B5BD7' },
      { v: 'founder', l: 'Founder · Gesellschafter', s: 'Running a company in Germany', icon: Icon.spark, color: T.amberSoft, accent: '#8A5A0F' },
      { v: 'researcher', l: 'Researcher · Student', s: 'University, PhD, or stipend', icon: Icon.doc, color: T.roseSoft, accent: '#A23541' },
      { v: 'unemployed', l: 'Between jobs', s: 'Looking for work or on benefits', icon: Icon.clock, color: T.surface, accent: T.ink2 },
      { v: 'other', l: 'Other / multiple', s: "We'll handle the nuance next", icon: Icon.filter, color: T.surface, accent: T.ink2 },
    ],
  },
  {
    id: 'income_types',
    title: 'Which income types apply to you?',
    sub: 'Select all that you receive — even small amounts matter for filing.',
    type: 'multi',
    short: 'income',
    options: [
      { v: 'salary', l: 'Salary (W-2 equivalent)', icon: Icon.briefcase, color: T.mintSoft, accent: T.mintInk },
      { v: 'freelance', l: 'Freelance income', icon: Icon.user, color: T.blueSoft, accent: '#2B5BD7' },
      { v: 'foreign', l: 'Foreign income', s: 'Pay from outside Germany', icon: Icon.globe, color: T.blueSoft, accent: '#2B5BD7' },
      { v: 'investments', l: 'Investments · Dividends', icon: Icon.chart, color: T.amberSoft, accent: '#8A5A0F' },
      { v: 'rsu', l: 'RSUs · Stock options', s: 'Vesting events count', icon: Icon.spark, color: T.amberSoft, accent: '#8A5A0F' },
      { v: 'crypto', l: 'Crypto', s: 'Trading, staking, mining', icon: Icon.coins, color: T.amberSoft, accent: '#8A5A0F' },
      { v: 'rental', l: 'Rental income', icon: Icon.home2, color: T.roseSoft, accent: '#A23541' },
      { v: 'pension', l: 'Pension', icon: Icon.clock, color: T.surface, accent: T.ink2 },
    ],
  },
  {
    id: 'filed_before',
    title: 'Have you filed a German tax return before?',
    sub: "Don't worry if not — most expats haven't.",
    type: 'single',
    short: 'history',
    options: [
      { v: 'never', l: 'No — never filed in Germany', icon: Icon.spark, color: T.mintSoft, accent: T.mintInk },
      { v: 'once', l: 'Once, a while ago', icon: Icon.clock, color: T.blueSoft, accent: '#2B5BD7' },
      { v: 'yearly', l: 'Yes, I file every year', icon: Icon.check, color: T.amberSoft, accent: '#8A5A0F' },
      { v: 'partial', l: "I started but didn't finish", icon: Icon.doc, color: T.surface, accent: T.ink2 },
    ],
  },
  {
    id: 'advisor',
    title: 'Do you already have a German tax advisor?',
    sub: 'A Steuerberater handles taxes for individuals and businesses.',
    type: 'single',
    short: 'advisor',
    options: [
      { v: 'none', l: 'No — looking for one', s: "We'll suggest verified advisors", icon: Icon.search, color: T.mintSoft, accent: T.mintInk },
      { v: 'have', l: 'Yes — already working with one', s: 'Share your profile with them', icon: Icon.user, color: T.blueSoft, accent: '#2B5BD7' },
      { v: 'past', l: "I had one, but I'm looking again", s: 'Switching or shopping around', icon: Icon.arrow, color: T.amberSoft, accent: '#8A5A0F' },
      { v: 'diy', l: 'I prefer to do it myself', s: 'Self-service tools only', icon: Icon.spark, color: T.surface, accent: T.ink2 },
    ],
  },
  {
    id: 'help_with',
    title: 'What do you need help with?',
    sub: 'Pick everything that applies.',
    type: 'multi',
    short: 'help',
    options: [
      { v: 'first', l: 'My first German tax return', color: T.mintSoft, accent: T.mintInk, icon: Icon.spark },
      { v: 'refund', l: 'Maximising my refund', color: T.mintSoft, accent: T.mintInk, icon: Icon.euro },
      { v: 'cross_border', l: 'Cross-border or foreign income', color: T.blueSoft, accent: '#2B5BD7', icon: Icon.globe },
      { v: 'self_emp', l: 'Self-employment & VAT', color: T.blueSoft, accent: '#2B5BD7', icon: Icon.briefcase },
      { v: 'docs', l: 'Knowing which documents to collect', color: T.amberSoft, accent: '#8A5A0F', icon: Icon.doc },
      { v: 'match', l: 'Finding the right advisor', color: T.amberSoft, accent: '#8A5A0F', icon: Icon.user },
      { v: 'past', l: 'Cleaning up previous years', color: T.surface, accent: T.ink2, icon: Icon.clock },
    ],
  },
  {
    id: 'urgency',
    title: 'How urgent is this for you?',
    sub: 'The German tax deadline is July 31 — we plan around it.',
    type: 'single',
    short: 'urgency',
    options: [
      { v: 'asap', l: 'Deadline soon — I need help fast', s: 'Within 30 days', icon: Icon.clock, color: T.roseSoft, accent: '#A23541' },
      { v: 'planning', l: 'Just planning ahead', s: 'Comfortable timeline', icon: Icon.spark, color: T.mintSoft, accent: T.mintInk },
      { v: 'exploring', l: 'Just exploring my options', s: 'No specific date in mind', icon: Icon.globe, color: T.blueSoft, accent: '#2B5BD7' },
    ],
  },
  {
    id: 'save',
    title: 'Want to save your preliminary profile?',
    sub: "You'll see results either way — saving lets you continue later and (optionally) match with an advisor.",
    type: 'single',
    short: 'save',
    options: [
      { v: 'save', l: 'Yes — save my profile', s: 'Recommended · 30 seconds', icon: Icon.shield, color: T.mintSoft, accent: T.mintInk },
      { v: 'later', l: 'Just show me the results first', s: 'You can always save it after', icon: Icon.arrow, color: T.surface, accent: T.ink2 },
    ],
  },
];

// ─── Shared assessment state hook ────────────────────────
function useAssessment(answers, setAnswers, go) {
  const [stepIdx, setStepIdx] = React.useState(0);
  const q = QUESTIONS[stepIdx];
  const total = QUESTIONS.length;
  const value = answers[q.id];

  const canNext = q.type === 'multi' ? (value && value.length > 0) : Boolean(value);

  const setAnswer = React.useCallback((val) => {
    if (q.type === 'multi') {
      const cur = answers[q.id] || [];
      const nextVal = cur.includes(val) ? cur.filter(x => x !== val) : [...cur, val];
      setAnswers({ ...answers, [q.id]: nextVal });
    } else {
      setAnswers({ ...answers, [q.id]: val });
    }
  }, [q.id, q.type, answers, setAnswers]);

  const next = React.useCallback(() => {
    if (stepIdx === total - 1) {
      if (answers.save === 'save') go('register');
      else go('result');
    } else {
      setStepIdx(s => s + 1);
    }
  }, [stepIdx, total, answers.save, go]);

  const back = React.useCallback(() => {
    if (stepIdx === 0) go('home');
    else setStepIdx(s => s - 1);
  }, [stepIdx, go]);

  return { stepIdx, q, total, value, canNext, setAnswer, next, back };
}

// ─── Top-level dispatcher ─────────────────────────────────
function AssessmentScreen({ go, answers, setAnswers, mobile = false, style = 'conversational' }) {
  const a = useAssessment(answers, setAnswers, go);
  if (style === 'cards') return <CardStackFlow {...a} answers={answers} mobile={mobile} go={go}/>;
  if (style === 'stepper') return <StepperFlow {...a} answers={answers} mobile={mobile} go={go}/>;
  return <ConversationalFlow {...a} answers={answers} mobile={mobile} go={go}/>;
}

// ─── B · Conversational ──────────────────────────────────
function ConversationalFlow({ stepIdx, q, total, value, canNext, setAnswer, next, back, answers, mobile, go }) {
  const scrollRef = React.useRef(null);
  React.useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' });
    }
  }, [stepIdx, value]);

  // Build conversation history up to current step
  const messages = [];
  // Greeting
  messages.push({ from: 'a', kind: 'text', body: <>Hi! I'm the Tax&nbsp;Bridge assistant. I'll ask a few short questions to build your <strong>preliminary tax profile</strong>. Nothing is shared, nothing is saved until you say so.</> });
  for (let i = 0; i <= stepIdx; i++) {
    const qq = QUESTIONS[i];
    messages.push({ from: 'a', kind: 'q', body: qq.title, sub: qq.sub, q: qq });
    const v = answers[qq.id];
    if (i < stepIdx && v) {
      messages.push({ from: 'u', kind: 'answer', q: qq, value: v });
      const insight = insightFor(i, answers);
      if (insight) messages.push({ from: 'a', kind: 'insight', body: insight });
    }
  }

  return (
    <div style={{
      minHeight: '100%', background: T.surfaceWarm,
      fontFamily: T.font, display: 'flex', flexDirection: 'column',
    }}>
      {/* Top bar */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: mobile ? '14px 18px' : '16px 28px', background: '#fff',
        borderBottom: `1px solid ${T.borderSoft}`,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <AssistantAvatar/>
          <div>
            <div style={{ fontSize: 13.5, fontWeight: 600, color: T.ink, letterSpacing: -0.2 }}>Tax Bridge Assistant</div>
            <div style={{ fontSize: 11, color: T.mintInk, display: 'flex', alignItems: 'center', gap: 5 }}>
              <span style={{ width: 6, height: 6, borderRadius: 999, background: T.mint }}/> Online · Encrypted · No signup yet
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <span style={{ fontFamily: T.mono, fontSize: 11, color: T.muted }}>
            {Math.min(stepIdx + 1, total)} / {total}
          </span>
          <button onClick={() => go('home')} style={{
            background: 'none', border: 0, cursor: 'pointer',
            fontFamily: T.font, fontSize: 12.5, color: T.muted,
          }}>Save & exit</button>
        </div>
      </div>

      {/* Progress strip */}
      <div style={{ padding: mobile ? '10px 18px' : '12px 28px', background: '#fff', borderBottom: `1px solid ${T.borderSoft}` }}>
        <ProgressBar value={((stepIdx + 1) / total) * 100}/>
      </div>

      {/* Conversation */}
      <div ref={scrollRef} style={{
        flex: 1, overflowY: 'auto', padding: mobile ? '20px 16px' : '28px 36px',
        display: 'flex', flexDirection: 'column', gap: 12,
      }}>
        <div style={{ maxWidth: 680, margin: '0 auto', width: '100%', display: 'flex', flexDirection: 'column', gap: 12 }}>
          {messages.map((m, i) => <ChatMessage key={i} m={m} mobile={mobile}/>)}

          {/* Active answer area */}
          <ActiveAnswer q={q} value={value} setAnswer={setAnswer} mobile={mobile}/>
        </div>
      </div>

      {/* Footer */}
      <div style={{
        padding: mobile ? '12px 18px' : '14px 28px',
        background: '#fff', borderTop: `1px solid ${T.borderSoft}`,
        display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10,
      }}>
        <Button variant="ghost" size="sm" onClick={back} icon={Icon.arrowL}>Back</Button>
        <Button variant="primary" size="md" disabled={!canNext} onClick={next} iconRight={Icon.arrow}>
          {stepIdx === total - 1 ? 'See my profile' : 'Send'}
        </Button>
      </div>
    </div>
  );
}

function AssistantAvatar({ size = 32 }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: 999, flexShrink: 0,
      background: `linear-gradient(135deg, ${T.ink} 0%, ${T.inkDeep} 100%)`,
      color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
      position: 'relative',
    }}>
      <svg width={size * 0.55} height={size * 0.55} viewBox="0 0 40 30" fill="none">
        <path d="M2 22 Q 11 8, 20 22" stroke="#fff" strokeWidth="3" strokeLinecap="round" fill="none"/>
        <path d="M20 22 Q 29 8, 38 22" stroke={T.mint} strokeWidth="3" strokeLinecap="round" fill="none"/>
      </svg>
    </div>
  );
}

function ChatMessage({ m, mobile }) {
  if (m.from === 'a' && m.kind === 'text') {
    return (
      <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
        <AssistantAvatar size={28}/>
        <div style={{
          background: '#fff', padding: '12px 16px', borderRadius: 16, borderTopLeftRadius: 4,
          maxWidth: '85%', border: `1px solid ${T.borderSoft}`,
          fontSize: 14, color: T.ink2, lineHeight: 1.55,
        }}>{m.body}</div>
      </div>
    );
  }
  if (m.from === 'a' && m.kind === 'q') {
    return (
      <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
        <AssistantAvatar size={28}/>
        <div style={{
          background: '#fff', padding: '14px 16px', borderRadius: 16, borderTopLeftRadius: 4,
          maxWidth: '85%', border: `1px solid ${T.borderSoft}`,
        }}>
          <div style={{ fontSize: 15, color: T.ink, fontWeight: 600, letterSpacing: -0.2, lineHeight: 1.35 }}>{m.body}</div>
          {m.sub && <div style={{ fontSize: 12.5, color: T.muted, marginTop: 5, lineHeight: 1.5 }}>{m.sub}</div>}
        </div>
      </div>
    );
  }
  if (m.from === 'a' && m.kind === 'insight') {
    return (
      <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
        <AssistantAvatar size={28}/>
        <div style={{
          background: T.mintSoft, padding: '12px 16px', borderRadius: 16, borderTopLeftRadius: 4,
          maxWidth: '85%', display: 'flex', gap: 10, alignItems: 'flex-start',
        }}>
          <span style={{ color: T.mintInk, marginTop: 1 }}>{Icon.spark}</span>
          <span style={{ fontSize: 13.5, color: T.ink2, lineHeight: 1.5 }}>{m.body}</span>
        </div>
      </div>
    );
  }
  if (m.from === 'u') {
    const labels = renderAnswerLabel(m.q, m.value);
    return (
      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <div style={{
          background: T.ink, color: '#fff',
          padding: '10px 14px', borderRadius: 16, borderTopRightRadius: 4,
          maxWidth: '80%', fontSize: 14, lineHeight: 1.4,
          display: 'flex', flexWrap: 'wrap', gap: 6,
        }}>{labels}</div>
      </div>
    );
  }
  return null;
}

function renderAnswerLabel(q, value) {
  if (q.type === 'multi') {
    const vals = value || [];
    return vals.map(v => {
      const opt = q.options.find(o => o.v === v);
      return opt ? opt.l : v;
    }).join(' · ');
  }
  const opt = q.options.find(o => o.v === value);
  return opt ? opt.l : value;
}

function ActiveAnswer({ q, value, setAnswer, mobile }) {
  // For singles → chip buttons aligned right; for multi → checkable chips with explicit confirm
  const isMulti = q.type === 'multi';
  return (
    <div style={{
      display: 'flex', flexWrap: 'wrap', gap: 8,
      justifyContent: 'flex-end', marginTop: 4,
      paddingLeft: mobile ? 0 : 40,
    }}>
      {q.options.map(opt => {
        const selected = isMulti ? (value || []).includes(opt.v) : value === opt.v;
        return (
          <button
            key={opt.v}
            onClick={() => setAnswer(opt.v)}
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 8,
              padding: '10px 14px', borderRadius: 999,
              background: selected ? T.ink : '#fff',
              color: selected ? '#fff' : T.ink2,
              border: `1.5px solid ${selected ? T.ink : T.border}`,
              fontFamily: T.font, fontSize: 13.5, fontWeight: 500,
              cursor: 'pointer', transition: 'all 140ms ease',
              maxWidth: '100%',
            }}
            onMouseEnter={(e) => { if (!selected) e.currentTarget.style.borderColor = T.ink3; }}
            onMouseLeave={(e) => { if (!selected) e.currentTarget.style.borderColor = T.border; }}
          >
            {opt.icon && <span style={{ color: selected ? T.mint : opt.accent, display: 'inline-flex' }}>{opt.icon}</span>}
            <span>{opt.l}</span>
            {selected && isMulti && <span style={{ color: T.mint }}>{Icon.check}</span>}
          </button>
        );
      })}
    </div>
  );
}

// ─── C · Card-stack ──────────────────────────────────────
function CardStackFlow({ stepIdx, q, total, value, canNext, setAnswer, next, back, answers, mobile, go }) {
  const isMulti = q.type === 'multi';
  return (
    <div style={{
      minHeight: '100%', background: T.ink, color: '#fff',
      fontFamily: T.font, display: 'flex', flexDirection: 'column',
      position: 'relative', overflow: 'hidden',
    }}>
      {/* glow */}
      <div style={{
        position: 'absolute', top: '15%', left: '50%', transform: 'translateX(-50%)',
        width: '120%', maxWidth: 900, height: 700, borderRadius: 999,
        background: `radial-gradient(circle, rgba(58,210,159,0.16), transparent 60%)`,
        pointerEvents: 'none',
      }}/>

      {/* Top */}
      <div style={{
        position: 'relative',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: mobile ? '16px 18px' : '20px 32px',
      }}>
        <Logo size={mobile ? 16 : 18} color="#fff" accent={T.mint}/>
        <div style={{ display: 'flex', gap: 4 }}>
          {QUESTIONS.map((_, i) => (
            <div key={i} style={{
              width: mobile ? 14 : 22, height: 3, borderRadius: 999,
              background: i < stepIdx ? T.mint : i === stepIdx ? '#fff' : 'rgba(255,255,255,0.18)',
              transition: 'background 280ms ease',
            }}/>
          ))}
        </div>
        <button onClick={() => go('home')} style={{
          background: 'none', border: 0, cursor: 'pointer',
          fontFamily: T.font, fontSize: 12, color: 'rgba(255,255,255,0.6)',
        }}>Exit</button>
      </div>

      {/* Body */}
      <div style={{
        flex: 1, position: 'relative',
        padding: mobile ? '12px 20px 20px' : '28px 40px 40px',
        display: 'flex', flexDirection: 'column',
        overflowY: 'auto',
      }}>
        <div style={{ maxWidth: 760, width: '100%', margin: '0 auto', display: 'flex', flexDirection: 'column' }}>
          <div style={{
            fontFamily: T.mono, fontSize: 11, color: 'rgba(255,255,255,0.55)',
            textTransform: 'uppercase', letterSpacing: 0.9, marginBottom: 10,
          }}>{String(stepIdx + 1).padStart(2, '0')} · {q.short}</div>
          <h2 style={{
            fontSize: mobile ? 28 : 38, fontWeight: 600,
            letterSpacing: mobile ? -0.8 : -1.2, lineHeight: 1.1,
            color: '#fff', margin: '0 0 10px', textWrap: 'balance',
          }}>{q.title}</h2>
          <p style={{
            fontSize: mobile ? 14 : 15.5, color: 'rgba(255,255,255,0.7)',
            lineHeight: 1.55, margin: '0 0 28px', textWrap: 'pretty',
          }}>{q.sub}</p>

          <div style={{
            display: 'grid',
            gridTemplateColumns: mobile
              ? (q.options.length > 4 ? '1fr 1fr' : '1fr')
              : (q.options.length > 4 ? 'repeat(3, 1fr)' : '1fr 1fr'),
            gap: mobile ? 10 : 12,
          }}>
            {q.options.map(opt => {
              const selected = isMulti ? (value || []).includes(opt.v) : value === opt.v;
              return (
                <button
                  key={opt.v}
                  onClick={() => setAnswer(opt.v)}
                  style={{
                    position: 'relative', textAlign: 'left',
                    padding: mobile ? '14px 14px' : '18px 18px',
                    borderRadius: 18,
                    minHeight: mobile ? 96 : 130,
                    background: opt.color,
                    border: `2px solid ${selected ? T.mint : 'transparent'}`,
                    cursor: 'pointer',
                    transition: 'all 180ms cubic-bezier(.2,.7,.2,1)',
                    transform: selected ? 'translateY(-3px)' : 'none',
                    boxShadow: selected ? '0 20px 40px rgba(0,0,0,0.32)' : '0 4px 12px rgba(0,0,0,0.12)',
                    fontFamily: T.font,
                  }}
                  onMouseEnter={(e) => { if (!selected) { e.currentTarget.style.transform = 'translateY(-1px)'; } }}
                  onMouseLeave={(e) => { if (!selected) { e.currentTarget.style.transform = 'none'; } }}
                >
                  {opt.icon && (
                    <div style={{
                      width: mobile ? 28 : 32, height: mobile ? 28 : 32, borderRadius: 9,
                      background: '#fff', color: opt.accent,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      marginBottom: mobile ? 8 : 10,
                    }}>{opt.icon}</div>
                  )}
                  <div style={{
                    fontSize: mobile ? 13.5 : 15.5, fontWeight: 600,
                    color: T.ink, letterSpacing: -0.2, lineHeight: 1.25,
                  }}>{opt.l}</div>
                  {opt.s && (
                    <div style={{
                      fontSize: mobile ? 11 : 12, color: T.ink3,
                      marginTop: 3, lineHeight: 1.4,
                    }}>{opt.s}</div>
                  )}
                  {selected && (
                    <div style={{
                      position: 'absolute', top: 10, right: 10,
                      width: 22, height: 22, borderRadius: 999,
                      background: T.mint, color: T.ink,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>{Icon.check}</div>
                  )}
                </button>
              );
            })}
          </div>

          {stepIdx > 1 && (
            <div style={{
              marginTop: 24, padding: '12px 16px',
              background: 'rgba(58,210,159,0.10)',
              border: `1px solid rgba(58,210,159,0.20)`,
              borderRadius: 14,
              display: 'flex', alignItems: 'flex-start', gap: 10,
            }}>
              <span style={{ color: T.mint, marginTop: 1 }}>{Icon.spark}</span>
              <span style={{ fontSize: 13, color: 'rgba(255,255,255,0.85)', lineHeight: 1.5 }}>
                {insightFor(stepIdx, answers)}
              </span>
            </div>
          )}
        </div>
      </div>

      {/* Footer */}
      <div style={{
        position: 'relative',
        padding: mobile ? '14px 20px' : '18px 32px',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10,
        borderTop: '1px solid rgba(255,255,255,0.08)',
      }}>
        <button onClick={back} style={{
          background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.12)',
          color: '#fff', padding: '9px 14px', borderRadius: 10,
          fontFamily: T.font, fontSize: 13, fontWeight: 500,
          cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 8,
        }}>{Icon.arrowL} Back</button>
        <span style={{ fontFamily: T.mono, fontSize: 11, color: 'rgba(255,255,255,0.45)' }}>
          {isMulti ? `${(value || []).length} selected` : ''}
        </span>
        <Button variant="mint" size="md" disabled={!canNext} onClick={next} iconRight={Icon.arrow}>
          {stepIdx === total - 1 ? 'See my profile' : 'Next'}
        </Button>
      </div>
    </div>
  );
}

// ─── A · Stepper (fallback) ───────────────────────────────
function StepperFlow({ stepIdx, q, total, value, canNext, setAnswer, next, back, answers, mobile, go }) {
  // Auto-advance for single-choice (subtle delay)
  React.useEffect(() => {
    if (q.type === 'single' && value && stepIdx < total - 1) {
      const id = setTimeout(() => next(), 360);
      return () => clearTimeout(id);
    }
  }, [value, q.type, stepIdx, total, next]);

  return (
    <div style={{
      minHeight: '100%', background: '#fff',
      fontFamily: T.font, display: 'flex', flexDirection: 'column',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: mobile ? '16px 20px' : '20px 40px',
        borderBottom: `1px solid ${T.borderSoft}`,
      }}>
        <Logo size={mobile ? 18 : 20}/>
        <button onClick={() => go('home')} style={{
          background: 'none', border: 0, cursor: 'pointer',
          fontFamily: T.font, fontSize: 13, color: T.muted,
        }}>Save and exit</button>
      </div>
      <div style={{ padding: mobile ? '20px 20px 12px' : '24px 40px 16px', background: T.surface }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
          <div style={{ fontFamily: T.mono, fontSize: 11, color: T.muted, textTransform: 'uppercase', letterSpacing: 0.8 }}>
            Step {stepIdx + 1} of {total} · Tax check
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: T.muted }}>
            <span style={{ color: T.mintInk }}>{Icon.shield}</span><span>No signup needed</span>
          </div>
        </div>
        <ProgressBar value={((stepIdx + 1) / total) * 100}/>
      </div>
      <div style={{ flex: 1, padding: mobile ? '28px 20px 24px' : '48px 40px 32px', maxWidth: 720, width: '100%', margin: '0 auto', boxSizing: 'border-box' }}>
        <div style={{ fontFamily: T.mono, fontSize: 11, color: T.muted, textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 10 }}>
          Question {String(stepIdx + 1).padStart(2, '0')}
        </div>
        <h2 style={{ fontSize: mobile ? 26 : 32, fontWeight: 600, letterSpacing: -0.7, lineHeight: 1.15, color: T.ink, margin: '0 0 10px' }}>{q.title}</h2>
        <p style={{ fontSize: mobile ? 14.5 : 16, color: T.muted, lineHeight: 1.5, margin: '0 0 28px' }}>{q.sub}</p>
        <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : (q.options.length > 5 ? '1fr 1fr' : '1fr'), gap: 10 }}>
          {q.options.map(opt => {
            const selected = q.type === 'multi' ? (value || []).includes(opt.v) : value === opt.v;
            return (
              <OptionCard key={opt.v} selected={selected} onClick={() => setAnswer(opt.v)} icon={opt.icon} sub={opt.s} multi={q.type === 'multi'}>
                {opt.l}
              </OptionCard>
            );
          })}
        </div>
      </div>
      <div style={{ position: 'sticky', bottom: 0, background: '#fff', padding: mobile ? '14px 20px' : '20px 40px', borderTop: `1px solid ${T.borderSoft}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
        <Button variant="ghost" size="md" onClick={back} icon={Icon.arrowL}>Back</Button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <span style={{ fontFamily: T.mono, fontSize: 11, color: T.muted }}>{stepIdx + 1} / {total}</span>
          <Button variant="primary" size="md" disabled={!canNext} onClick={next} iconRight={Icon.arrow}>
            {stepIdx === total - 1 ? 'See my profile' : 'Continue'}
          </Button>
        </div>
      </div>
    </div>
  );
}

// ─── Live insight copy ─────────────────────────────────
function insightFor(idx, a) {
  if (idx === 2 && a.income_types) {
    const it = a.income_types;
    if (it.includes('rsu')) return "RSUs add complexity — most expats benefit from an advisor here. We'll flag that in your profile.";
    if (it.includes('crypto')) return "Crypto held >1 year is tax-free in Germany. We track that automatically.";
    if (it.includes('foreign')) return "Foreign income often qualifies for double-taxation relief. Worth checking.";
    return "Salary-only filers can often claim back ~€700–€1,200 in deductions.";
  }
  if (idx === 3) {
    if (a.filed_before === 'never') return "Most first-time filers in Germany get a refund — the average is around €1,072.";
    if (a.filed_before === 'yearly') return "We can import your previous filings to make this faster.";
  }
  if (idx === 4) {
    if (a.advisor === 'none') return "We'll match you with 2–3 advisors based on your situation. You stay in control.";
    if (a.advisor === 'diy') return "Got it — we'll skip advisor matching and focus on self-service.";
  }
  if (idx === 5) return "We'll build a personalised document checklist based on your selections.";
  if (idx === 6 && a.urgency === 'asap') return "Tight deadline noted — advisors with availability will be prioritised.";
  return null;
}

Object.assign(window, { AssessmentScreen, QUESTIONS });
