// screens-onboarding.jsx — Home + matching quiz + results

const QUIZ_QUESTIONS = [
  // ── Section I ────────────────────────────────────────────
  { type: 'section', id: 's1', num: 1,
    title: 'Section I',    title_el: 'Ενότητα Α',
    sub:   'About your needs', sub_el: 'Σχετικά με τις ανάγκες σας' },

  {
    id: 'support_type',
    title: 'What type of support are you looking for?',
    title_el: 'Τι είδος υποστήριξης αναζητάτε;',
    options: [
      { id: 'individual', label: 'Individual',           label_el: 'Ατομική',                meta: { supportType: 'individual' } },
      { id: 'couples',    label: 'Couples',              label_el: 'Ζευγάρια',               meta: { supportType: 'couples' }, tags: { couples: 2 }, approach: { systemic: 2 } },
      { id: 'family',     label: 'Families and parents', label_el: 'Οικογένειες και γονείς', meta: { supportType: 'family' },  approach: { systemic: 2 } },
    ],
  },

  {
    id: 'areas',
    title:    'In which areas would you like support?',
    title_el: 'Σε ποιους τομείς θέλετε υποστήριξη;',
    sub:      'Select up to 3 areas. Fewer choices = more precise matches.',
    sub_el:   'Επιλέξτε έως 3 τομείς. Λιγότερες επιλογές = πιο στοχευμένα αποτελέσματα.',
    multi: true, maxSelect: 3, grid: true,
    options: [
      { id: 'anxiety',    label: 'Anxiety or worry',                  label_el: 'Άγχος ή ανησυχία',                       tags: { anxiety: 2 },    approach: { cbt: 2, act: 1 } },
      { id: 'depression', label: 'Depression or low mood',            label_el: 'Κατάθλιψη ή χαμηλή διάθεση',             tags: { depression: 2 }, approach: { cbt: 1, psychodynamic: 1, humanistic: 1 } },
      { id: 'relations',  label: 'Relationship challenges',           label_el: 'Προκλήσεις στις σχέσεις',                 tags: { couples: 1 },    approach: { systemic: 2, humanistic: 1 } },
      { id: 'stress',     label: 'Stress or burnout',                 label_el: 'Στρες ή επαγγελματική εξουθένωση',        tags: { work: 1 },       approach: { cbt: 1, act: 1 } },
      { id: 'trauma',     label: 'Past trauma or PTSD',               label_el: 'Παλιό τραύμα ή PTSD',                    tags: { trauma: 2 },     approach: { emdr: 2, psychodynamic: 1 } },
      { id: 'transition', label: 'Life transitions',                  label_el: 'Αλλαγές στη ζωή',                        tags: { grief: 1 },      approach: { humanistic: 2, act: 1 } },
      { id: 'adhd',       label: 'ADHD support',                      label_el: 'Υποστήριξη ADHD',                                                  approach: { cbt: 2 } },
      { id: 'career',     label: 'Career challenges',                 label_el: 'Επαγγελματικές προκλήσεις',               tags: { work: 2 },       approach: { cbt: 1 } },
      { id: 'self_esteem',label: 'Self-esteem concerns',              label_el: 'Αυτοεκτίμηση',                                                     approach: { humanistic: 2, psychodynamic: 1 } },
      { id: 'grief',      label: 'Grief & loss',                      label_el: 'Πένθος & απώλεια',                       tags: { grief: 2 },      approach: { humanistic: 2, psychodynamic: 1 } },
      { id: 'eating',     label: 'Eating disorder or body image',     label_el: 'Διατροφικές διαταραχές ή εικόνα σώματος',                          approach: { cbt: 2 } },
      { id: 'addiction',  label: 'Addictions',                        label_el: 'Εξαρτήσεις',                                                       approach: { cbt: 2, act: 1 } },
      { id: 'anger',      label: 'Anger management',                  label_el: 'Διαχείριση θυμού',                                                 approach: { cbt: 2, act: 1 } },
      { id: 'cultural',   label: 'Cultural adjustment / Expat life',  label_el: 'Πολιτισμική προσαρμογή / Ζωή expat',                               approach: { humanistic: 1, integrative: 1 } },
      { id: 'ocd',        label: 'OCD',                               label_el: 'OCD',                                                              approach: { cbt: 3 } },
      { id: 'identity',   label: 'Identity & self-discovery',         label_el: 'Ταυτότητα & αυτογνωσία',                                           approach: { psychodynamic: 2, humanistic: 1 } },
      { id: 'intimacy',   label: 'Sex or intimacy issues',            label_el: 'Ζητήματα σεξουαλικότητας ή οικειότητας',                           approach: { systemic: 1, humanistic: 1 } },
      { id: 'other',      label: 'Other',                             label_el: 'Άλλο' },
    ],
  },

  {
    id: 'mode',
    title:    'What therapy session formats do you prefer?',
    title_el: 'Ποιες μορφές συνεδριών προτιμάτε;',
    sub:      'If open to online when a local match is not found, select both.',
    sub_el:   'Αν είστε ανοιχτοί σε online όταν δεν βρίσκεται τοπικό αποτέλεσμα, επιλέξτε και τα δύο.',
    multi: true,
    options: [
      { id: 'on', label: 'Online',     label_el: 'Διαδικτυακά', meta: { mode: 'online' } },
      { id: 'in', label: 'In-person',  label_el: 'Δια ζώσης',   meta: { mode: 'in-person' } },
    ],
  },

  {
    id: 'district',
    title:    'In which city would you like to meet?',
    title_el: 'Σε ποια πόλη θέλετε να συναντηθείτε;',
    sub:      "If your city isn't listed, choose the nearest district.",
    sub_el:   'Αν η πόλη σας δεν είναι στη λίστα, επιλέξτε την πλησιέστερη επαρχία.',
    options: DISTRICTS.map(d => ({ id: d, label: d, label_el: DISTRICT_EL[d] || d, meta: { district: d } })),
  },

  {
    id: 'language',
    title:    'What language would you prefer for your sessions?',
    title_el: 'Τι γλώσσα προτιμάτε για τις συνεδρίες σας;',
    sub:      'Some things are easier in your first language.',
    sub_el:   'Κάποια πράγματα είναι πιο εύκολα στη μητρική σας γλώσσα.',
    multi: true, grid: true,
    options: [
      { id: 'gr',  label: 'Greek',          label_el: 'Ελληνικά',  meta: { language: 'Greek' } },
      { id: 'en',  label: 'English',        label_el: 'Αγγλικά',   meta: { language: 'English' } },
      { id: 'ru',  label: 'Russian',        label_el: 'Ρωσικά',    meta: { language: 'Russian' } },
      { id: 'ro',  label: 'Romanian',       label_el: 'Ρουμανικά', meta: { language: 'Romanian' } },
      { id: 'ar',  label: 'Arabic',         label_el: 'Αραβικά',   meta: { language: 'Arabic' } },
      { id: 'de',  label: 'German',         label_el: 'Γερμανικά', meta: { language: 'German' } },
      { id: 'fr',  label: 'French',         label_el: 'Γαλλικά',   meta: { language: 'French' } },
      { id: 'any', label: "Doesn't matter", label_el: 'Δεν με πειράζει' },
    ],
  },

  // ── Section II ───────────────────────────────────────────
  { type: 'section', id: 's2', num: 2,
    title: 'Section II',   title_el: 'Ενότητα Β',
    sub:   'More about you', sub_el: 'Περισσότερα για σας' },

  {
    id: 'therapy_before',
    title:    'Have you ever been in therapy before?',
    title_el: 'Έχετε κάνει ποτέ θεραπεία στο παρελθόν;',
    options: [
      { id: 'yes', label: 'Yes', label_el: 'Ναι' },
      { id: 'no',  label: 'No',  label_el: 'Όχι' },
    ],
  },

  {
    id: 'style',
    title:    "When something's wrong, what helps you most?",
    title_el: 'Όταν κάτι πάει στραβά, τι σας βοηθάει περισσότερο;',
    sub:      "Different approaches lean toward different styles. There's no wrong answer.",
    sub_el:   'Διαφορετικές προσεγγίσεις ταιριάζουν σε διαφορετικά στυλ. Δεν υπάρχει λάθος απάντηση.',
    options: [
      { id: 'plan',   label: 'A clear plan with steps I can practise',           label_el: 'Ένα σαφές πλάνο με βήματα που μπορώ να εξασκώ',              approach: { cbt: 2, act: 1 } },
      { id: 'roots',  label: 'Understanding the roots of why I feel this way',   label_el: 'Να καταλάβω τις ρίζες του γιατί νιώθω έτσι',                  approach: { psychodynamic: 2, gestalt: 1 } },
      { id: 'listen', label: 'Someone really listening, without judging',        label_el: 'Κάποιος που να με ακούει πραγματικά, χωρίς κρίση',             approach: { humanistic: 2, gestalt: 1 } },
      { id: 'tools',  label: 'Tools to manage difficult feelings in the moment', label_el: 'Εργαλεία για να διαχειριστώ δύσκολα συναισθήματα στη στιγμή', approach: { cbt: 2, act: 2 } },
      { id: 'unsure', label: "I don't know — open to whatever works",            label_el: 'Δεν ξέρω — ανοιχτός/η σε ό,τι λειτουργεί',                    approach: { integrative: 2 } },
    ],
  },

  {
    id: 'duration',
    title:    'How long do you want to commit?',
    title_el: 'Για πόσο χρονικό διάστημα θέλετε να δεσμευτείτε;',
    sub:      "This isn't binding — it just helps us match you.",
    sub_el:   'Δεν είναι δεσμευτικό — μας βοηθά μόνο να σας ταιριάξουμε.',
    options: [
      { id: 'short',    label: 'A few sessions, focused on one thing',        label_el: 'Λίγες συνεδρίες, εστιασμένες σε ένα θέμα',         approach: { cbt: 2, act: 1 } },
      { id: 'medium',   label: 'A few months — see how it goes',              label_el: 'Λίγους μήνες — να δούμε πώς πάει',                  approach: { cbt: 1, integrative: 1, humanistic: 1 } },
      { id: 'long',     label: "Open-ended, I'm in this for the deeper work", label_el: 'Ανοιχτής διάρκειας, είμαι εδώ για βαθύτερη δουλειά', approach: { psychodynamic: 2 } },
      { id: 'undecided',label: 'No idea yet',                                 label_el: 'Δεν ξέρω ακόμα',                                    approach: {} },
    ],
  },

  {
    id: 'goals',
    title:    'What are you hoping to gain from therapy?',
    title_el: 'Τι ελπίζετε να αποκομίσετε από τη θεραπεία;',
    sub:      "Not sure yet? That's okay — your therapist can help you explore this.",
    sub_el:   'Δεν είστε σίγουροι; Εντάξει — ο θεραπευτής σας μπορεί να σας βοηθήσει να το εξερευνήσετε.',
    multi: true, maxSelect: 3, optional: true, grid: true,
    options: [
      { id: 'present',    label: 'Being more present',         label_el: 'Να είμαι πιο παρών/παρούσα' },
      { id: 'patterns',   label: 'Understanding my patterns',  label_el: 'Να καταλάβω τα μοτίβα μου' },
      { id: 'boundaries', label: 'Setting better boundaries',  label_el: 'Να βάζω καλύτερα όρια' },
      { id: 'self',       label: 'Self-exploration',           label_el: 'Αυτοεξερεύνηση' },
      { id: 'control',    label: 'More control over my reactions', label_el: 'Περισσότερος έλεγχος στις αντιδράσεις μου' },
      { id: 'goals_pers', label: 'Achieving personal goals',   label_el: 'Επίτευξη προσωπικών στόχων' },
      { id: 'challenges', label: 'Solving current challenges', label_el: 'Επίλυση τρεχουσών προκλήσεων' },
      { id: 'trauma_rec', label: 'Recovering from trauma',     label_el: 'Ανάρρωση από τραύμα' },
      { id: 'relations',  label: 'Improving relationships',    label_el: 'Βελτίωση σχέσεων' },
      { id: 'other',      label: 'Other',                      label_el: 'Άλλο' },
    ],
  },

  // ── Section III ──────────────────────────────────────────
  { type: 'section', id: 's3', num: 3,
    title: 'Section III',          title_el: 'Ενότητα Γ',
    sub:   'About your therapist', sub_el:   'Σχετικά με τον θεραπευτή σας' },

  {
    id: 'therapist_gender',
    title:    'Do you have a gender preference for your therapist?',
    title_el: 'Έχετε προτίμηση φύλου για τον θεραπευτή σας;',
    sub:      "Select any that matter to you, or skip if you're flexible.",
    sub_el:   'Επιλέξτε ό,τι σας αφορά, ή παραλείψτε αν είστε ευέλικτοι.',
    multi: true, optional: true,
    options: [
      { id: 'female',    label: 'Female',     label_el: 'Γυναίκα',           meta: { therapistGender: 'female' } },
      { id: 'male',      label: 'Male',       label_el: 'Άντρας',            meta: { therapistGender: 'male' } },
      { id: 'nonbinary', label: 'Non-binary', label_el: 'Μη δυαδικό/ή',     meta: { therapistGender: 'nonbinary' } },
    ],
  },

  {
    id: 'therapist_topics',
    title:    'Should your therapist have experience with specific topics?',
    title_el: 'Θέλετε ο θεραπευτής σας να έχει εμπειρία με συγκεκριμένα θέματα;',
    sub:      "Select any that are important to you, or skip if you're flexible.",
    sub_el:   'Επιλέξτε ό,τι είναι σημαντικό για σας, ή παραλείψτε αν είστε ευέλικτοι.',
    multi: true, maxSelect: 3, optional: true, grid: true,
    options: [
      { id: 'expat',    label: 'Expat / immigrant experiences',  label_el: 'Εμπειρίες expat / μεταναστών' },
      { id: 'lgbtq',    label: 'LGBTQ+',                         label_el: 'LGBTQ+' },
      { id: 'intl',     label: 'International living',           label_el: 'Διεθνής διαβίωση' },
      { id: 'neurodiv', label: 'Neurodiversity',                 label_el: 'Νευροποικιλία' },
      { id: 'identity', label: 'Gender identity or transition',  label_el: 'Ταυτότητα φύλου ή μετάβαση' },
      { id: 'faith',    label: 'Religious / faith background',   label_el: 'Θρησκευτικό / πνευματικό υπόβαθρο' },
      { id: 'discrim',  label: 'Discrimination or racism',       label_el: 'Διακρίσεις ή ρατσισμός' },
      { id: 'other',    label: 'Other',                          label_el: 'Άλλο' },
    ],
  },

  {
    id: 'gesy',
    title:    'Are you using GeSY?',
    title_el: 'Χρησιμοποιείτε ΓεΣΥ;',
    sub:      'The Cyprus national health system can cover some psychology sessions.',
    sub_el:   'Το κυπριακό εθνικό σύστημα υγείας μπορεί να καλύψει ορισμένες συνεδρίες ψυχολογίας.',
    options: [
      { id: 'gesy_yes',  label: 'Yes — GeSY only',            label_el: 'Ναι — μόνο ΓεΣΥ',                meta: { gesy: true } },
      { id: 'gesy_pref', label: 'I prefer GeSY but flexible', label_el: 'Προτιμώ ΓεΣΥ αλλά είμαι ευέλικτος/η', meta: { gesy: 'pref' } },
      { id: 'gesy_no',   label: 'Paying privately is fine',   label_el: 'Ιδιωτικά είναι εντάξει',          meta: { gesy: false } },
    ],
  },
];

