/* tab-screens.jsx — Routes / Community / Profile tab screens. Uses shared from window. */

function ScreenShell({ theme, title, action, children, active, go }) {
  const { TabBar } = window;
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 20, background: 'var(--bg)', display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '58px 20px 8px', display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', flexShrink: 0 }}>
        <h1 style={{ margin: 0, fontSize: 32, fontWeight: 800, letterSpacing: -0.5, color: 'var(--text)' }}>{title}</h1>
        {action}
      </div>
      <div className="noscroll" style={{ flex: 1, overflowY: 'auto', padding: '6px 0 116px' }}>
        {children}
      </div>
      <TabBar theme={theme} active={active} go={go} />
    </div>
  );
}

function Card({ children, style, onClick }) {
  return (
    <div onClick={onClick} className={onClick ? 'tap' : ''} style={{
      background: 'var(--surface)', borderRadius: 18, boxShadow: 'var(--shadow)',
      padding: 14, margin: '0 16px 10px', cursor: onClick ? 'pointer' : 'default', ...style,
    }}>{children}</div>
  );
}

// refined stat strip — framed card with accented metrics, dividers, optional trend
function StatStrip({ label, items, bare }) {
  const inner = (
    <React.Fragment>
      {label && <div style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: 0.6, color: 'var(--muted)', textTransform: 'uppercase', marginBottom: 13 }}>{label}</div>}
      <div style={{ display: 'flex', alignItems: 'stretch' }}>
        {items.map((it, i) => (
          <React.Fragment key={i}>
            {i > 0 && <div style={{ width: 1, alignSelf: 'center', height: 32, background: 'var(--hairline)' }} />}
            <div style={{ flex: 1, textAlign: 'center', padding: '0 4px' }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'center', gap: 2 }}>
                <span style={{ fontSize: 27, fontWeight: 800, lineHeight: 1, letterSpacing: -0.6, whiteSpace: 'nowrap', color: it.accent || 'var(--text)' }}>{it.n}</span>
                {it.unit && <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--faint)' }}>{it.unit}</span>}
              </div>
              <div style={{ fontSize: 11.5, color: 'var(--faint)', fontWeight: 600, marginTop: 6 }}>{it.l}</div>
              {it.trend && (
                <div style={{ marginTop: 7, display: 'inline-flex', alignItems: 'center', gap: 2, fontSize: 10.5, fontWeight: 800, color: 'var(--safe)', background: 'color-mix(in oklch, var(--safe) 14%, transparent)', borderRadius: 999, padding: '2px 7px' }}>
                  <svg width="9" height="9" viewBox="0 0 24 24" fill="none"><path d="M12 19V6M6 12l6-6 6 6" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg>{it.trend}
                </div>
              )}
            </div>
          </React.Fragment>
        ))}
      </div>
    </React.Fragment>
  );
  if (bare) return <div>{inner}</div>;
  return (
    <div style={{ margin: '4px 16px 14px', borderRadius: 20, padding: 1.5, background: 'linear-gradient(135deg, color-mix(in oklch, var(--brand) 32%, transparent), color-mix(in oklch, var(--brand) 5%, transparent))', boxShadow: 'var(--shadow)' }}>
      <div style={{ borderRadius: 18.5, background: 'var(--surface)', padding: '16px 16px 15px' }}>{inner}</div>
    </div>
  );
}

// ============================================================
// МАРШРУТИ (Routes / history)
// ============================================================
function EmptyHint({ children }) {
  return <div style={{ fontSize: 13.5, color: 'var(--muted)', fontWeight: 500, lineHeight: 1.45, padding: '4px 22px 8px' }}>{children}</div>;
}

