// components.jsx — shared UI primitives for Psyche

const { useState, useEffect, useMemo, useRef, useContext, createContext } = React;

// ----- Icon -----
function Icon({ name, className = '', style }) {
  return <span className={`icon ${className}`} style={style} aria-hidden="true">{name}</span>;
}

// ----- Brand mark -----
// Geometric Ψ (psi) — the universal symbol of psychology.
// Built from clean geometric strokes so it scales crisply.
function PsycheMark({ size = 32, color = 'var(--psy-accent)' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 40 40" fill="none" aria-hidden="true">
      {/* central stem */}
      <line x1="20" y1="6" x2="20" y2="34" stroke={color} strokeWidth="3" strokeLinecap="round" />
      {/* curved outer arms — like a cradle */}
      <path
        d="M 8 12 L 8 18 C 8 24, 12 26, 20 26"
        stroke={color} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" fill="none" />
      <path
        d="M 32 12 L 32 18 C 32 24, 28 26, 20 26"
        stroke={color} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" fill="none" />
      {/* small dot at top — "breath" */}
      <circle cx="20" cy="6" r="2.4" fill={color} />
    </svg>
  );
}

// ----- Stars -----
function Stars({ value = 0, size }) {
  const full = Math.floor(value);
  const half = value - full >= 0.5;
  const out = [];
  for (let i = 0; i < 5; i++) {
    const filled = i < full || (i === full && half);
    out.push(<Icon key={i} name={filled ? 'star' : 'star'} className={filled ? '' : 'empty'} style={size ? { fontSize: size } : null} />);
  }
  return <span className="stars">{out}</span>;
}

// ----- Avatar -----
function Avatar({ psy, size = 'lg' }) {
  if (size === 'sm') {
    if (psy.avatarData) {
      return (
        <div className="avatar-sm" style={{ background: avatarBg(psy.avatarVariant), overflow: 'hidden', padding: 0 }}>
          <img src={psy.avatarData} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: '50%' }} />
        </div>
      );
    }
    return (
      <div className="avatar-sm" style={{ background: avatarBg(psy.avatarVariant) }}>
        {psy.initials}
      </div>
    );
  }
  if (psy.avatarData) {
    return (
      <div className={`avatar-large ${psy.avatarVariant || 'a'}`} style={{ overflow: 'hidden', padding: 0 }}>
        <img src={psy.avatarData} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: '50%' }} />
      </div>
    );
  }
  return (
    <div className={`avatar-large ${psy.avatarVariant || 'a'}`}>
      {psy.initials}
    </div>
  );
}
function avatarBg(v) {
  switch (v) {
    case 'b': return 'linear-gradient(135deg, #c8e0c2, #4d7c5a)';
    case 'c': return 'linear-gradient(135deg, #d6dcf3, #2581eb)';
    case 'd': return 'linear-gradient(135deg, #f3c8d6, #b04d70)';
    case 'e': return 'linear-gradient(135deg, #efe1bf, #b08a3d)';
    default:  return 'linear-gradient(135deg, color-mix(in oklab, var(--psy-accent) 35%, white), var(--psy-accent))';
  }
}

// ----- LangToggle -----
function LangToggle() {
  const { lang, setLang } = useLang();
  return (
    <div style={{ display: 'flex', gap: 2, background: 'var(--psy-surface)', border: '1px solid var(--psy-rule)', borderRadius: 8, padding: 2 }}>
      {['en', 'el'].map(function(l) {
        return (
          <button key={l} onClick={function() { setLang(l); }}
            style={{
              appearance: 'none', border: 0, cursor: 'pointer',
              padding: '3px 9px', borderRadius: 6, fontSize: 12, fontWeight: 600,
              background: lang === l ? 'var(--psy-ink)' : 'transparent',
              color: lang === l ? 'white' : 'var(--fg2)',
              transition: 'all 0.15s',
              letterSpacing: '0.03em',
            }}>
            {l === 'en' ? 'EN' : 'ΕΛ'}
          </button>
        );
      })}
    </div>
  );
}