// ===========================================================
//  HOME
// ===========================================================
function HomeScreen({ setRoute, openQuiz }) {
  const { t, lang } = useLang();
  const [showVerModal, setShowVerModal] = useState(false);
  const [featuredPsys, setFeaturedPsys] = useState([]);
  const [stats, setStats] = useState({ psychologists: null, reviews: null, sessions: null });
  useEffect(() => {
    API.getPsychologists()
      .then(data => setFeaturedPsys(Array.isArray(data) ? data.slice(0, 3) : []))
      .catch(() => {});
  }, []);
  useEffect(() => {
    fetch('/api/stats')
      .then(r => r.json())
      .then(d => setStats({ psychologists: d.psychologists, reviews: d.reviews, sessions: d.sessions }))
      .catch(() => {});
  }, []);
  return (
    <div className="page">
      <section className="hero">
        <div>
          <span className="eyebrow" style={{ display: 'inline-flex', alignItems: 'baseline', gap: '0.35em' }}>
            {lang === 'el' ? 'Καλώς ήρθατε στο' : 'Welcome to'}
            <span style={{ fontWeight: 800, fontSize: '1.5em', letterSpacing: '-0.02em', color: '#1a1523', fontFamily: 'inherit', textTransform: 'none' }}>
              psych<span style={{ background: 'linear-gradient(135deg, #5b21b6 0%, #16c784 100%)', WebkitBackgroundClip: 'text', backgroundClip: 'text', color: 'transparent' }}>e</span><span style={{ color: '#16c784', marginLeft: 1 }}>.</span>
            </span>
          </span>
          <h1 style={{ marginTop: 18 }}>
            {t('home_h1')}
          </h1>
          <p className="lede">
            {t('home_sub')}
          </p>
          <div className="hero-cta">
            <button className="btn accent lg" onClick={openQuiz}>
              <Icon name="explore" /> {t('home_cta_quiz')}
            </button>
            <button className="btn ghost lg" onClick={() => setRoute('directory')}>
              {t('home_cta_browse')}
            </button>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 24, color: 'var(--fg2)', fontSize: 13 }}>
            <Icon name="lock" className="sm" />
            {t('home_quiz_privacy')}
          </div>
        </div>
        <ThreadArt />
      </section>

      {/* Trust strip */}
      <div className="trust-strip">
        <div className="item">
          <Icon name="verified" />
          <div>
            <div className="num">
              {stats.psychologists === null ? '—' : stats.psychologists}
            </div>
            <div className="label">{t('home_trust_psys')}</div>
          </div>
        </div>
        <div className="item">
          <Icon name="reviews" />
          <div>
            <div className="num">
              {stats.reviews === null
                ? '—'
                : stats.reviews >= 1000
                  ? (stats.reviews / 1000).toFixed(1).replace(/\.0$/, '') + 'k'
                  : stats.reviews}
            </div>
            <div className="label">{t('home_trust_reviews')}</div>
          </div>
        </div>
        <div className="item">
          <Icon name="public" />
          <div>
            <div className="num">6</div>
            <div className="label">{t('home_trust_districts')}</div>
          </div>
        </div>
        <div className="item">
          <Icon name="calendar_month" />
          <div>
            <div className="num">
              {stats.sessions === null ? '—' : stats.sessions}
            </div>
            <div className="label">{t('home_trust_sessions')}</div>
          </div>
        </div>
      </div>

      {/* How it works */}
      <section style={{ marginTop: 80 }}>
        <div className="section-head">
          <div>
            <span className="eyebrow muted">{t('home_how_eyebrow')}</span>
            <h2 style={{ marginTop: 8 }}>{t('home_how_sub')}</h2>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 16 }}>
          {[
            { n: '01', title: t('home_step1_title'), body: t('home_step1_body') },
            { n: '02', title: t('home_step2_title'), body: t('home_step2_body') },
            { n: '03', title: t('home_step3_title'), body: t('home_step3_body') },
          ].map(s => (
            <div className="card" key={s.n} style={{ padding: '28px 24px' }}>
              <div className="eyebrow" style={{ color: 'var(--psy-accent)' }}>{s.n}</div>
              <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em', marginTop: 14 }}>{s.title}</h3>
              <p style={{ color: 'var(--fg2)', marginTop: 10, fontSize: 14, lineHeight: 1.55 }}>{s.body}</p>
            </div>
          ))}
        </div>
      </section>

      {/* Featured — only shown when there are real psychologists */}
      {featuredPsys.length > 0 && (
        <section style={{ marginTop: 80 }}>
          <div className="section-head">
            <div>
              <span className="eyebrow muted">{t('home_eyebrow')}</span>
              <h2 style={{ marginTop: 8 }}>{t('home_featured')}</h2>
            </div>
            <button className="btn link" onClick={() => setRoute('directory')}>{t('home_view_all')} <Icon name="arrow_forward" className="sm" /></button>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
            {featuredPsys.map(p => (
              <MiniPsyCard key={p.id} psy={p} setRoute={setRoute} />
            ))}
          </div>
        </section>
      )}

      {/* Learn teaser */}
      <section style={{ marginTop: 80 }}>
        <div className="section-head">
          <div>
            <span className="eyebrow muted">{t('home_resource_eyebrow')}</span>
            <h2 style={{ marginTop: 8 }}>{t('home_resource_h2')}</h2>
          </div>
          <button className="btn link" onClick={() => setRoute('learn')}>{t('home_resource_browse')} <Icon name="arrow_forward" className="sm" /></button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
          {LEARN_ARTICLES.filter(a => ['cbt', 'anxiety', 'first-session'].includes(a.id)).map(a => (
            <ArticleCard key={a.id} article={a} onClick={() => setRoute('article', a.id)} />
          ))}
        </div>
      </section>

      {/* Quiet promise */}
      <section style={{ marginTop: 80 }}>
        <div className="card" style={{ padding: '40px 48px', background: 'var(--psy-ink)', color: 'white', borderColor: 'transparent' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 24, alignItems: 'center' }}>
            <div>
              <span className="eyebrow" style={{ color: 'color-mix(in oklab, var(--psy-accent) 50%, white)' }}>{t('home_promise_eyebrow')}</span>
              <h2 className="display" style={{ fontSize: 32, marginTop: 12, color: 'white', textWrap: 'balance' }}>
                {t('home_promise_body')}
              </h2>
            </div>
            <button className="btn accent" onClick={() => setShowVerModal(true)}>{t('home_how_works')}</button>
          </div>
        </div>
      </section>

      {/* For psychologists banner */}
      <section style={{ marginTop: 48 }}>
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16,
          padding: '24px 32px', borderRadius: 20,
          border: '1.5px solid var(--psy-rule)', background: 'var(--psy-surface-2)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <Icon name="psychology" style={{ color: 'var(--psy-accent)', fontSize: 28 }} />
            <div>
              <div style={{ fontWeight: 700, fontSize: 15 }}>
                {lang === 'el' ? 'Είστε ψυχολόγος;' : 'Are you a psychologist?'}
              </div>
              <div style={{ fontSize: 13, color: 'var(--fg2)', marginTop: 2 }}>
                {lang === 'el'
                  ? 'Δημιουργήστε δωρεάν προφίλ και γίνετε ορατοί σε χιλιάδες χρήστες στην Κύπρο.'
                  : 'Create a free profile and get found by thousands of users across Cyprus.'}
              </div>
            </div>
          </div>
          <button className="btn accent" onClick={() => setRoute('pricing')}>
            {lang === 'el' ? 'Μάθετε περισσότερα' : 'Learn more'}
            <Icon name="arrow_forward" className="sm" style={{ marginLeft: 6 }} />
          </button>
        </div>
      </section>

      {showVerModal && <VerificationModal onClose={() => setShowVerModal(false)} />}
    </div>
  );
}

