// Admin screens for Gym 24/7. Desktop-first layouts inside a browser frame.

const { useState: aUseState, useEffect: aUseEffect, useMemo: aUseMemo } = React;

// ─────────────────────────────────────────────────────────────
// ADMIN SHELL — sidebar + main
// ─────────────────────────────────────────────────────────────
function AdminShell({ children }) {
  const { route, go } = useRouter();
  const items = [
    { id: 'admin',           label: 'Dashboard',  icon: 'dashboard' },
    { id: 'admin-members',   label: 'Členovia',   icon: 'users' },
    { id: 'admin-passes',    label: 'Permanentky',icon: 'card', stub: true },
    { id: 'admin-logs',      label: 'Vstupy',     icon: 'log' },
    { id: 'admin-door-qr',   label: 'QR poster',  icon: 'door' },
    { id: 'admin-settings',  label: 'Nastavenia', icon: 'settings' },
  ];
  return (
    <div className="admin-shell">
      <aside className="admin-side">
        <div className="brand">
          <div className="dot" />
          Gym 24/7
        </div>
        {items.map(it => {
          const active = route === it.id || (it.id === 'admin-members' && route === 'admin-member-detail');
          return (
            <div key={it.id} className={'nav-item ' + (active ? 'active' : '')} onClick={() => go(it.stub ? 'admin-stub' : it.id, { stubName: it.label })}>
              <Icon name={it.icon} size={18} color={active ? 'var(--red-soft)' : 'var(--text-secondary)'} />
              <span>{it.label}</span>
            </div>
          );
        })}
        <div className="footer">
          <div className="avatar">JM</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 600 }}>Jozef Majiteľ</div>
            <div style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>owner@gym247.sk</div>
          </div>
          <button onClick={() => go('landing')} style={{ background: 'transparent', border: 'none', color: 'var(--text-tertiary)' }}>
            <Icon name="logout" size={16} color="currentColor" />
          </button>
        </div>
      </aside>
      <main className="admin-main">{children}</main>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// ADMIN DASHBOARD
// ─────────────────────────────────────────────────────────────
function ScreenAdminDashboard() {
  return (
    <AdminShell>
      <AdminDashContent />
    </AdminShell>
  );
}

function AdminDashContent() {
  const [range, setRange] = aUseState('30');
  const [stream, setStream] = aUseState(MOCK_ADMIN_RECENT_VISITS);
  const toast = useToast();

  // Fake live feed: prepend a new row every 12s (slightly faster than spec for demo)
  aUseEffect(() => {
    const t = setInterval(() => {
      const fresh = { ...MOCK_LIVE_STREAM_POOL[Math.floor(Math.random() * MOCK_LIVE_STREAM_POOL.length)], timeAgo: 'práve teraz', fresh: true };
      setStream(s => [fresh, ...s.slice(0, 11)].map((x, i) => i === 0 ? x : { ...x, fresh: false }));
    }, 12000);
    return () => clearInterval(t);
  }, []);

  const chartData = range === '7' ? MOCK_ADMIN_CHART_7 : range === '90' ? MOCK_ADMIN_CHART_90 : MOCK_ADMIN_CHART_30;

  return (
    <>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 22 }}>
        <h1 className="admin-h1">Prehľad · streda 20. máj</h1>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="btn-outline" style={{ padding: '8px 14px', fontSize: 13 }}>Exportovať .csv</button>
          <button className="btn-red" style={{ padding: '8px 14px', fontSize: 13 }} onClick={() => toast('Faktúra vygenerovaná')}>+ Nová permanentka</button>
        </div>
      </div>

      <div className="metric-grid" style={{ marginBottom: 24 }}>
        <MetricBox label="Aktívni členovia" value={MOCK_ADMIN_METRICS.activeMembers} delta="+8" icon="users" />
        <MetricBox label="Vstupy dnes" value={MOCK_ADMIN_METRICS.visitsToday} delta="+12 %" icon="ticket" />
        <MetricBox label="Príjem (máj)" value={MOCK_ADMIN_METRICS.revenueThisMonth} suffix=" €" delta="+340 €" icon="card" />
        <MetricBox label="Končí tento týždeň" value={MOCK_ADMIN_METRICS.expiringThisWeek} red icon="bell" />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.8fr', gap: 18, marginBottom: 22 }}>
        <LiveOccupancyCard />
        <div className="card" style={{ padding: 22 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
            <h2 className="admin-h2">Obsadenosť · posledné 4 týždne</h2>
            <span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>priemer ľudí v každú hodinu</span>
          </div>
          <WeekHeatmap cellSize={18} gap={3} />
        </div>
      </div>

      <div className="card" style={{ padding: 22, marginBottom: 22 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
          <h2 className="admin-h2">Vstupy za posledných {range} dní</h2>
          <SegTabs full={false} value={range} onChange={setRange} options={[
            { id: '7',  label: '7 dní' },
            { id: '30', label: '30 dní' },
            { id: '90', label: '90 dní' },
          ]} />
        </div>
        <LineChart data={chartData} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 18 }}>
        <div className="card" style={{ padding: 22 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>
            <h2 className="admin-h2">Aktuálne vstupy</h2>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--text-tertiary)' }}>
              <div style={{ width: 7, height: 7, borderRadius: '50%', background: '#22C55E', animation: 'pulse 2s ease-out infinite' }} />
              live
            </div>
          </div>
          <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginBottom: 14 }}>Nový vstup sa pridá automaticky.</div>
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {stream.slice(0, 8).map((v, i) => (
              <div key={i + v.name + v.timeAgo} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '10px 0', borderBottom: i === 7 ? 'none' : '1px solid var(--border)',
                animation: v.fresh ? 'slideDown .35s ease-out' : 'none',
                background: v.fresh ? 'rgba(34,197,94,0.06)' : 'transparent',
                marginLeft: -8, paddingLeft: 8, borderRadius: v.fresh ? 8 : 0,
                transition: 'background 1.5s',
              }}>
                <Avatar initials={v.initials} size={32} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{v.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>pred {v.timeAgo}</div>
                </div>
                <div style={{ width: 28, height: 28, borderRadius: 7, background: 'var(--red-faded)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Icon name={v.method} size={14} color="var(--red-soft)" />
                </div>
                <div className="pill-green" style={{ fontSize: 10 }}>povolený</div>
              </div>
            ))}
          </div>
        </div>

        <div className="card" style={{ padding: 22 }}>
          <h2 className="admin-h2" style={{ marginBottom: 4 }}>Permanentky končia</h2>
          <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginBottom: 14 }}>Pošli upomienku jedným klikom.</div>
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {MOCK_ADMIN_EXPIRING.map((m, i) => {
              const isRed = m.days <= 2;
              return (
                <div key={m.name} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: '10px 0', borderBottom: i === MOCK_ADMIN_EXPIRING.length - 1 ? 'none' : '1px solid var(--border)',
                }}>
                  <Avatar initials={m.initials} size={32} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{m.name}</div>
                    <div style={{ fontSize: 11, color: isRed ? 'var(--red-soft)' : '#F59E0B', fontWeight: 600 }} className="mono">
                      {m.days === 1 ? 'končí zajtra' : `končí o ${m.days} dní`}
                    </div>
                  </div>
                  <button className="btn-outline" style={{ padding: '6px 12px', fontSize: 12 }} onClick={() => toast(`Upomienka pre ${m.name.split(' ')[0]} odoslaná`)}>
                    Pošli
                  </button>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </>
  );
}