function RoutesScreen({ theme, go, onPlanRoute }) {
  const { SafetyChip, SectionLabel, IconBike, IconChevR, IconStar } = window;
  const savedRoutes = window.useSavedRoutes();
  const trips = window.useTrips();
  // weekly summary from real trips in the last 7 days
  const weekAgo = Date.now() - 7 * 864e5;
  const week = trips.filter((t) => (t.ts || 0) >= weekAgo);
  const km = week.reduce((a, t) => a + (t.distM || 0), 0) / 1000;
  const avg = week.length ? Math.round(week.reduce((a, t) => a + (t.score || 0), 0) / week.length) : 0;
  const kmStr = (Math.round(km * 10) / 10).toString().replace('.', ',');
  return (
    <ScreenShell theme={theme} title="Маршрути" active="routes" go={go}>
      {/* weekly summary (computed from real trips) */}
      <StatStrip label="Тази седмица" items={[
        { n: week.length ? kmStr : '0', unit: 'км', l: 'разстояние' },
        { n: String(week.length), l: 'пътувания' },
        { n: avg ? String(avg) : '—', l: 'ср. безопасност', accent: 'var(--safe)' },
      ]} />

      <SectionLabel>Запазени</SectionLabel>
      {savedRoutes.length === 0 && <EmptyHint>Запазете маршрут със звездата в екрана с маршрути — ще се появи тук за бърз достъп.</EmptyHint>}
      {savedRoutes.map((s) => (
        <Card key={s.id} onClick={() => onPlanRoute && onPlanRoute(s)}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <span style={{ width: 38, height: 38, borderRadius: 11, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'color-mix(in oklch, var(--brand) 14%, transparent)', color: 'var(--brand)' }}><IconStar size={20} /></span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 16, fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.from} → {s.to}</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 5 }}>
                <SafetyChip level={s.level} score={s.score} />
                <span style={{ fontSize: 13, color: 'var(--muted)', fontWeight: 600 }}>{s.dist}{s.time ? ` · ${s.time} мин` : ''}</span>
              </div>
            </div>
            <IconChevR size={18} style={{ color: 'var(--faint)' }} />
          </div>
        </Card>
      ))}

      <SectionLabel>Скорошни пътувания</SectionLabel>
      {trips.length === 0 && <EmptyHint>Тук ще се появят пътуванията ти — щом стартираш навигация по маршрут.</EmptyHint>}
      {trips.map((tr) => (
        <Card key={tr.id}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <span style={{ width: 38, height: 38, borderRadius: 11, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--surface-2)', color: 'var(--muted)' }}><IconBike size={20} /></span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 15.5, fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{tr.from} → {tr.to}</div>
              <div style={{ fontSize: 12.5, color: 'var(--faint)', fontWeight: 600, marginTop: 2 }}>{window.vrWhen(tr.ts)}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 15, fontWeight: 800 }}>{tr.dist}</div>
              <div style={{ fontSize: 12, color: 'var(--muted)', fontWeight: 600 }}>{tr.dur}</div>
            </div>
          </div>
        </Card>
      ))}
    </ScreenShell>
  );
}

// ============================================================
// ОБЩНОСТ (Community)
// ============================================================
const C_STATS = [['128', 'сигнала'], ['1 240', 'колоездачи'], ['42', 'опасни зони']];
const REPORTS = [
  { cat: 'Дупка', Icon: 'IconWarn', level: 'moderate', loc: 'ул. Граф Игнатиев', ago: 'преди 12 мин', up: 8 },
  { cat: 'Опасно движение', Icon: 'IconCar', level: 'danger', loc: 'Орлов мост', ago: 'преди 1 ч', up: 21 },
  { cat: 'Блокирана велоалея', Icon: 'IconBike', level: 'moderate', loc: 'бул. България', ago: 'преди 2 ч', up: 5 },
  { cat: 'Ремонт на пътя', Icon: 'IconConstruction', level: 'moderate', loc: 'бул. Витоша', ago: 'преди 3 ч', up: 13 },
];
const CONTRIB = [
  { name: 'Ивайло П.', pts: '2 410', badge: 'Локален експерт' },
  { name: 'Мария Г.', pts: '1 980', badge: 'Доверен' },
];