function VerificationModal({ onClose }) {
  const { t } = useLang();
  const steps = [
    {
      icon: 'how_to_reg',
      title: t('home_ver_step1_title'),
      body: t('home_ver_step1_body'),
    },
    {
      icon: 'manage_search',
      title: t('home_ver_step2_title'),
      body: t('home_ver_step2_body'),
    },
    {
      icon: 'task_alt',
      title: t('home_ver_step3_title'),
      body: t('home_ver_step3_body'),
    },
    {
      icon: 'rate_review',
      title: t('home_ver_step4_title'),
      body: t('home_ver_step4_body'),
    },
  ];

  return (
    <div
      onClick={onClose}
      style={{ position: 'fixed', inset: 0, zIndex: 50, background: 'rgba(15,21,37,0.55)', backdropFilter: 'blur(4px)', display: 'grid', placeItems: 'center', padding: 24 }}>
      <div
        onClick={e => e.stopPropagation()}
        style={{ background: 'var(--psy-surface-2)', borderRadius: 28, padding: '44px 48px', maxWidth: 640, width: '100%', boxShadow: '0 24px 64px rgba(15,21,37,0.22)', position: 'relative', maxHeight: '90vh', overflowY: 'auto' }}>

        <button onClick={onClose} style={{ position: 'absolute', top: 18, right: 18, background: 'var(--psy-surface)', border: 0, width: 32, height: 32, borderRadius: '50%', cursor: 'pointer', display: 'grid', placeItems: 'center', color: 'var(--fg2)' }}>
          <Icon name="close" className="sm" />
        </button>

        <span className="eyebrow" style={{ color: 'var(--psy-leaf)' }}>{t('home_ver_eyebrow')}</span>
        <h2 className="display" style={{ fontSize: 34, fontWeight: 600, marginTop: 8, marginBottom: 6 }}>{t('home_ver_h2')}</h2>
        <p style={{ color: 'var(--fg2)', fontSize: 15, lineHeight: 1.55, marginBottom: 36 }}>
          {t('home_ver_sub')}
        </p>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
          {steps.map((s, i) => (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '48px 1fr', gap: 20, paddingBottom: i < steps.length - 1 ? 28 : 0, marginBottom: i < steps.length - 1 ? 28 : 0, borderBottom: i < steps.length - 1 ? '1px solid var(--psy-rule)' : 'none' }}>
              <div style={{ width: 48, height: 48, borderRadius: 14, background: 'var(--psy-leaf-soft)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                <Icon name={s.icon} style={{ color: 'var(--psy-leaf)', fontSize: 22 }} />
              </div>
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
                  <span style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--psy-ink)', color: 'white', display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 700, flexShrink: 0 }}>{i + 1}</span>
                  <strong style={{ fontSize: 16, color: 'var(--psy-ink)' }}>{s.title}</strong>
                </div>
                <p style={{ margin: 0, color: 'var(--fg2)', fontSize: 14, lineHeight: 1.6 }}>{s.body}</p>
              </div>
            </div>
          ))}
        </div>

        <div style={{ marginTop: 32, padding: '18px 20px', background: 'var(--psy-surface)', borderRadius: 14, display: 'flex', gap: 12, alignItems: 'flex-start' }}>
          <Icon name="info" style={{ color: 'var(--fg2)', fontSize: 18, flexShrink: 0, marginTop: 1 }} />
          <p style={{ margin: 0, fontSize: 13, color: 'var(--fg2)', lineHeight: 1.55 }}>
            {t('home_ver_note')}
          </p>
        </div>

        <button className="btn primary" style={{ marginTop: 28, width: '100%' }} onClick={onClose}>{t('home_ver_got_it')}</button>
      </div>
    </div>
  );
}