function MetricBox({ label, value, suffix = '', delta, red, icon }) {
  return (
    <div className="card" style={{ padding: 18, position: 'relative' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
        <div style={{ fontSize: 11, color: 'var(--text-tertiary)', letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>{label}</div>
        <div style={{ width: 26, height: 26, borderRadius: 7, background: 'var(--bg-tertiary)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name={icon} size={14} color="var(--text-secondary)" />
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <div>
          <CountUp to={value} className="mono" style={{ fontSize: 28, fontWeight: 600, color: red ? 'var(--red-soft)' : '#fff', letterSpacing: '-0.02em' }} />
          {suffix && <span className="mono" style={{ fontSize: 18, color: red ? 'var(--red-soft)' : 'var(--text-secondary)' }}>{suffix}</span>}
        </div>
        {delta && (
          <div style={{ fontSize: 11, color: red ? 'var(--red-soft)' : '#22C55E', fontWeight: 600 }} className="mono">{delta}</div>
        )}
      </div>
    </div>
  );
}

function LineChart({ data, height = 180 }) {
  const w = 1000;
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = max - min || 1;
  const step = w / (data.length - 1);
  const yOf = v => height - 20 - ((v - min) / range) * (height - 40);
  const xOf = i => i * step;
  const path = data.map((v, i) => `${i === 0 ? 'M' : 'L'} ${xOf(i)} ${yOf(v)}`).join(' ');
  const area = `${path} L ${xOf(data.length - 1)} ${height} L 0 ${height} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${height}`} preserveAspectRatio="none" style={{ width: '100%', height }}>
      {/* grid */}
      {[0, 0.25, 0.5, 0.75, 1].map((t, i) => (
        <line key={i} x1={0} y1={height - 20 - t * (height - 40)} x2={w} y2={height - 20 - t * (height - 40)} stroke="#2A2A2A" strokeWidth={1} />
      ))}
      <defs>
        <linearGradient id="redfade" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#E10600" stopOpacity="0.25" />
          <stop offset="100%" stopColor="#E10600" stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={area} fill="url(#redfade)" />
      <path d={path} fill="none" stroke="#E10600" strokeWidth={2.5} strokeLinejoin="round" strokeLinecap="round" />
      {data.map((v, i) => (
        <circle key={i} cx={xOf(i)} cy={yOf(v)} r={2.5} fill={i === data.length - 1 ? '#fff' : '#E10600'} />
      ))}
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// ADMIN MEMBERS list
// ─────────────────────────────────────────────────────────────
function ScreenAdminMembers() {
  const [q, setQ] = aUseState('');
  const [filter, setFilter] = aUseState('all');
  const { go } = useRouter();

  const filtered = aUseMemo(() => {
    return MOCK_ADMIN_MEMBERS.filter(m => {
      if (q && !m.name.toLowerCase().includes(q.toLowerCase())) return false;
      if (filter !== 'all' && m.status !== filter) return false;
      return true;
    });
  }, [q, filter]);

  const statusPill = (s) =>
    s === 'active' ? <span className="pill-green">aktívna</span> :
    s === 'expired' ? <span className="pill-amber">expirovaná</span> :
    <span className="pill-gray">blokovaná</span>;

  return (
    <AdminShell>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
        <h1 className="admin-h1">Členovia</h1>
        <button className="btn-red" style={{ padding: '8px 14px', fontSize: 13 }}>+ Pridať člena</button>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
        <div style={{ flex: 1, position: 'relative' }}>
          <Icon name="search" size={16} color="var(--text-tertiary)" style={{ position: 'absolute', top: 11, left: 12 }} />
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Hľadať podľa mena..." style={{
            width: '100%', background: 'var(--bg-secondary)', border: '1px solid var(--border)',
            borderRadius: 8, padding: '10px 14px 10px 36px', color: '#fff', fontSize: 13, outline: 'none',
          }} />
        </div>
        <SegTabs full={false} value={filter} onChange={setFilter} options={[
          { id: 'all',     label: 'Všetky' },
          { id: 'active',  label: 'Aktívne' },
          { id: 'expired', label: 'Expirované' },
          { id: 'blocked', label: 'Blokované' },
        ]} />
      </div>

      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <table className="table">
          <thead>
            <tr>
              <th style={{ width: 50 }}></th>
              <th>Meno</th>
              <th>Telefón</th>
              <th>Permanentka</th>
              <th>Stav</th>
              <th>Posledný vstup</th>
              <th style={{ textAlign: 'right' }}>Spolu</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(m => (
              <tr key={m.id} onClick={() => go('admin-member-detail', { id: m.id })} style={{ cursor: 'pointer' }}>
                <td><Avatar initials={m.initials} size={28} /></td>
                <td style={{ fontWeight: 500 }}>{m.name}</td>
                <td className="mono" style={{ color: 'var(--text-secondary)', fontSize: 12 }}>{m.phone}</td>
                <td>{m.membership}</td>
                <td>{statusPill(m.status)}</td>
                <td style={{ color: 'var(--text-secondary)' }}>{m.lastVisit}</td>
                <td className="mono" style={{ textAlign: 'right', fontWeight: 600 }}>{m.total}</td>
              </tr>
            ))}
          </tbody>
        </table>
        {filtered.length === 0 && (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-tertiary)', fontSize: 13 }}>Žiadny člen nenájdený.</div>
        )}
      </div>
      <div style={{ marginTop: 12, fontSize: 12, color: 'var(--text-tertiary)' }}>{filtered.length} z {MOCK_ADMIN_MEMBERS.length}</div>
    </AdminShell>
  );
}

// ─────────────────────────────────────────────────────────────
// ADMIN MEMBER DETAIL
// ─────────────────────────────────────────────────────────────
function ScreenAdminMemberDetail() {
  const { params, go } = useRouter();
  const toast = useToast();
  const member = MOCK_ADMIN_MEMBERS.find(m => m.id === params.id) || MOCK_ADMIN_MEMBERS[14];
  const [tab, setTab] = aUseState('passes');
  const [doorOpen, setDoorOpen] = aUseState(false);
  const [note, setNote] = aUseState(() => {
    try { return localStorage.getItem('note-' + member.id) || ''; } catch (e) { return ''; }
  });

  aUseEffect(() => {
    try { localStorage.setItem('note-' + member.id, note); } catch (e) {}
  }, [note, member.id]);

  return (
    <AdminShell>
      <button onClick={() => go('admin-members')} className="btn-ghost" style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginBottom: 14, marginLeft: -10 }}>
        <Icon name="back" size={14} color="currentColor" /> Späť na členov
      </button>

      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 22 }}>
        <div style={{ display: 'flex', gap: 18, alignItems: 'center' }}>
          <Avatar initials={member.initials} size={64} red />
          <div>
            <h1 className="admin-h1" style={{ marginBottom: 4 }}>{member.name}</h1>
            <div style={{ display: 'flex', gap: 14, alignItems: 'center', color: 'var(--text-secondary)', fontSize: 13 }}>
              <span className="mono">{member.phone}</span>
              <span>·</span>
              <span>člen od {member.joinedAt}</span>
              {member.status === 'active' ? <span className="pill-green">aktívna</span> :
                member.status === 'expired' ? <span className="pill-amber">expirovaná</span> :
                <span className="pill-gray">blokovaná</span>}
            </div>
          </div>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 8, marginBottom: 22 }}>
        <button className="btn-outline" style={{ padding: '10px 16px', fontSize: 13 }} onClick={() => toast('Permanentka pridaná')}>+ Pridať permanentku</button>
        <button className="btn-red" style={{ padding: '10px 16px', fontSize: 13 }} onClick={() => setDoorOpen(true)}>Otvoriť dvere na 5 s</button>
        <button className="btn-outline" style={{ padding: '10px 16px', fontSize: 13 }} onClick={() => toast('Člen zablokovaný', { icon: 'check' })}>Zablokovať</button>
      </div>

      <div className="card" style={{ padding: 22 }}>
        <div style={{ display: 'flex', gap: 4, marginBottom: 18, borderBottom: '1px solid var(--border)' }}>
          {[
            { id: 'passes', label: 'Permanentky' },
            { id: 'visits', label: 'Vstupy' },
            { id: 'notes',  label: 'Poznámky' },
          ].map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              background: 'transparent', border: 'none',
              color: tab === t.id ? '#fff' : 'var(--text-tertiary)',
              fontSize: 13, fontWeight: 500,
              padding: '10px 14px', borderBottom: tab === t.id ? '2px solid var(--red-primary)' : '2px solid transparent',
              marginBottom: -1,
            }}>{t.label}</button>
          ))}
        </div>

        {tab === 'passes' && (
          <table className="table">
            <thead>
              <tr><th>Typ</th><th>Zakúpené</th><th>Platné do</th><th>Cena</th><th>Stav</th></tr>
            </thead>
            <tbody>
              <tr><td>Mesačná</td><td>15. máj 2026</td><td>14. jún 2026</td><td className="mono">35 €</td><td><span className="pill-green">aktívna</span></td></tr>
              <tr><td>Mesačná</td><td>10. apr. 2026</td><td>10. máj 2026</td><td className="mono">35 €</td><td><span className="pill-gray">ukončená</span></td></tr>
              <tr><td>Mesačná</td><td>10. mar. 2026</td><td>10. apr. 2026</td><td className="mono">35 €</td><td><span className="pill-gray">ukončená</span></td></tr>
              <tr><td>10× vstup</td><td>15. sept. 2025</td><td>15. mar. 2026</td><td className="mono">42 €</td><td><span className="pill-gray">vyčerpaná</span></td></tr>
            </tbody>
          </table>
        )}

        {tab === 'visits' && (
          <table className="table">
            <thead>
              <tr><th>Dátum</th><th>Čas</th><th>Metóda</th><th>Stav</th></tr>
            </thead>
            <tbody>
              {MOCK_RECENT_VISITS.map(v => {
                const d = new Date(v.date);
                return (
                  <tr key={v.id}>
                    <td>{d.toLocaleDateString('sk-SK', { day: 'numeric', month: 'long', year: 'numeric' })}</td>
                    <td className="mono">{d.toLocaleTimeString('sk-SK', { hour: '2-digit', minute: '2-digit' })}</td>
                    <td><span style={{ textTransform: 'uppercase', fontSize: 11, letterSpacing: '0.05em', color: 'var(--text-secondary)' }}>{v.method}</span></td>
                    <td><span className="pill-green">povolený</span></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}

        {tab === 'notes' && (
          <div>
            <textarea
              value={note}
              onChange={e => setNote(e.target.value)}
              placeholder="Pridaj poznámku o členovi. Ulozí sa automaticky."
              style={{
                width: '100%', minHeight: 160, padding: 14,
                background: 'var(--bg-primary)', border: '1px solid var(--border)',
                borderRadius: 10, color: '#fff', fontSize: 13, fontFamily: 'inherit',
                resize: 'vertical', outline: 'none',
              }}
            />
            <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 8 }}>
              {note.length} znakov · uložené lokálne
            </div>
          </div>
        )}
      </div>

      <Modal open={doorOpen} onClose={() => setDoorOpen(false)}>
        <div style={{ textAlign: 'center', padding: '10px 0' }}>
          <BigCheck size={72} color="#22C55E" />
          <div style={{ fontSize: 18, fontWeight: 600, margin: '20px 0 6px' }}>Brána otvorená</div>
          <div style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 18 }}>Zostáva 4 s</div>
          <button className="btn-outline" style={{ width: '100%' }} onClick={() => setDoorOpen(false)}>Zatvoriť</button>
        </div>
      </Modal>
    </AdminShell>
  );
}