// ----- TopNav -----
function TopNav({ route, setRoute, persona, setPersona, savedCount, authUser, onSignOut, openAuth, navAvatarData }) {
  const { t } = useLang();

  const userLinks = [
    { id: 'home',      label: t('nav_home') },
    { id: 'directory', label: t('nav_directory') },
    { id: 'pricing',   label: t('nav_for_psychologists'), muted: true },
    { id: 'learn',     label: t('nav_learn') },
    { id: 'journal',   label: t('nav_journal') },
  ];
  const proLinks = [
    { id: 'provider',  label: t('nav_dashboard') },
    { id: 'directory', label: t('nav_directory') },
    { id: 'learn',     label: t('nav_learn') },
    { id: 'chat',      label: t('nav_messages') },
  ];
  const adminLinks = [
    { id: 'admin',     label: t('nav_queue') },
    { id: 'directory', label: t('nav_directory') },
    { id: 'learn',     label: t('nav_learn') },
  ];
  const links = persona === 'pro' ? proLinks : persona === 'admin' ? adminLinks : userLinks;

  return (
    <nav className="topnav">
      <div className="topnav-inner">
        <a className="brand" onClick={(e) => { e.preventDefault(); setRoute('home'); }} style={{ fontWeight: 800, fontSize: '2rem', letterSpacing: '-0.02em', textDecoration: 'none', color: '#1a1523', display: 'flex', alignItems: 'baseline', gap: 0 }}>
          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>
        </a>
        <div className="nav-links">
          {links.map(l => (
            <button key={l.id}
              className={`nav-link ${route === l.id ? 'active' : ''}`}
              style={l.muted && route !== l.id ? { color: 'var(--fg3)' } : {}}
              onClick={() => setRoute(l.id)}>
              {l.label}
            </button>
          ))}
        </div>
        <div className="nav-spacer"></div>

        <LangToggle />

        {authUser ? (
          <>
            {persona === 'user' && (
              <>
                <button className="nav-icon-btn" onClick={() => setRoute('my-sessions')} title={t('nav_my_sessions')}
                  style={route === 'my-sessions' || route === 'video-call' || route === 'book' ? { color: 'var(--psy-accent)' } : {}}>
                  <Icon name="calendar_month" />
                </button>
                <button className="nav-icon-btn" onClick={() => setRoute('shortlist')} title={t('nav_shortlist')}>
                  <Icon name="bookmark" />
                  {savedCount > 0 && <span className="dot"></span>}
                </button>
              </>
            )}
            <button className="nav-icon-btn" onClick={() => setRoute('chat')} title={t('nav_messages')}
              style={route === 'chat' ? { color: 'var(--psy-accent)' } : {}}>
              <Icon name="forum" />
            </button>
            <PersonaSwitcher persona={persona} setPersona={setPersona} onSignOut={onSignOut} authUser={authUser} setRoute={setRoute} navAvatarData={navAvatarData} />
          </>
        ) : (
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <button className="btn ghost sm" onClick={() => openAuth('login')}>{t('nav_signin')}</button>
            <button className="btn primary sm" onClick={() => openAuth('signup')}>{t('nav_signup')}</button>
          </div>
        )}
      </div>
    </nav>
  );
}