function MiniPsyCard({ psy, setRoute }) {
  return (
    <div className="card hoverable" style={{ padding: 22 }} onClick={() => setRoute('detail', psy.id)}>
      <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
        <Avatar psy={psy} />
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 18, letterSpacing: '-0.015em' }}>{psy.name}</div>
          <div style={{ fontSize: 12.5, color: 'var(--fg2)', marginTop: 2 }}>{psy.credentials.split('·')[0]}</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 8 }}>
            <Stars value={psy.rating} />
            <span style={{ fontSize: 13, fontWeight: 600 }}>{psy.rating}</span>
            <span style={{ fontSize: 12, color: 'var(--fg2)' }}>({psy.reviewCount})</span>
          </div>
        </div>
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 14 }}>
        <TagList ids={[psy.primaryApproach]} source={APPROACHES} kind="accent" />
        <TagList ids={psy.specializations.slice(0, 2)} source={SPECIALIZATIONS} />
      </div>
      <div style={{ marginTop: 16, paddingTop: 14, borderTop: '1px solid var(--psy-rule)', display: 'flex', justifyContent: 'space-between', fontSize: 13, color: 'var(--fg2)' }}>
        <span><Icon name="place" className="sm" style={{ verticalAlign: -3, marginRight: 4 }} /> {psy.district}</span>
        <span style={{ color: 'var(--psy-leaf)', fontWeight: 600 }}>{psy.nextAvailable}</span>
      </div>
    </div>
  );
}