// ─────────────────────────────────────────────────────────────
// ADMIN ACCESS LOGS — live feed
// ─────────────────────────────────────────────────────────────
function ScreenAdminLogs() {
  const [stream, setStream] = aUseState(() => {
    return MOCK_ADMIN_RECENT_VISITS.map((v, i) => ({
      ...v,
      ts: new Date(Date.now() - i * 7 * 60 * 1000),
    }));
  });
  aUseEffect(() => {
    const t = setInterval(() => {
      const pool = MOCK_LIVE_STREAM_POOL[Math.floor(Math.random() * MOCK_LIVE_STREAM_POOL.length)];
      setStream(s => [{ ...pool, ts: new Date(), fresh: true }, ...s.slice(0, 24)].map((x, i) => i === 0 ? x : { ...x, fresh: false }));
    }, 8000);
    return () => clearInterval(t);
  }, []);
  return (
    <AdminShell>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
        <h1 className="admin-h1">Vstupy · live</h1>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--text-secondary)' }}>
          <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#22C55E', animation: 'pulse 2s ease-out infinite' }} />
          aktualizuje sa automaticky
        </div>
      </div>

      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <table className="table">
          <thead>
            <tr>
              <th style={{ width: 50 }}></th>
              <th>Člen</th>
              <th>Čas</th>
              <th>Metóda</th>
              <th>Výsledok</th>
            </tr>
          </thead>
          <tbody>
            {stream.map((v, i) => (
              <tr key={i + '_' + v.ts.getTime()} style={{
                animation: v.fresh ? 'slideDown .35s ease-out' : 'none',
                background: v.fresh ? 'rgba(34,197,94,0.04)' : 'transparent',
              }}>
                <td><Avatar initials={v.initials} size={28} /></td>
                <td style={{ fontWeight: 500 }}>{v.name}</td>
                <td className="mono" style={{ color: 'var(--text-secondary)' }}>{v.ts.toLocaleTimeString('sk-SK', { hour: '2-digit', minute: '2-digit', second: '2-digit' })}</td>
                <td><span style={{ textTransform: 'uppercase', fontSize: 11, letterSpacing: '0.05em', color: 'var(--text-secondary)' }}>{v.method}</span></td>
                <td><span className="pill-green">povolený</span></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </AdminShell>
  );
}

// ─────────────────────────────────────────────────────────────
// ADMIN DOOR QR poster
// ─────────────────────────────────────────────────────────────
function ScreenAdminDoorQR() {
  const toast = useToast();
  const [seed, setSeed] = aUseState(() => Math.random().toString(36).slice(2, 14));
  return (
    <AdminShell>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
        <h1 className="admin-h1">QR poster pre dvere</h1>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="btn-outline" style={{ padding: '8px 14px', fontSize: 13, display: 'inline-flex', alignItems: 'center', gap: 6 }} onClick={() => { setSeed(Math.random().toString(36).slice(2, 14)); toast('QR rotovaný'); }}>
            <Icon name="rotate" size={14} color="currentColor" /> Rotovať
          </button>
          <button className="btn-red" style={{ padding: '8px 14px', fontSize: 13, display: 'inline-flex', alignItems: 'center', gap: 6 }} onClick={() => toast('Otvára sa náhľad tlače...', { icon: 'printer' })}>
            <Icon name="printer" size={14} color="#fff" /> Vytlačiť
          </button>
        </div>
      </div>

      <div style={{
        background: '#fff', color: '#0A0A0A', padding: 40, borderRadius: 12,
        maxWidth: 560, margin: '0 auto', textAlign: 'center',
        border: '1px solid var(--border)',
        boxShadow: '0 30px 80px rgba(0,0,0,0.45)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, marginBottom: 4 }}>
          <div style={{ width: 18, height: 18, background: '#E10600', borderRadius: 4 }} />
          <div style={{ fontSize: 24, fontWeight: 700, letterSpacing: '-0.01em' }}>Gym 24/7</div>
        </div>
        <div style={{ fontSize: 12, color: '#6B6B6B', letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 28 }}>Poprad · Mnoheľova 3</div>

        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 28 }}>
          <FakeQR seed={seed} size={260} />
        </div>

        <div style={{ fontSize: 24, fontWeight: 600, marginBottom: 18, letterSpacing: '-0.015em' }}>Otvor dvere mobilom</div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, alignItems: 'flex-start', maxWidth: 380, margin: '0 auto', textAlign: 'left' }}>
          {[
            'Otvor appku Gym 24/7',
            'Klikni „Vstup" → „QR kód"',
            'Naskenuj tento kód',
          ].map((line, i) => (
            <div key={i} style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
              <div className="mono" style={{ width: 34, height: 34, borderRadius: '50%', background: '#0A0A0A', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 600, fontSize: 14 }}>{i + 1}</div>
              <div style={{ fontSize: 15 }}>{line}</div>
            </div>
          ))}
        </div>

        <div style={{ marginTop: 32, paddingTop: 18, borderTop: '1px solid #E5E5E5', fontSize: 11, color: '#9CA3AF', letterSpacing: '0.04em' }} className="mono">
          KÓD: {seed.toUpperCase()} · ROTUJE KAŽDÝCH 24 H
        </div>
      </div>
    </AdminShell>
  );
}