function CommunityScreen({ theme, go, openReport, selId }) {
  const { SectionLabel, IconWarn, IconChevR, IconPlus, IconCheck } = window;
  const lc = (lvl) => `var(--${lvl})`;
  const reports = window.useComm();
  // selection: a tapped card, OR a report picked on the map (selId, shares the `live-…` id space)
  const [tapId, setTapId] = React.useState(null);
  const selectedId = tapId || selId;
  const onMyMap = reports.filter((r) => window.isOfficial(r) || r.onMap).length;
  return (
    <ScreenShell theme={theme} title="Общност" active="community" go={go}>
      {/* stats */}
      <StatStrip items={[
        { n: '128', l: 'сигнала', accent: 'var(--brand)' },
        { n: '1 240', l: 'колоездачи' },
        { n: '42', l: 'опасни зони', accent: 'var(--danger)' },
      ]} />

      {/* contribute CTA */}
      <button onClick={() => go('contribute')} className="tap" style={{
        margin: '0 16px 16px', width: 'calc(100% - 32px)', cursor: 'pointer', textAlign: 'left',
        borderRadius: 18, padding: '14px 15px', border: 'none', color: 'var(--text)',
        background: 'color-mix(in oklch, var(--brand) 9%, var(--surface))', boxShadow: 'var(--shadow)',
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <span style={{ width: 42, height: 42, borderRadius: 12, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--brand)', color: '#fff' }}><IconPlus size={22} /></span>
        <span style={{ flex: 1 }}>
          <span style={{ display: 'block', fontSize: 15.5, fontWeight: 700 }}>Добави към картата</span>
          <span style={{ display: 'block', fontSize: 12.5, color: 'var(--muted)', fontWeight: 500 }}>Маркирай безопасна улица или опасен участък</span>
        </span>
        <IconChevR size={18} style={{ color: 'var(--faint)' }} />
      </button>

      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', padding: '14px 20px 6px' }}>
        <span style={{ fontSize: 12.5, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase', color: 'var(--faint)' }}>Скорошни сигнали</span>
        <span style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--brand)' }}>{onMyMap} на моята карта</span>
      </div>
      <div style={{ fontSize: 12.5, color: 'var(--muted)', fontWeight: 500, padding: '0 20px 8px', lineHeight: 1.4 }}>Сигналите от всички колоездачи. Добави ги на своята карта и гласувай — след 20 гласа стават официални за всички.</div>
      {reports.map((r) => {
        const Ico = window[r.Icon];
        const official = window.isOfficial(r);
        const added = official || r.onMap;
        const isSel = r.id === selectedId;
        return (
          <Card key={r.id} onClick={() => setTapId((p) => p === r.id ? null : r.id)}
            style={isSel ? { boxShadow: '0 0 0 2px var(--brand), var(--shadow)' } : null}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <span style={{ width: 42, height: 42, borderRadius: 12, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: `color-mix(in oklch, ${lc(r.level)} 16%, transparent)`, color: lc(r.level) }}><Ico size={22} /></span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                  <span style={{ fontSize: 15.5, fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.cat}</span>
                  {official && <span style={{ flexShrink: 0, display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 10.5, fontWeight: 800, color: 'var(--safe)', background: 'color-mix(in oklch, var(--safe) 15%, transparent)', borderRadius: 999, padding: '2px 7px' }}><IconCheck size={11} sw={3} />Официален</span>}
                </div>
                <div style={{ fontSize: 13, color: 'var(--muted)', fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.loc} · {r.ago} · {r.author}</div>
              </div>
              <button onClick={(e) => { e.stopPropagation(); window.Comm.vote(r.id); }} className="tap" aria-label="Гласувай" style={{ flexShrink: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 1, padding: '4px 6px', borderRadius: 12, border: 'none', cursor: 'pointer', background: r.voted ? 'color-mix(in oklch, var(--safe) 14%, transparent)' : 'var(--surface-2)', color: r.voted ? 'var(--safe)' : 'var(--muted)', fontWeight: 800 }}>
                <svg width="19" height="19" viewBox="0 0 24 24" fill="none"><path d="M12 5l7 8h-4v6H9v-6H5l7-8z" fill={r.voted ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round"/></svg>
                <span style={{ fontSize: 12 }}>{r.votes}</span>
              </button>
            </div>
            {!official && (
              <button onClick={(e) => { e.stopPropagation(); window.Comm.toggleMap(r.id); }} className="tap" style={{
                marginTop: 11, width: '100%', height: 38, borderRadius: 12, cursor: 'pointer', fontSize: 13.5, fontWeight: 700,
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
                border: added ? '1px solid transparent' : '1px solid var(--hairline)',
                background: added ? 'color-mix(in oklch, var(--brand) 12%, transparent)' : 'var(--surface)',
                color: added ? 'var(--brand)' : 'var(--text)',
              }}>
                {added ? <><IconCheck size={16} sw={2.4} /> На моята карта</> : <><IconPlus size={16} /> Добави на моята карта</>}
              </button>
            )}
            {official && (
              <div style={{ marginTop: 11, fontSize: 12.5, color: 'var(--muted)', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6 }}>
                <IconCheck size={15} style={{ color: 'var(--safe)' }} /> Потвърден от общността — винаги на картата
              </div>
            )}
          </Card>
        );
      })}

      <SectionLabel>Топ участници</SectionLabel>
      {CONTRIB.map((c, i) => (
        <Card key={i}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <span style={{ width: 38, height: 38, borderRadius: 38, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 15, color: '#fff', background: 'linear-gradient(140deg, var(--brand), color-mix(in oklch, var(--brand) 55%, #000))' }}>{c.name[0]}</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 15.5, fontWeight: 700 }}>{c.name}</div>
              <div style={{ fontSize: 12.5, color: 'var(--brand)', fontWeight: 700 }}>{c.badge}</div>
            </div>
            <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--muted)' }}>{c.pts} т.</div>
          </div>
        </Card>
      ))}
    </ScreenShell>
  );
}

// ============================================================
// ПРОФИЛ (Profile)
// ============================================================
const P_STATS = [['128', 'км / месец'], ['24', 'пътувания'], ['9', 'доклада']];
const P_SETTINGS = [
  { Icon: 'IconShield', label: 'Предпочитания за маршрут', detail: 'Най-безопасен', to: 'onboarding' },
  { Icon: 'IconStar', label: 'Запазени места', detail: '4', to: 'saved' },
  { Icon: 'IconBike', label: 'Моят велосипед', detail: 'Градски', to: 'bike' },
  { Icon: 'IconBell', label: 'Известия', detail: '', to: 'notifications' },
];

function ProfileScreen({ theme, go, lang, onToggleLang, themeName, setTheme }) {
  const { IconChevR, IconLayers, IconLogout, IconSound, IconUser, IconMail, VSwitch } = window;
  const voice = window.useVoicePref ? window.useVoicePref() : true;
  const setVoice = (v) => { if (window.VoicePref) window.VoicePref.set(v); };
  const prefs = window.usePrefs();
  const saved = window.useSaved();
  const user = window.useUser();
  const name = window.vrDisplayName(user) || 'Гост';
  const initials = window.vrInitials(name);
  const subtitle = user ? 'София · Колоездач' : 'Влезте в профила си';
  const logout = async () => { if (window.VR_DB && window.VR_DB.enabled) await window.VR_DB.signOut(); if (window.UserStore) window.UserStore.set(null); go('auth'); };
  const settings = [
    { Icon: 'IconShield', label: 'Предпочитания за маршрут', detail: window.STYLE_LABEL[prefs.style], to: 'routeprefs' },
    { Icon: 'IconStar', label: 'Запазени места', detail: String(saved.length), to: 'saved' },
    { Icon: 'IconBike', label: 'Моят велосипед', detail: 'Градски', to: 'bike' },
    { Icon: 'IconBell', label: 'Известия', detail: '', to: 'notifications' },
  ];
  // password change only for a signed-in account
  if (user && window.VR_DB && window.VR_DB.enabled) {
    settings.push({ Icon: 'IconLock', label: 'Смяна на парола', detail: '', to: 'changepass' });
  }
  return (
    <ScreenShell theme={theme} title="Профил" active="profile" go={go}>
      {/* identity */}
      <Card style={{ margin: '4px 16px 14px', padding: '16px 18px' }} onClick={user ? undefined : () => go('auth')}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, cursor: user ? 'default' : 'pointer' }}>
          <span style={{ width: 56, height: 56, borderRadius: 56, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 20, color: '#fff', background: 'linear-gradient(140deg, var(--brand), color-mix(in oklch, var(--brand) 55%, #000))' }}>{user ? initials : <IconUser size={26} />}</span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 18.5, fontWeight: 800, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{name}</div>
            <div style={{ fontSize: 13.5, color: 'var(--muted)', fontWeight: 600, marginTop: 2 }}>{subtitle}</div>
          </div>
          {!user && <IconChevR size={20} style={{ color: 'var(--faint)' }} />}
        </div>
        <div style={{ marginTop: 16, paddingTop: 16, borderTop: '0.5px solid var(--hairline)' }}>
          <StatStrip bare items={[
            { n: '128', l: 'км / месец' },
            { n: '24', l: 'пътувания' },
            { n: '9', l: 'доклада', accent: 'var(--brand)' },
          ]} />
        </div>
      </Card>

      {/* premium */}
      <div onClick={() => go('premium')} className="tap" style={{ margin: '0 16px 16px', borderRadius: 20, padding: '16px 18px', color: '#fff', cursor: 'pointer', background: 'linear-gradient(135deg, oklch(0.55 0.13 250), oklch(0.5 0.15 285))', boxShadow: '0 10px 26px oklch(0.5 0.13 260 / 0.4)' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 18, fontWeight: 800 }}>Veloroute+</div>
            <div style={{ fontSize: 13, opacity: 0.85, fontWeight: 500, marginTop: 2 }}>Офлайн карти · анализи · история</div>
          </div>
          <IconLayers size={30} style={{ opacity: 0.9 }} />
        </div>
        <div className="tap" style={{ marginTop: 14, width: '100%', height: 44, borderRadius: 13, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(255,255,255,0.95)', color: 'oklch(0.5 0.15 270)', fontSize: 15, fontWeight: 800 }}>Опитай безплатно</div>
      </div>

      {/* settings list */}
      <div style={{ background: 'var(--surface)', borderRadius: 18, margin: '0 16px', boxShadow: 'var(--shadow)', overflow: 'hidden' }}>
        {settings.map((s, i) => {
          const Ico = window[s.Icon];
          return (
            <div key={i} onClick={() => s.to && go(s.to)} className="tap" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 15px', cursor: 'pointer', borderTop: i ? '0.5px solid var(--hairline)' : 'none' }}>
              <span style={{ width: 32, height: 32, borderRadius: 9, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--surface-2)', color: 'var(--muted)' }}><Ico size={19} /></span>
              <span style={{ flex: 1, fontSize: 15.5, fontWeight: 600 }}>{s.label}</span>
              {s.detail && <span style={{ fontSize: 14, color: 'var(--faint)', fontWeight: 600 }}>{s.detail}</span>}
              <IconChevR size={17} style={{ color: 'var(--faint)' }} />
            </div>
          );
        })}
        {/* theme (light / dark) */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 15px', borderTop: '0.5px solid var(--hairline)' }}>
          <span style={{ width: 32, height: 32, borderRadius: 9, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--surface-2)', color: 'var(--muted)' }}>
            <svg width="19" height="19" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" strokeWidth="1.8"/><path d="M12 3a9 9 0 000 18z" fill="currentColor"/></svg>
          </span>
          <span style={{ flex: 1, fontSize: 15.5, fontWeight: 600 }}>Тема</span>
          <div style={{ display: 'flex', gap: 3, padding: 3, borderRadius: 11, background: 'var(--surface-2)' }}>
            {[['Светла', 'Светла'], ['Тъмна', 'Тъмна']].map(([val, label]) => {
              const on = themeName === val;
              return (
                <button key={val} onClick={() => setTheme && setTheme(val)} className="tap" style={{ height: 30, padding: '0 13px', border: 'none', borderRadius: 8, cursor: 'pointer', fontSize: 13, fontWeight: 700, background: on ? 'var(--surface)' : 'transparent', color: on ? 'var(--brand)' : 'var(--muted)', boxShadow: on ? 'var(--shadow)' : 'none' }}>{label}</button>
              );
            })}
          </div>
        </div>
        {/* voice navigation toggle */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 15px', borderTop: '0.5px solid var(--hairline)' }}>
          <span style={{ width: 32, height: 32, borderRadius: 9, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--surface-2)', color: 'var(--muted)' }}><IconSound size={19} /></span>
          <span style={{ flex: 1, fontSize: 15.5, fontWeight: 600 }}>Гласова навигация</span>
          <VSwitch on={voice} onChange={setVoice} />
        </div>
        {/* language */}
        <div onClick={() => go('language')} className="tap" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 15px', cursor: 'pointer', borderTop: '0.5px solid var(--hairline)' }}>
          <span style={{ width: 32, height: 32, borderRadius: 9, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--surface-2)', color: 'var(--brand)', fontSize: 12, fontWeight: 800 }}>{lang === 'en' ? 'EN' : 'БГ'}</span>
          <span style={{ flex: 1, fontSize: 15.5, fontWeight: 600 }}>Език</span>
          <span style={{ fontSize: 14, color: 'var(--faint)', fontWeight: 600 }}>{lang === 'en' ? 'English' : 'Български'}</span>
          <IconChevR size={17} style={{ color: 'var(--faint)' }} />
        </div>
        {/* feedback — opens the mail client with a pre-filled subject (Phase 2 Ship & Learn loop) */}
        <a href="mailto:enikolova@theoremus.com?subject=VeloRoute%20—%20обратна%20връзка" className="tap" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 15px', textDecoration: 'none', color: 'inherit', borderTop: '0.5px solid var(--hairline)' }}>
          <span style={{ width: 32, height: 32, borderRadius: 9, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--surface-2)', color: 'var(--brand)' }}>{IconMail ? <IconMail size={19} /> : null}</span>
          <span style={{ flex: 1, fontSize: 15.5, fontWeight: 600 }}>Обратна връзка</span>
          <IconChevR size={17} style={{ color: 'var(--faint)' }} />
        </a>
      </div>

      <button onClick={user ? logout : () => go('auth')} className="tap" style={{
        margin: '14px 16px 0', width: 'calc(100% - 32px)', cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9,
        height: 50, borderRadius: 16, border: 'none', background: 'var(--surface)',
        boxShadow: 'var(--shadow)', color: 'var(--danger)', fontSize: 15.5, fontWeight: 700,
      }}><IconLogout size={20} /> {user ? 'Изход' : 'Вход'}</button>
    </ScreenShell>
  );
}

Object.assign(window, { RoutesScreen, CommunityScreen, ProfileScreen });