function PersonaSwitcher({ persona, setPersona, onSignOut, authUser, setRoute, navAvatarData }) {
  const { t } = useLang();
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    function onDoc(e) { if (ref.current && !ref.current.contains(e.target)) setOpen(false); }
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, []);

  const role     = authUser?.role || 'user';
  const name     = authUser?.name || 'Account';
  const initials = name.split(' ').map(w => w[0]).slice(0, 2).join('').toUpperCase();

  const [avatarVariant, setAvatarVariant] = React.useState(null);
  const [deleteConfirm, setDeleteConfirm] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [localAvatar, setLocalAvatar] = useState(authUser?.avatar_data || null);
  React.useEffect(() => { if (authUser?.avatar_data) setLocalAvatar(authUser.avatar_data); }, [authUser?.avatar_data]);
  // navAvatarData: undefined = no user action yet, null = explicitly removed, string = new photo
  const displayAvatar = navAvatarData !== undefined ? navAvatarData : localAvatar;

  React.useEffect(() => {
    if (role !== 'user' || !authUser?.id) return;
    const token = JSON.parse(localStorage.getItem('psyche-auth') || '{}').token || '';
    fetch('/api/users/profile', { headers: { Authorization: 'Bearer ' + token } })
      .then(r => r.ok ? r.json() : null)
      .then(d => { if (d?.avatar_data) setLocalAvatar(d.avatar_data); })
      .catch(() => {});
  }, [authUser?.id]);

  async function handleDeleteAccount() {
    setDeleting(true);
    try {
      const stored = JSON.parse(localStorage.getItem('psyche-auth') || '{}');
      const token = stored.token || '';
      const res = await fetch('/api/users/me', {
        method: 'DELETE',
        headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' },
      });
      if (res.ok) { setOpen(false); onSignOut(); }
      else { setDeleting(false); }
    } catch { setDeleting(false); }
  }
  React.useEffect(() => {
    if (role === 'pro' && authUser?.id) {
      API.getMyProfile && API.getMyProfile()
        .then(d => {
          if (d && d.avatarVariant != null) setAvatarVariant(d.avatarVariant);
          if (d && d.avatarData) setLocalAvatar(d.avatarData);
        })
        .catch(() => {});
    }
  }, [role, authUser?.id]);

  const roleLabel = { user: 'Member', pro: 'Psychologist', admin: 'Psyche admin' }[role] || 'Member';
  const roleColor = role === 'admin' ? 'var(--psy-ink)' : role === 'pro' ? avatarBg(avatarVariant != null ? avatarVariant : 'b') : avatarBg('a');

  // Admin-only view options
  const adminViews = [
    { id: 'admin', label: 'Admin panel',        icon: 'admin_panel_settings' },
    { id: 'user',  label: 'Browse as visitor',  icon: 'person'               },
    { id: 'pro',   label: 'Psychologist view',  icon: 'medical_services'     },
  ];

  return (
    <div style={{ position: 'relative' }} ref={ref}>
      <button className="persona-pill" onClick={() => setOpen(!open)}>
        {displayAvatar
          ? <span className="avatar" style={{ background: roleColor, overflow: 'hidden', padding: 0 }}><img src={displayAvatar} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: '50%' }} /></span>
          : <span className="avatar" style={{ background: roleColor }}>{initials}</span>}
        {name.split(' ')[0]}
        <Icon name="expand_more" className="sm" />
      </button>

      {open && (
        <div style={{
          position: 'absolute', right: 0, top: 'calc(100% + 6px)',
          background: 'white', border: '1px solid var(--psy-rule)',
          borderRadius: 14, padding: 6, minWidth: 240,
          boxShadow: 'var(--elev-4)', zIndex: 30,
        }}>
          {/* Identity header */}
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', padding: '10px 12px 12px' }}>
            <span className="avatar" style={{
              width: 36, height: 36, borderRadius: '50%', background: roleColor,
              color: 'white', display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 13, flexShrink: 0,
              overflow: 'hidden', padding: 0,
            }}>
              {displayAvatar
                ? <img src={displayAvatar} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                : initials}
            </span>
            <span>
              <div style={{ fontWeight: 600, fontSize: 14, color: 'var(--psy-ink)' }}>{name}</div>
              <div style={{ fontSize: 12, color: 'var(--fg2)', marginTop: 1 }}>{roleLabel}</div>
            </span>
          </div>

          <div style={{ height: 1, background: 'var(--psy-rule)', margin: '0 4px 6px' }} />

          {/* Admin: full view switcher */}
          {role === 'admin' && (
            <>
              <div style={{ padding: '4px 12px 6px', fontSize: 11, color: 'var(--fg3)', textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 600 }}>
                Switch view
              </div>
              {adminViews.map(v => (
                <button key={v.id}
                  onClick={() => { setPersona(v.id); setOpen(false); }}
                  style={{
                    width: '100%', display: 'flex', gap: 10, alignItems: 'center',
                    padding: '9px 12px', background: persona === v.id ? 'var(--psy-surface)' : 'transparent',
                    border: 0, borderRadius: 10, cursor: 'pointer', fontSize: 14, color: 'var(--psy-ink)',
                  }}>
                  <Icon name={v.icon} className="sm" style={{ color: 'var(--fg2)' }} />
                  {v.label}
                  {persona === v.id && <Icon name="check" className="sm" style={{ marginLeft: 'auto', color: 'var(--psy-ink)' }} />}
                </button>
              ))}
              <div style={{ height: 1, background: 'var(--psy-rule)', margin: '6px 4px' }} />
            </>
          )}

          {/* Pro: can toggle between dashboard and visitor browsing */}
          {role === 'pro' && (
            <>
              {persona === 'pro'
                ? (
                  <button onClick={() => { setPersona('user'); setOpen(false); }}
                    style={{ width: '100%', display: 'flex', gap: 10, alignItems: 'center', padding: '9px 12px', background: 'transparent', border: 0, borderRadius: 10, cursor: 'pointer', fontSize: 14, color: 'var(--psy-ink)' }}>
                    <Icon name="person" className="sm" style={{ color: 'var(--fg2)' }} />
                    Browse as visitor
                  </button>
                ) : (
                  <button onClick={() => { setPersona('pro'); setOpen(false); }}
                    style={{ width: '100%', display: 'flex', gap: 10, alignItems: 'center', padding: '9px 12px', background: 'transparent', border: 0, borderRadius: 10, cursor: 'pointer', fontSize: 14, color: 'var(--psy-ink)' }}>
                    <Icon name="dashboard" className="sm" style={{ color: 'var(--fg2)' }} />
                    Back to my dashboard
                  </button>
                )
              }
              <div style={{ height: 1, background: 'var(--psy-rule)', margin: '6px 4px' }} />
            </>
          )}

          {/* Account settings — all logged-in users */}
          {authUser && (persona === 'user' || persona === 'pro') && (
            <>
              <button onClick={() => { setOpen(false); setRoute('user-profile'); }}
                style={{ width: '100%', display: 'flex', gap: 10, alignItems: 'center', padding: '9px 12px', background: 'transparent', border: 0, borderRadius: 10, cursor: 'pointer', fontSize: 14, color: 'var(--psy-ink)' }}>
                <Icon name="manage_accounts" className="sm" style={{ color: 'var(--fg2)' }} />
                {t('acct_h1')}
              </button>
              <div style={{ height: 1, background: 'var(--psy-rule)', margin: '6px 4px' }} />
            </>
          )}

          {/* Sign out — everyone */}
          <button onClick={() => { setOpen(false); onSignOut(); }}
            style={{
              width: '100%', display: 'flex', gap: 10, alignItems: 'center',
              padding: '9px 12px', background: 'transparent',
              border: 0, borderRadius: 10, cursor: 'pointer',
              color: 'var(--fg2)', fontSize: 14, fontWeight: 500,
            }}>
            <Icon name="logout" className="sm" /> {t('nav_signout')}
          </button>

          {/* Delete account — at the very bottom, subtle */}
          {authUser && !deleteConfirm && (
            <>
              <div style={{ height: 1, background: 'var(--psy-rule)', margin: '6px 4px' }} />
              <button onClick={() => setDeleteConfirm(true)}
                style={{ width: '100%', textAlign: 'left', padding: '7px 12px', background: 'transparent', border: 0, borderRadius: 10, cursor: 'pointer', color: 'var(--fg3)', fontSize: 12 }}>
                {t('acct_delete_btn')}
              </button>
            </>
          )}
          {authUser && deleteConfirm && (
            <div style={{ padding: '10px 12px', borderTop: '1px solid var(--psy-rule)', marginTop: 4 }}>
              <p style={{ margin: '0 0 10px', fontSize: 12, color: 'var(--psy-ink)', fontWeight: 600 }}>{t('acct_delete_confirm_h')}</p>
              <div style={{ display: 'flex', gap: 6 }}>
                <button onClick={handleDeleteAccount} disabled={deleting}
                  style={{ flex: 1, background: '#DC2626', color: 'white', border: 'none', borderRadius: 8, padding: '7px 0', fontSize: 12, fontWeight: 700, cursor: 'pointer' }}>
                  {deleting ? t('acct_deleting') : t('acct_delete_confirm_btn')}
                </button>
                <button onClick={() => setDeleteConfirm(false)}
                  style={{ flex: 1, background: 'var(--psy-surface)', color: 'var(--fg2)', border: '1px solid var(--psy-rule)', borderRadius: 8, padding: '7px 0', fontSize: 12, cursor: 'pointer' }}>
                  {t('acct_delete_cancel')}
                </button>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// ----- Crisis ribbon -----
function CrisisRibbon() {
  const { t } = useLang();
  return (
    <div className="crisis">
      {t('crisis_ribbon')}
    </div>
  );
}

// ----- Tag list -----
function TagList({ ids, source, kind = 'tag', max = 3 }) {
  const { lang } = useLang();
  const items = (ids || []).map(id => source.find(x => x.id === id)).filter(Boolean);
  const shown = items.slice(0, max);
  const extra = items.length - shown.length;
  return (
    <>
      {shown.map(x => (
        <span key={x.id} className={`tag ${kind === 'accent' ? 'accent' : kind === 'leaf' ? 'leaf' : ''}`}>
          {lang === 'el' && x.name_el ? x.name_el : x.name}
        </span>
      ))}
      {extra > 0 && <span className="tag">+{extra}</span>}
    </>
  );
}

// ----- Verified badge -----
function VerifiedBadge({ children = 'Verified review' }) {
  return (
    <span className="verified-badge">
      <Icon name="verified" /> {children}
    </span>
  );
}

// ----- Toast -----
function Toast({ message, onDone, duration = 3000 }) {
  useEffect(() => {
    if (!message) return;
    const t = setTimeout(onDone, duration);
    return () => clearTimeout(t);
  }, [message]);
  if (!message) return null;
  return <div className="toast">{message}</div>;
}

// ----- Mood face (svg) -----
function MoodFace({ value, size = 28 }) {
  // value 0..1 — sad to happy
  const angry = value < 0.25;
  const ok = value >= 0.25 && value < 0.75;
  const happy = value >= 0.75;
  const color = angry ? '#b04d70' : ok ? '#9c7600' : '#4d7c5a';
  // mouth path interpolates
  const y = 22 - (value * 8); // higher value = lower mouth curve start point
  const curve = (value - 0.5) * 14; // negative = frown, positive = smile
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
      <circle cx="11" cy="13" r="1.6" fill={color} />
      <circle cx="21" cy="13" r="1.6" fill={color} />
      <path d={`M 10 ${y} Q 16 ${y + curve}, 22 ${y}`} stroke={color} strokeWidth="2" strokeLinecap="round" fill="none" />
    </svg>
  );
}

// ----- Hero ornament — abstract "psyche" composition.
// Layered concentric rings + an enlarged psi mark, palette-aware.
function ThreadArt() {
  return (
    <div style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <img
        src="/hero-photo.png"
        alt=""
        style={{ width: '100%', maxWidth: 680, mixBlendMode: 'multiply', display: 'block' }}
      />
    </div>
  );
}

// ----- SiteFooter -----
function SiteFooter({ setRoute }) {
  const { lang } = useLang();

  var col2Links = [
    { label: lang === 'el' ? 'Βρείτε ψυχολόγο' : 'Find a psychologist', route: 'directory' },
    { label: lang === 'el' ? 'Για ψυχολόγους' : 'For psychologists', route: 'pricing' },
    { label: lang === 'el' ? 'Κουίζ αντιστοίχισης' : 'Matching quiz', route: 'quiz' },
    { label: lang === 'el' ? 'Άρθρα' : 'Learn', route: 'learn' },
    { label: lang === 'el' ? 'Κέντρο Βοήθειας' : 'Help Center', route: 'help' },
  ];

  var col3Links = [
    { label: lang === 'el' ? 'Τεστ κατάθλιψης' : 'Depression test', route: 'depression-test' },
    { label: lang === 'el' ? 'Τεστ άγχους' : 'Anxiety test', route: 'anxiety-test' },
    { label: lang === 'el' ? 'Τεστ ADHD' : 'ADHD test', route: 'adhd-test' },
    { label: lang === 'el' ? 'Τεστ αυτοεκτίμησης' : 'Self-esteem test', route: 'self-esteem-test' },
    { label: lang === 'el' ? 'Ψυχολόγος ή ψυχίατρος;' : 'Psychologist vs psychiatrist', route: 'article', id: 'psychologist-vs-psychiatrist' },
    { label: lang === 'el' ? 'Πρώτη συνεδρία' : 'First therapy session', route: 'article', id: 'first-session' },
  ];

  var col4Legal = [
    { label: lang === 'el' ? 'Πολιτική Απορρήτου' : 'Privacy Policy', route: 'privacy' },
    { label: lang === 'el' ? 'Όροι Χρήσης' : 'Terms of Use', route: 'terms' },
    { label: lang === 'el' ? 'Κώδικας Δεοντολογίας' : 'Code of Conduct', route: 'ethics' },
    { label: lang === 'el' ? 'Κέντρο Βοήθειας' : 'Help Center', route: 'help' },
  ];

  var navBtnStyle = {
    display: 'block', background: 'none', border: 0, padding: '4px 0',
    fontSize: 13, color: 'var(--fg2)', cursor: 'pointer', textAlign: 'left',
    transition: 'color 0.15s',
  };

  return (
    <footer style={{ borderTop: '1px solid var(--psy-rule)', background: 'var(--psy-surface)', padding: '40px 32px 24px', marginTop: 40 }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 1fr', gap: 32 }}>

        {/* Column 1 — Brand */}
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
            <PsycheMark size={22} />
            <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16, letterSpacing: '-0.02em' }}>Psyche</span>
          </div>
          <p style={{ fontSize: 13, color: 'var(--fg2)', lineHeight: 1.55, maxWidth: 220, margin: '0 0 16px' }}>
            {lang === 'el' ? 'Η σωστή πλατφόρμα αναζήτησης ψυχολόγων στην Κύπρο.' : 'The right psychologist directory for Cyprus.'}
          </p>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '6px 12px',
            border: '1.5px solid var(--psy-leaf)', borderRadius: 10, marginBottom: 10 }}>
            <Icon name="verified_user" style={{ color: 'var(--psy-leaf)', fontSize: 16 }} />
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--psy-leaf)', lineHeight: 1 }}>GDPR</div>
              <div style={{ fontSize: 10, color: 'var(--psy-leaf)', lineHeight: 1.2 }}>Compliant</div>
            </div>
          </div>
          <p style={{ fontSize: 11, color: 'var(--fg3)', margin: '8px 0 0' }}>
            {"© 2026 Psyche · " + (lang === 'el' ? 'Φτιαγμένο στην Κύπρο' : 'Built in Cyprus')}
          </p>
        </div>

        {/* Column 2 — Platform */}
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg3)', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 14 }}>
            {lang === 'el' ? 'Πλατφόρμα' : 'Platform'}
          </div>
          {col2Links.map(function(item) {
            return (
              <button key={item.route} onClick={function() { setRoute(item.route); }}
                style={navBtnStyle}
                onMouseEnter={function(e) { e.target.style.color = 'var(--psy-ink)'; }}
                onMouseLeave={function(e) { e.target.style.color = 'var(--fg2)'; }}>
                {item.label}
              </button>
            );
          })}
        </div>

        {/* Column 3 — Resources (self-tests + articles) */}
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg3)', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 14 }}>
            {lang === 'el' ? 'Πόροι' : 'Resources'}
          </div>
          {col3Links.map(function(item) {
            return (
              <button key={item.id ? (item.route + '-' + item.id) : item.route}
                onClick={function() { setRoute(item.route, item.id || undefined); }}
                style={navBtnStyle}
                onMouseEnter={function(e) { e.target.style.color = 'var(--psy-ink)'; }}
                onMouseLeave={function(e) { e.target.style.color = 'var(--fg2)'; }}>
                {item.label}
              </button>
            );
          })}
        </div>

        {/* Column 4 — Legal & Contact */}
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg3)', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 14 }}>
            {lang === 'el' ? 'Επικοινωνία & Νομικά' : 'Contact & Legal'}
          </div>
          {col4Legal.map(function(item) {
            return (
              <button key={item.route + '-legal'} onClick={function() { setRoute(item.route); }}
                style={navBtnStyle}
                onMouseEnter={function(e) { e.target.style.color = 'var(--psy-ink)'; }}
                onMouseLeave={function(e) { e.target.style.color = 'var(--fg2)'; }}>
                {item.label}
              </button>
            );
          })}
          <a href="mailto:hello@psyche.cy"
            style={{ display: 'block', padding: '4px 0', fontSize: 13, color: 'var(--fg2)', textDecoration: 'none' }}>
            hello@psyche.cy
          </a>
          <div style={{ marginTop: 16, padding: '8px 12px', background: 'white', borderRadius: 8,
            border: '1px solid var(--psy-rule)', display: 'flex', alignItems: 'center', gap: 8 }}>
            <Icon name="lock" style={{ color: 'var(--psy-leaf)', fontSize: 14 }} />
            <span style={{ fontSize: 11, color: 'var(--fg3)', lineHeight: 1.4 }}>
              Data hosted in EU<br />No tracking cookies
            </span>
          </div>
        </div>
      </div>

      {/* Crisis line */}
      <div style={{ maxWidth: 1200, margin: '24px auto 0', paddingTop: 20,
        borderTop: '1px solid var(--psy-rule)', display: 'flex', alignItems: 'center',
        justifyContent: 'space-between', fontSize: 11, color: 'var(--fg3)', flexWrap: 'wrap', gap: 8 }}>
        <span>
          {lang === 'el'
            ? 'Το Psyche δεν είναι υπηρεσία κρίσεων. Σε έκτακτη ανάγκη καλέστε 1410 ή 112.'
            : 'Psyche is not a crisis service. In an emergency call 1410 or 112.'
          }
        </span>
        <span>{"© 2026 Psyche"}</span>
      </div>
    </footer>
  );
}