// SVG fake QR — deterministic dot grid from seed
function FakeQR({ seed, size = 240 }) {
  const N = 25;
  const cells = aUseMemo(() => {
    // hash seed to bits
    let h = 0;
    for (let i = 0; i < seed.length; i++) h = (h * 31 + seed.charCodeAt(i)) | 0;
    const bits = [];
    for (let i = 0; i < N * N; i++) {
      h = (h * 1103515245 + 12345) | 0;
      bits.push((h >>> 16) & 1);
    }
    return bits;
  }, [seed]);
  const c = size / N;
  // finder squares
  const isFinder = (x, y) =>
    (x < 7 && y < 7) || (x >= N - 7 && y < 7) || (x < 7 && y >= N - 7);
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ display: 'block' }}>
      <rect width={size} height={size} fill="#fff" />
      {/* finder pattern outer */}
      {[[0,0],[N-7,0],[0,N-7]].map(([fx, fy], i) => (
        <g key={i}>
          <rect x={fx*c} y={fy*c} width={7*c} height={7*c} fill="#0A0A0A" />
          <rect x={(fx+1)*c} y={(fy+1)*c} width={5*c} height={5*c} fill="#fff" />
          <rect x={(fx+2)*c} y={(fy+2)*c} width={3*c} height={3*c} fill="#0A0A0A" />
        </g>
      ))}
      {/* random data cells */}
      {cells.map((b, i) => {
        if (!b) return null;
        const x = i % N, y = Math.floor(i / N);
        if (isFinder(x, y)) return null;
        return <rect key={i} x={x*c+0.5} y={y*c+0.5} width={c-1} height={c-1} fill="#0A0A0A" />;
      })}
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// ADMIN SETTINGS — incl. Wrapped email preview
// ─────────────────────────────────────────────────────────────
function ScreenAdminSettings() {
  const [tab, setTab] = aUseState('basic');
  const toast = useToast();
  return (
    <AdminShell>
      <h1 className="admin-h1" style={{ marginBottom: 18 }}>Nastavenia</h1>

      <div style={{ display: 'flex', gap: 4, marginBottom: 22, borderBottom: '1px solid var(--border)' }}>
        {[
          { id: 'basic',     label: 'Základné' },
          { id: 'pricing',   label: 'Cenník' },
          { id: 'onboard',   label: 'Onboarding' },
          { id: 'emails',    label: 'Email šablóny' },
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            background: 'transparent', border: 'none',
            color: tab === t.id ? '#fff' : 'var(--text-tertiary)',
            fontSize: 14, fontWeight: 500,
            padding: '12px 16px', borderBottom: tab === t.id ? '2px solid var(--red-primary)' : '2px solid transparent',
            marginBottom: -1,
          }}>{t.label}</button>
        ))}
      </div>

      {tab === 'basic' && (
        <div className="card" style={{ padding: 24, maxWidth: 640 }}>
          <h2 className="admin-h2" style={{ marginBottom: 18 }}>Informácie o gyme</h2>
          {[
            { label: 'Názov', value: 'Gym 24/7 Poprad' },
            { label: 'Adresa', value: 'Mnoheľova 3, 058 01 Poprad' },
            { label: 'Telefón', value: '+421 905 000 000' },
            { label: 'Kontaktný email', value: 'info@gym247.sk' },
          ].map(f => (
            <div key={f.label} style={{ marginBottom: 14 }}>
              <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 6 }}>{f.label}</div>
              <input defaultValue={f.value} style={{
                width: '100%', background: 'var(--bg-primary)', border: '1px solid var(--border)',
                borderRadius: 8, padding: '10px 12px', color: '#fff', fontSize: 14, fontFamily: 'inherit', outline: 'none',
              }} />
            </div>
          ))}
          <button className="btn-red" style={{ marginTop: 10 }} onClick={() => toast('Nastavenia uložené')}>Uložiť</button>
        </div>
      )}

      {tab === 'pricing' && (
        <div className="card" style={{ padding: 24, maxWidth: 640 }}>
          <h2 className="admin-h2" style={{ marginBottom: 18 }}>Cenník</h2>
          {MOCK_PRICING.map(p => (
            <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 12 }}>
              <div className="mono" style={{ fontSize: 11, color: 'var(--red-soft)', fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', width: 180 }}>{p.type}</div>
              <input defaultValue={p.price} style={{
                flex: 1, background: 'var(--bg-primary)', border: '1px solid var(--border)',
                borderRadius: 8, padding: '10px 12px', color: '#fff', fontSize: 14, fontFamily: 'Geist Mono, monospace', outline: 'none',
                fontVariantNumeric: 'tabular-nums',
              }} />
              <span style={{ color: 'var(--text-secondary)' }}>€</span>
            </div>
          ))}
          <button className="btn-red" style={{ marginTop: 10 }} onClick={() => toast('Cenník uložený')}>Uložiť</button>
        </div>
      )}

      {tab === 'onboard' && (
        <div className="card" style={{ padding: 24, maxWidth: 640 }}>
          <h2 className="admin-h2" style={{ marginBottom: 18 }}>Onboarding nových členov</h2>
          <SettingsToggleRow label="Vyžadovať schválenie nových členov" desc="Nový člen čaká na manuálne schválenie predtým, než môže prísť." />
          <SettingsToggleRow label="Verifikácia telefónu" desc="Pošli SMS kód pri registrácii." defaultOn />
          <SettingsToggleRow label="Onboarding video" desc="Nový člen musí pozrieť 60-sekundové video o bezpečnosti." last />
        </div>
      )}

      {tab === 'emails' && <EmailTemplates />}
    </AdminShell>
  );
}