// ===========================================================
//  QUIZ
// ===========================================================
function QuizDisclaimer({ onConfirm, onSkip }) {
  const { lang } = useLang();
  const el = lang === 'el';
  return (
    <div className="page narrow">
      <div className="quiz-shell" style={{ maxWidth: 600 }}>
        <h2 style={{ fontSize: 22, fontWeight: 700, marginBottom: 20, letterSpacing: '-0.02em' }}>
          {el ? 'Πριν ξεκινήσουμε' : 'Before we begin'}
        </h2>

        {/* Crisis notice */}
        <div style={{ background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 14, padding: '16px 20px', marginBottom: 20, display: 'flex', gap: 12, alignItems: 'flex-start' }}>
          <Icon name="emergency" style={{ color: '#DC2626', fontSize: 20, flexShrink: 0, marginTop: 1 }} />
          <p style={{ margin: 0, fontSize: 14, color: '#7F1D1D', lineHeight: 1.6 }}>
            {el
              ? <>Αν βιώνετε κρίση ή ο κίνδυνος για τη ζωή είναι άμεσος, καλέστε{' '}
                  <strong>1410</strong> (Γραμμή Ψυχικής Υγείας Κύπρου, 24/7 δωρεάν) ή{' '}
                  <strong>112</strong> (Εκτακτη Ανάγκη). Το Psyche δεν είναι υπηρεσία κρίσεων.</>
              : <>If you are in crisis or your life is at risk, call{' '}
                  <strong>1410</strong> (Cyprus Mental Health Helpline, free 24/7) or{' '}
                  <strong>112</strong> (Emergency Services). Psyche is not a crisis service.</>
            }
          </p>
        </div>

        <p style={{ fontSize: 15, color: 'var(--fg2)', lineHeight: 1.7, marginBottom: 16 }}>
          {el
            ? 'Αυτή η υπηρεσία απευθύνεται σε άτομα 18 ετών και άνω.'
            : 'This service is for individuals 18 years and older.'}
        </p>
        <p style={{ fontSize: 15, color: 'var(--fg2)', lineHeight: 1.7, marginBottom: 28 }}>
          {el
            ? 'Μερικές ερωτήσεις αφορούν την ψυχική σας υγεία. Συνεχίζοντας, συναινείτε ρητά στη χρήση αυτών των δεδομένων για την αντιστοίχισή σας με ψυχολόγο.'
            : 'Some questions relate to your mental health. By continuing, you explicitly consent to us using this information to match you with a psychologist.'}
        </p>

        <p style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg1)', marginBottom: 24, lineHeight: 1.6 }}>
          {el
            ? 'Επιβεβαιώνω ότι είμαι 18 ετών ή άνω, δεν βρίσκομαι σε κρίση, και συναινώ στη χρήση των δεδομένων ψυχικής υγείας για την αντιστοίχισή μου με ψυχολόγο.'
            : 'I confirm that I am 18 or older, not in a life-threatening crisis, and consent to my mental health data being used to match me with a psychologist.'}
        </p>

        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          <button className="btn accent" style={{ fontSize: 15, padding: '13px 28px' }} onClick={onConfirm}>
            {el ? 'Ναι, επιβεβαιώνω' : 'Yes, I confirm'}
          </button>
          <button className="btn ghost" style={{ fontSize: 14 }} onClick={onSkip}>
            {el ? 'Παράλειψη' : 'Skip'}
          </button>
        </div>
      </div>
    </div>
  );
}