// ----- AddressInput: text input with Nominatim geocoding -----
function AddressInput({ value, onChange, onCoords, district }) {
  const timer = React.useRef(null);
  const [suggestions, setSuggestions] = React.useState([]);
  const [open, setOpen] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const wrapRef = React.useRef(null);

  // Close dropdown on outside click
  React.useEffect(() => {
    function handleClick(e) {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);
    }
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, []);

  function handleChange(e) {
    const v = e.target.value;
    onChange(v);
    setSuggestions([]);
    clearTimeout(timer.current);
    if (v.length < 3) { setOpen(false); return; }
    setLoading(true);
    timer.current = setTimeout(async () => {
      try {
        const districtHint = district && district !== 'Other' ? `, ${district}` : '';
        const q = encodeURIComponent(v + districtHint + ', Cyprus');
        const r = await fetch(`https://nominatim.openstreetmap.org/search?q=${q}&format=json&limit=5&countrycodes=cy&addressdetails=1`, {
          headers: { 'Accept-Language': 'el,en' }
        });
        const data = await r.json();
        setSuggestions(data);
        setOpen(data.length > 0);
      } catch (_) {}
      setLoading(false);
    }, 500);
  }

  function selectSuggestion(item) {
    // Build clean label: first 3 parts of display_name
    const parts = item.display_name.split(',').map(s => s.trim());
    const label = parts.slice(0, 3).join(', ');
    onChange(label);
    onCoords({ lat: parseFloat(item.lat), lon: parseFloat(item.lon) });
    setSuggestions([]);
    setOpen(false);
  }

  return (
    <div ref={wrapRef} style={{ position: 'relative' }}>
      <input className="input" value={value} onChange={handleChange}
        onFocus={() => suggestions.length > 0 && setOpen(true)}
        placeholder="12 Stasikratous, Office 4B, 1065 Nicosia"
        autoComplete="off" />
      {loading && (
        <div style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', fontSize: 12, color: 'var(--fg3)' }}>
          🔍
        </div>
      )}
      {open && suggestions.length > 0 && (
        <div style={{
          position: 'absolute', top: '100%', left: 0, right: 0, zIndex: 999,
          background: 'white', border: '1px solid var(--psy-rule)', borderRadius: 12,
          boxShadow: '0 8px 24px rgba(0,0,0,0.12)', marginTop: 4, overflow: 'hidden',
        }}>
          {suggestions.map((item, i) => {
            const parts = item.display_name.split(',').map(s => s.trim());
            const main = parts.slice(0, 2).join(', ');
            const sub  = parts.slice(2, 4).join(', ');
            return (
              <div key={i}
                onMouseDown={() => selectSuggestion(item)}
                style={{
                  padding: '10px 14px', cursor: 'pointer', borderTop: i ? '1px solid var(--psy-rule)' : 'none',
                  display: 'flex', alignItems: 'center', gap: 10,
                }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--psy-surface)'}
                onMouseLeave={e => e.currentTarget.style.background = ''}>
                <Icon name="location_on" className="sm" style={{ color: 'var(--psy-accent)', flexShrink: 0 }} />
                <div>
                  <div style={{ fontSize: 14, fontWeight: 500 }}>{main}</div>
                  {sub && <div style={{ fontSize: 12, color: 'var(--fg3)', marginTop: 1 }}>{sub}</div>}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ----- MapPreview: OpenStreetMap embed -----
function MapPreview({ address, coords, district }) {
  if (coords && coords.lat) {
    const url = `https://www.openstreetmap.org/export/embed.html?bbox=${coords.lon-0.005},${coords.lat-0.003},${coords.lon+0.005},${coords.lat+0.003}&layer=mapnik&marker=${coords.lat},${coords.lon}`;
    return (
      <div style={{ marginTop: 12, height: 180, borderRadius: 12, overflow: 'hidden', border: '1px solid var(--psy-rule)' }}>
        <iframe src={url} width="100%" height="100%" style={{ border: 0 }} title="map" loading="lazy" />
      </div>
    );
  }
  return (
    <div className="map" style={{ marginTop: 12, height: 160 }}>
      <div className="pin">{district}</div>
    </div>
  );
}

// Export to window for cross-file use
Object.assign(window, {
  Icon, PsycheMark, Stars, Avatar, avatarBg, TopNav, CrisisRibbon, TagList, VerifiedBadge, Toast, MoodFace, ThreadArt, EmailVerificationBanner, SiteFooter,
  AddressInput, MapPreview,
});

// ----- Email verification banner -----
function EmailVerificationBanner({ email, onResent }) {
  const { t } = useLang();
  const [dismissed, setDismissed] = useState(false);
  const [sending, setSending] = useState(false);

  if (dismissed) return null;

  async function resend() {
    setSending(true);
    try {
      const raw = localStorage.getItem('psyche-auth');
      const token = raw ? JSON.parse(raw).token : null;
      await fetch('/api/auth/resend-verification', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
      });
      onResent && onResent();
    } catch {}
    finally { setSending(false); }
  }

  return (
    <div style={{
      background: 'color-mix(in oklab, var(--psy-accent) 8%, white)',
      borderBottom: '1px solid var(--psy-accent-soft)',
      padding: '10px 32px',
      display: 'flex', alignItems: 'center', gap: 12,
      fontSize: 13,
    }}>
      <Icon name="mark_email_unread" style={{ color: 'var(--psy-accent)', fontSize: 18 }} />
      <span style={{ flex: 1, color: 'var(--psy-ink)' }}>
        {t('email_banner_text')} <strong>{email}</strong>.
      </span>
      <button
        onClick={resend}
        disabled={sending}
        style={{ background: 'none', border: 0, cursor: 'pointer', color: 'var(--psy-accent)', fontWeight: 600, fontSize: 13 }}>
        {sending ? t('email_banner_sending') : t('email_banner_resend')}
      </button>
      <button
        onClick={() => setDismissed(true)}
        style={{ background: 'none', border: 0, cursor: 'pointer', color: 'var(--fg3)', fontSize: 18, lineHeight: 1 }}>
        ×
      </button>
    </div>
  );
}