function SettingsToggleRow({ label, desc, defaultOn = false, last }) {
  const [on, setOn] = aUseState(defaultOn);
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 18, padding: '14px 0', borderBottom: last ? 'none' : '1px solid var(--border)' }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 14, fontWeight: 500 }}>{label}</div>
        <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginTop: 2 }}>{desc}</div>
      </div>
      <button onClick={() => setOn(o => !o)} style={{
        width: 42, height: 24, borderRadius: 999,
        background: on ? 'var(--red-primary)' : 'rgba(255,255,255,0.1)',
        border: 'none', position: 'relative', flexShrink: 0,
      }}>
        <div style={{
          position: 'absolute', top: 2, left: on ? 20 : 2,
          width: 20, height: 20, borderRadius: '50%', background: '#fff',
          transition: 'left .15s', boxShadow: '0 1px 3px rgba(0,0,0,0.3)',
        }} />
      </button>
    </div>
  );
}

function EmailTemplates() {
  const [pick, setPick] = aUseState('wrapped');
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '240px 1fr', gap: 24 }}>
      <div>
        {[
          { id: 'welcome',   label: 'Privítanie', desc: 'Po registrácii' },
          { id: 'reminder',  label: 'Pripomenutie', desc: '3 dni pred koncom' },
          { id: 'wrapped',   label: 'Mesačný Wrapped', desc: '1. v mesiaci' },
        ].map(t => (
          <button key={t.id} onClick={() => setPick(t.id)} style={{
            width: '100%', textAlign: 'left', padding: 14,
            background: pick === t.id ? 'var(--red-faded)' : 'var(--bg-secondary)',
            border: '1px solid ' + (pick === t.id ? 'var(--red-stronger)' : 'var(--border)'),
            borderRadius: 10, color: '#fff', marginBottom: 8, cursor: 'pointer',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
              <Icon name="mail" size={14} color={pick === t.id ? 'var(--red-soft)' : 'var(--text-secondary)'} />
              <span style={{ fontSize: 13, fontWeight: 600 }}>{t.label}</span>
            </div>
            <div style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>{t.desc}</div>
          </button>
        ))}
      </div>
      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ padding: '10px 16px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 12, color: 'var(--text-tertiary)' }}>
          <span>náhľad emailu</span>
          <span className="mono">no-reply@gym247.sk</span>
        </div>
        <div style={{ padding: 0, background: '#0A0A0A' }}>
          {pick === 'welcome' && <EmailWelcome />}
          {pick === 'reminder' && <EmailReminder />}
          {pick === 'wrapped' && <EmailWrapped />}
        </div>
      </div>
    </div>
  );
}