function QuizScreen({ onSkip, onComplete }) {
  const { t, lang } = useLang();
  const el = lang === 'el';
  const [showDisclaimer, setShowDisclaimer] = useState(true);
  const [step, setStep] = useState(0);
  const [answers, setAnswers] = useState({});

  if (showDisclaimer) {
    return <QuizDisclaimer onConfirm={() => setShowDisclaimer(false)} onSkip={onSkip} />;
  }

  const q = QUIZ_QUESTIONS[step];
  const questionSteps = QUIZ_QUESTIONS.filter(x => x.type !== 'section');
  const qIndex = questionSteps.indexOf(q);

  function advance(ans) {
    const next = ans !== undefined ? ans : answers;
    if (step < QUIZ_QUESTIONS.length - 1) setStep(step + 1);
    else onComplete(scoreAnswers(next));
  }

  function pickSingle(option) {
    const next = { ...answers, [q.id]: option };
    setAnswers(next);
    setTimeout(() => advance(next), 220);
  }

  function toggleMulti(option) {
    const current = answers[q.id] || [];
    const already = current.some(o => o.id === option.id);
    let next;
    if (already) {
      next = current.filter(o => o.id !== option.id);
    } else if (!q.maxSelect || current.length < q.maxSelect) {
      next = [...current, option];
    } else {
      return; // at max
    }
    setAnswers({ ...answers, [q.id]: next });
  }

  // Section header step
  if (q.type === 'section') {
    return (
      <div className="page narrow">
        <div className="quiz-shell" style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', minHeight: 320 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 12 }}>
            <span style={{ background: 'var(--psy-accent)', color: '#fff', borderRadius: 8, width: 32, height: 32, display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 15, flexShrink: 0 }}>{q.num}</span>
            <h2 style={{ margin: 0, fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em' }}>
              <strong>{el ? q.title_el || q.title : q.title}:</strong> <span style={{ fontWeight: 400, color: 'var(--fg2)' }}>{el ? q.sub_el || q.sub : q.sub}</span>
            </h2>
          </div>
          <button className="btn accent" style={{ alignSelf: 'flex-start', marginTop: 20, fontSize: 15, padding: '13px 28px' }} onClick={() => advance()}>
            {el ? 'Συνέχεια' : 'Continue'}
          </button>
        </div>
      </div>
    );
  }

  const multiSelected = q.multi ? (answers[q.id] || []) : null;
  const selCount = multiSelected?.length || 0;
  const atMax = q.maxSelect && selCount >= q.maxSelect;

  let countLabel = '';
  if (q.multi) {
    if (q.maxSelect) {
      countLabel = atMax
        ? (el ? `Επιλέξατε ${selCount} από ${q.maxSelect}` : `${selCount} of ${q.maxSelect} selected`)
        : (el ? `Μπορείτε να επιλέξετε έως ${q.maxSelect}` : `You can choose up to ${q.maxSelect}`);
    } else {
      countLabel = el ? 'Επιλέξτε όσα θέλετε' : 'Choose as many as you like';
    }
  }

  return (
    <div className="page narrow">
      <div className="quiz-shell">
        <div className="quiz-progress">
          {questionSteps.map((_, i) => (
            <span key={i} className={`seg ${i < qIndex ? 'done' : i === qIndex ? 'now' : ''}`}></span>
          ))}
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12, fontSize: 13, color: 'var(--fg2)' }}>
          <span>{t('quiz_step')} {qIndex + 1} {t('quiz_of')} {questionSteps.length}</span>
          <button className="quiz-skip-top" onClick={onSkip}>{t('quiz_skip')}</button>
        </div>

        <h2 className="quiz-question">{el ? q.title_el || q.title : q.title}</h2>
        {q.sub && <p className="quiz-sub">{el ? q.sub_el || q.sub : q.sub}</p>}
        {q.multi && <p style={{ fontSize: 13, color: 'var(--fg3)', marginBottom: 16, marginTop: -8 }}>{countLabel}</p>}

        <div className={`quiz-options${q.grid ? ' quiz-grid' : ''}`}>
          {q.options.map((opt, i) => {
            const isSel = q.multi
              ? multiSelected.some(o => o.id === opt.id)
              : answers[q.id]?.id === opt.id;
            const isDisabled = q.multi && atMax && !isSel;
            return (
              <button key={opt.id}
                className={`quiz-option${isSel ? ' selected' : ''}${isDisabled ? ' disabled' : ''}`}
                style={isDisabled ? { opacity: 0.35, cursor: 'not-allowed' } : {}}
                onClick={() => {
                  if (isDisabled) return;
                  q.multi ? toggleMulti(opt) : pickSingle(opt);
                }}>
                <span className="key">{String.fromCharCode(65 + i)}</span>
                {el ? opt.label_el || opt.label : opt.label}
              </button>
            );
          })}
        </div>

        <div className="quiz-foot">
          <button className="btn ghost sm" onClick={() => setStep(Math.max(0, step - 1))} disabled={step === 0}>
            <Icon name="arrow_back" className="sm" /> {t('quiz_back')}
          </button>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <span style={{ fontSize: 12, color: 'var(--fg3)', marginRight: 4 }}>
              <Icon name="lock" className="sm" style={{ verticalAlign: -2 }} /> {t('home_quiz_privacy')}
            </span>
            {q.multi && q.optional && (
              <button className="btn ghost" onClick={() => advance()}>
                {el ? 'Παράλειψη' : 'Skip'}
              </button>
            )}
            {q.multi && (
              <button className="btn accent"
                disabled={!q.optional && selCount === 0}
                onClick={() => advance()}>
                OK
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// Tally answers into a recommendation (handles both single options and arrays from multi-select)
function scoreAnswers(answers) {
  const approachScore = {};
  const tagScore = {};
  let mode = null, district = null, language = null, gesy = null;

  for (const answer of Object.values(answers)) {
    const opts = Array.isArray(answer) ? answer : [answer];
    for (const opt of opts) {
      if (!opt) continue;
      if (opt.approach) {
        for (const [k, v] of Object.entries(opt.approach)) approachScore[k] = (approachScore[k] || 0) + v;
      }
      if (opt.tags) {
        for (const [k, v] of Object.entries(opt.tags)) tagScore[k] = (tagScore[k] || 0) + v;
      }
      if (opt.meta?.mode && !mode) mode = opt.meta.mode;
      if (opt.meta?.district) district = opt.meta.district;
      if (opt.meta?.language !== undefined && !language) language = opt.meta.language;
      if (opt.meta?.gesy !== undefined) gesy = opt.meta.gesy;
    }
  }

  // For multi-mode, prefer the first selected
  if (Array.isArray(answers.mode) && answers.mode.length > 0) {
    mode = answers.mode.length === 1 ? answers.mode[0].meta?.mode : 'both';
  }

  const topApproach = Object.entries(approachScore).sort((a, b) => b[1] - a[1])[0]?.[0] || 'integrative';
  const topTags = Object.entries(tagScore).sort((a, b) => b[1] - a[1]).slice(0, 2).map(x => x[0]);

  return { approach: topApproach, tags: topTags, mode, district, language, gesy };
}

// ===========================================================
//  QUIZ RESULT
// ===========================================================
function QuizResultScreen({ result, setRoute, setFiltersFromResult }) {
  const { t } = useLang();
  const approach = APPROACHES.find(a => a.id === result.approach) || APPROACHES[0];
  const topTags = result.tags
    .map(id => SPECIALIZATIONS.find(s => s.id === id))
    .filter(Boolean);

  // matching psychologists (preview)
  const matched = PSYS.filter(p => p.approaches.includes(approach.id))
    .filter(p => !result.district || p.district === result.district || result.mode === 'online')
    .filter(p => !result.language || p.languages.includes(result.language))
    .slice(0, 3);

  return (
    <div className="page narrow">
      <div style={{ paddingTop: 32 }}>
        <div className="recommend-card">
          <span className="badge"><Icon name="auto_awesome" className="sm" /> {t('quiz_result_match')}</span>
          <h2>
            {t('quiz_result_based')} <em>{approach.long}</em> {t('quiz_result_fits')}
          </h2>
          <p className="why">
            {approach.short}
          </p>
          {topTags.length > 0 && (
            <div style={{ display: 'flex', gap: 8, marginTop: 18, flexWrap: 'wrap' }}>
              <span style={{ fontSize: 13, color: 'var(--fg2)', alignSelf: 'center' }}>{t('quiz_result_also')}</span>
              {topTags.map(tag => <span key={tag.id} className="tag accent">{tag.name}</span>)}
            </div>
          )}
          <div style={{ marginTop: 28, display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            <button className="btn primary" onClick={() => { setFiltersFromResult(result); setRoute('directory'); }}>
              {t('quiz_result_see')} {matched.length > 0
                ? `${matched.length} ${matched.length === 1 ? t('quiz_result_match_s') : t('quiz_result_matches')}`
                : t('quiz_result_matches')
              } <Icon name="arrow_forward" className="sm" />
            </button>
            <button className="btn ghost" onClick={() => setRoute('directory')}>{t('quiz_result_browse_all')}</button>
          </div>
          <div className="divider"></div>
          <div style={{ fontSize: 12, color: 'var(--fg3)', lineHeight: 1.6 }}>
            <strong style={{ color: 'var(--fg2)' }}>{t('quiz_result_what')}</strong> {t('quiz_result_what_body')}
          </div>
        </div>

        {/* Quick preview of matched psychologists */}
        {matched.length > 0 && (
          <div style={{ marginTop: 40 }}>
            <div className="section-head">
              <div>
                <span className="eyebrow muted">{t('quiz_result_look')}</span>
                <h2 style={{ marginTop: 6 }}>{t('quiz_result_found')}</h2>
              </div>
            </div>
            <div className="psy-list">
              {matched.map(p => <PsyCard key={p.id} psy={p} onOpen={() => setRoute('detail', p.id)} saved={false} onToggleSave={() => {}} />)}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { HomeScreen, QuizScreen, QuizResultScreen, scoreAnswers, QUIZ_QUESTIONS, MiniPsyCard });