function EmailWelcome() {
  return (
    <div style={{ padding: 40, color: '#fff', textAlign: 'center', maxWidth: 560, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, marginBottom: 24 }}>
        <div style={{ width: 14, height: 14, background: '#E10600', borderRadius: 3 }} />
        <div style={{ fontSize: 16, fontWeight: 700 }}>Gym 24/7</div>
      </div>
      <h2 style={{ fontSize: 28, fontWeight: 600, margin: '0 0 14px', letterSpacing: '-0.02em' }}>Vitaj, Martin!</h2>
      <p style={{ fontSize: 15, lineHeight: 1.6, color: '#A1A1A1', maxWidth: 420, margin: '0 auto 28px' }}>
        Tvoj účet je pripravený. Stiahni si appku, vyber permanentku a poď trénovať. Prvý vstup ti dáme zadarmo.
      </p>
      <button className="btn-red">Otvoriť appku</button>
    </div>
  );
}

function EmailReminder() {
  return (
    <div style={{ padding: 40, color: '#fff', textAlign: 'center', maxWidth: 560, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, marginBottom: 24 }}>
        <div style={{ width: 14, height: 14, background: '#E10600', borderRadius: 3 }} />
        <div style={{ fontSize: 16, fontWeight: 700 }}>Gym 24/7</div>
      </div>
      <div className="pill-amber" style={{ marginBottom: 14 }}>končí o 3 dni</div>
      <h2 style={{ fontSize: 26, fontWeight: 600, margin: '0 0 12px', letterSpacing: '-0.02em' }}>Tvoja permanentka končí v sobotu</h2>
      <p style={{ fontSize: 14, color: '#A1A1A1', lineHeight: 1.6, maxWidth: 380, margin: '0 auto 24px' }}>
        Predĺž ju jedným klikom a pokračuj v tvojej 12-dňovej sérii.
      </p>
      <button className="btn-red">Predĺžiť za 35 €</button>
    </div>
  );
}

// ⭐ The showpiece email — make it gorgeous.
function EmailWrapped() {
  return (
    <div style={{
      padding: 0, color: '#fff',
      background: 'radial-gradient(circle at 30% 0%, rgba(225,6,0,0.35), transparent 50%), radial-gradient(circle at 80% 90%, rgba(225,6,0,0.18), transparent 55%), #0A0A0A',
      position: 'relative', overflow: 'hidden',
    }}>
      <div style={{ padding: '44px 40px', maxWidth: 560, margin: '0 auto' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 36 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, fontWeight: 700 }}>
            <div style={{ width: 12, height: 12, background: '#E10600', borderRadius: 3 }} />
            Gym 24/7
          </div>
          <div className="mono" style={{ fontSize: 11, color: '#A1A1A1', letterSpacing: '0.1em' }}>MÁJ 2026</div>
        </div>

        <h1 style={{ fontSize: 44, fontWeight: 600, margin: '0 0 12px', letterSpacing: '-0.03em', lineHeight: 1.02 }}>
          Tvoj mesiac<br/>v <span style={{ color: '#FF1A0F' }}>Gym 24/7</span>.
        </h1>
        <p style={{ fontSize: 14, color: '#A1A1A1', margin: '0 0 32px' }}>Tu je, čo si zvládol, Martin.</p>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 24 }}>
          <div style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid #2A2A2A', borderRadius: 16, padding: 22 }}>
            <div className="mono" style={{ fontSize: 56, fontWeight: 600, color: '#FF1A0F', letterSpacing: '-0.04em', lineHeight: 1 }}>14×</div>
            <div style={{ fontSize: 13, color: '#A1A1A1', marginTop: 8 }}>prešiel si dverami</div>
          </div>
          <div style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid #2A2A2A', borderRadius: 16, padding: 22 }}>
            <div className="mono" style={{ fontSize: 44, fontWeight: 600, letterSpacing: '-0.04em', lineHeight: 1.1 }}>23:15</div>
            <div style={{ fontSize: 13, color: '#A1A1A1', marginTop: 8 }}>najobľúbenejší čas</div>
          </div>
        </div>

        <div style={{
          background: 'linear-gradient(135deg, rgba(225,6,0,0.18), rgba(225,6,0,0.04))',
          border: '1px solid #4A0001', borderRadius: 16, padding: 24,
          display: 'flex', gap: 16, alignItems: 'center', marginBottom: 24,
        }}>
          <div style={{ width: 56, height: 56, borderRadius: 14, background: 'var(--red-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icon name="moon" size={28} color="#fff" />
          </div>
          <div>
            <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.01em', marginBottom: 4 }}>Patríš medzi Top 10% nočných sov.</div>
            <div style={{ fontSize: 13, color: '#A1A1A1' }}>Získavaš odznak <b style={{ color: '#FF1A0F' }}>Nočná sova</b> + 10 % zľavu na ďalší mesiac.</div>
          </div>
        </div>

        <div style={{ display: 'flex', gap: 12, fontSize: 12, color: '#A1A1A1', padding: '14px 0', borderTop: '1px solid #2A2A2A', borderBottom: '1px solid #2A2A2A', marginBottom: 24 }}>
          <Stat n="12" sub="dní séria" />
          <Stat n="6 h" sub="strávených v gyme" />
          <Stat n="+3" sub="vs. apríl" red />
        </div>

        <button className="btn-red" style={{ width: '100%' }}>Predĺžiť so zľavou 10 %</button>
        <div style={{ marginTop: 18, fontSize: 11, color: '#6B6B6B', textAlign: 'center' }}>
          Tento report dostávaš každý 1. v mesiaci. Môžeš ho vypnúť v profile.
        </div>
      </div>
    </div>
  );
}
function Stat({ n, sub, red }) {
  return (
    <div style={{ flex: 1 }}>
      <div className="mono" style={{ fontSize: 22, fontWeight: 600, color: red ? '#22C55E' : '#fff', letterSpacing: '-0.02em' }}>{n}</div>
      <div style={{ fontSize: 11, marginTop: 2 }}>{sub}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// ADMIN stub for not-built pages
// ─────────────────────────────────────────────────────────────
function ScreenAdminStub() {
  const { params, go } = useRouter();
  return (
    <AdminShell>
      <h1 className="admin-h1" style={{ marginBottom: 8 }}>{params.stubName || 'Stránka'}</h1>
      <p style={{ color: 'var(--text-secondary)', marginBottom: 24 }}>Táto sekcia ešte nie je súčasťou demo prototypu.</p>
      <button className="btn-outline" onClick={() => go('admin')}>Späť na dashboard</button>
    </AdminShell>
  );
}

Object.assign(window, {
  ScreenAdminDashboard, ScreenAdminMembers, ScreenAdminMemberDetail,
  ScreenAdminLogs, ScreenAdminDoorQR, ScreenAdminSettings, ScreenAdminStub,
});
