// ============================================
// MariusVPN — all screens
// Exposes: LoginScreen, DashboardScreen, SubscriptionScreen, PaymentsScreen,
//   DevicesScreen, TrafficScreen, ReferralScreen, HelpScreen
// ============================================

const { useState, useEffect, useRef, useCallback, useMemo } = React;
const {
  api, MOCK, Icon, FMT, PLATFORM_LABEL, PLATFORM_ICON,
  Logo, Card, Button, IconButton, Badge, Toggle, ProgressBar, Skeleton, Spinner,
  Field, Input, Select, CopyField,
  Modal, Sheet, useToast, ScreenHeader, KV,
} = window;

// ============================================
// LOGIN
// ============================================
const TG_BOT_USERNAME = 'marius_vpnbot';

function LoginScreen({ onLogin }) {
  const [code, setCode] = useState('');
  const [loading, setLoading] = useState(false);
  const [showLink, setShowLink] = useState(false);
  const widgetRef = useRef(null);
  const toast = useToast();

  const submit = async (e) => {
    e.preventDefault();
    let t = code.trim();
    if (!t) { toast.error('Вставьте ссылку или код из бота'); return; }
    // The bot sends a login LINK (…/cabinet/?token=XXXX). Accept either the
    // whole link or just the token.
    const m = t.match(/[?&]token=([^&\s]+)/);
    if (m) t = decodeURIComponent(m[1]);
    setLoading(true);
    try {
      await api('/login', { method: 'POST', body: { token: t } });
      toast.success('Вход выполнен');
      onLogin?.();
    } catch (err) {
      toast.error('Ссылка/код недействительны. Получите новые в боте.');
    } finally { setLoading(false); }
  };

  // Fallback: ask the bot to DM a one-time browser login link.
  const getLink = () => {
    if (MOCK) { onLogin?.(); return; }
    window.open(`https://t.me/${TG_BOT_USERNAME}?start=weblogin`, '_blank');
  };

  // Telegram Login Widget — official "Log in with Telegram" button (browser OAuth).
  useEffect(() => {
    if (MOCK) return;
    window.onTelegramAuth = async (user) => {
      try {
        const r = await fetch('/api/tg/cabinet-widget-auth', {
          method: 'POST', credentials: 'include',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(user),
        });
        if (!r.ok) throw new Error('widget auth failed');
        toast.success('Вход выполнен');
        onLogin?.();
      } catch (e) {
        toast.error('Не удалось войти. Возможно, этот Telegram ещё не регистрировался в боте.');
      }
    };
    const el = widgetRef.current;
    if (el && !el.querySelector('script')) {
      const s = document.createElement('script');
      s.async = true;
      s.src = 'https://telegram.org/js/telegram-widget.js?22';
      s.setAttribute('data-telegram-login', TG_BOT_USERNAME);
      s.setAttribute('data-size', 'large');
      s.setAttribute('data-radius', '12');
      s.setAttribute('data-onauth', 'onTelegramAuth(user)');
      s.setAttribute('data-request-access', 'write');
      el.appendChild(s);
    }
  }, []);

  // Try to auto-auth via Telegram WebApp initData if opened inside Telegram.
  useEffect(() => {
    const tgInitData = window.Telegram?.WebApp?.initData;
    if (!tgInitData) return;
    (async () => {
      try {
        const r = await fetch('/api/tg/cabinet-auth', {
          method: 'POST', credentials: 'include',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ init_data: tgInitData }),
        });
        if (r.ok) { onLogin?.(); }
      } catch (e) {}
    })();
  }, []);

  return (
    <div className="min-h-screen w-full grid place-items-center px-5 py-10 relative overflow-hidden">
      <div className="absolute -top-40 -right-40 w-[480px] h-[480px] rounded-full bg-m-accent/15 blur-3xl pointer-events-none" />
      <div className="absolute -bottom-40 -left-40 w-[480px] h-[480px] rounded-full bg-cyan-600/10 blur-3xl pointer-events-none" />

      <div className="w-full max-w-[400px] relative">
        <div className="flex justify-center mb-7">
          <Logo size={56} />
        </div>
        <h1 className="text-2xl text-center font-semibold text-m-text tracking-tight">Личный кабинет</h1>
        <p className="text-center text-m-mute text-sm mt-2 mb-8">
          Войдите через Telegram — в один клик, на любом устройстве.
        </p>

        <Card padding="p-6" className="slide-up">
          {/* Primary: official Telegram Login Widget button */}
          <div ref={widgetRef} className="flex justify-center min-h-[48px]" />

          <div className="flex items-center gap-3 my-5 text-[11px] uppercase tracking-widest text-m-dim">
            <div className="flex-1 h-px bg-white/5" />
            или
            <div className="flex-1 h-px bg-white/5" />
          </div>

          {/* Secondary: bot DMs a one-time browser link */}
          <Button
            variant="secondary"
            size="lg"
            fullWidth
            icon="telegram"
            onClick={getLink}
          >
            Получить ссылку в Telegram
          </Button>

          {/* Tertiary: paste a link manually */}
          <button
            type="button"
            onClick={() => setShowLink(v => !v)}
            className="w-full mt-4 text-[12px] text-m-dim hover:text-m-mute transition"
          >
            {showLink ? 'Скрыть ручной ввод' : 'У меня уже есть ссылка из бота'}
          </button>
          {showLink && (
            <form onSubmit={submit} className="space-y-3 mt-3">
              <Input
                type="text"
                placeholder="Вставьте ссылку из бота"
                value={code}
                onChange={(e) => setCode(e.target.value)}
                className="!text-sm font-mono"
              />
              <Button type="submit" variant="secondary" size="lg" fullWidth loading={loading} iconRight="arrowRight">
                Войти
              </Button>
            </form>
          )}
        </Card>

        <p className="text-center text-[11px] text-m-dim mt-6">
          Входя, вы соглашаетесь с условиями использования и политикой конфиденциальности.
        </p>
      </div>
    </div>
  );
}

// ============================================
// DASHBOARD
// ============================================
function DashboardScreen({ onRoute, refreshKey }) {
  const [me, setMe] = useState(null);
  const [traffic, setTraffic] = useState(null);
  const toast = useToast();

  useEffect(() => {
    let alive = true;
    Promise.all([api('/me'), api('/traffic')]).then(([m, t]) => {
      if (!alive) return;
      setMe(m); setTraffic(t);
    });
    return () => { alive = false; };
  }, [refreshKey]);

  if (!me || !traffic) return <DashboardSkeleton />;

  const s = me.subscription;
  const lim = me.limits;
  const bypass = traffic.bypass;
  const bypassPct = (bypass.used_gb / bypass.quota_gb) * 100;

  return (
    <div className="slide-up">
      <ScreenHeader
        title={`Привет, ${me.user.name.split(' ')[0]}`}
        subtitle="Управляйте подпиской, устройствами и трафиком"
      />

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">

        {/* Subscription status (hero) */}
        <Card className="lg:col-span-2 relative overflow-hidden" padding="p-5 md:p-6">
          <div className="absolute -top-20 -right-20 w-64 h-64 rounded-full bg-m-accent/10 blur-3xl pointer-events-none" />
          <div className="relative">
            <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3">
              <div className="min-w-0">
                <div className="text-[11px] uppercase tracking-widest text-m-dim mb-1">Подписка</div>
                <div className="flex items-center flex-wrap gap-2">
                  <span className="text-xl font-semibold text-m-text">{s.plan_name}</span>
                  {s.status === 'active' && <Badge tone="ok" icon="check">Активна</Badge>}
                  {s.status === 'expired' && <Badge tone="err">Истекла</Badge>}
                  {s.status === 'trial' && <Badge tone="gold">Триал</Badge>}
                </div>
              </div>
              <Button variant="primary" size="md" icon="zap" onClick={() => onRoute('subscription')}
                className="shrink-0 w-full sm:w-auto">
                Продлить
              </Button>
            </div>

            <div className="flex items-end gap-4 mt-6">
              <div className="text-[88px] md:text-[120px] leading-[0.85] font-light tracking-tighter text-m-text tabular-nums">
                {s.days_left}
              </div>
              <div className="pb-3">
                <div className="text-m-mute text-sm">{FMT.daysWord(s.days_left)} до окончания</div>
                <div className="text-m-dim text-[12px] font-mono mt-0.5">истекает {FMT.date(s.expires_at)}</div>
              </div>
            </div>

            <div className="mt-5">
              <ProgressBar value={s.days_left} max={s.total_days} tone="bg-gradient-to-r from-m-accent to-cyan-300" />
              <div className="flex justify-between text-[11px] text-m-dim font-mono mt-1.5">
                <span>оплачено {s.period_label}</span>
                <span>{Math.round((s.days_left / s.total_days) * 100)}%</span>
              </div>
            </div>
          </div>
        </Card>

        {/* Traffic card */}
        <Card>
          <div className="flex items-start justify-between mb-4">
            <div>
              <div className="text-[11px] uppercase tracking-widest text-m-dim">Трафик</div>
              <div className="mt-2 flex items-baseline gap-3 tabular-nums">
                <div className="text-3xl font-medium text-m-text">{FMT.gb(traffic.total.down_gb)}</div>
                <span className="text-m-mute text-sm">скачано</span>
              </div>
              <div className="text-[12px] text-m-dim font-mono mt-1">
                <span className="text-m-ok">↓ {FMT.gb(traffic.total.down_gb)}</span>
                <span className="mx-2">·</span>
                <span className="text-m-accent">↑ {FMT.gb(traffic.total.up_gb)}</span>
              </div>
            </div>
            <IconButton icon="chart" onClick={() => onRoute('traffic')} />
          </div>

          <div className="mt-5 pt-5 border-t border-white/5">
            <div className="flex items-center justify-between mb-2">
              <div className="text-[13px] text-m-text font-medium flex items-center gap-2">
                <Icon name="globe" size={14} className="text-m-mute" />
                Сервер обхода
              </div>
              <div className="text-[12px] font-mono text-m-mute tabular-nums">
                {FMT.gb(bypass.used_gb)} / {FMT.gb(bypass.quota_gb)}
              </div>
            </div>
            <ProgressBar value={bypass.used_gb} max={bypass.quota_gb} />
            <div className="mt-3 flex items-center justify-between">
              <div className="text-[11px] text-m-dim">
                базовый лимит {FMT.gb(bypass.base_cap_gb)} · докуплено {FMT.gb(bypass.extra_gb)}
              </div>
              <Button size="sm" variant="ghost" icon="plus" onClick={() => onRoute('traffic')}>Докупить ГБ</Button>
            </div>
          </div>
        </Card>

        {/* Devices card */}
        <Card>
          <div className="flex items-start justify-between mb-4">
            <div>
              <div className="text-[11px] uppercase tracking-widest text-m-dim">Устройства</div>
              <div className="mt-2 flex items-baseline gap-3 tabular-nums">
                <div className="text-3xl font-medium text-m-text">{lim.devices_used}</div>
                <span className="text-m-mute text-sm">из {lim.devices_max} активных</span>
              </div>
              <div className="text-[12px] text-m-dim mt-1">
                доп. устройство — {FMT.money(lim.extra_device_price, lim.extra_device_currency)}/мес
              </div>
            </div>
            <IconButton icon="device" onClick={() => onRoute('devices')} />
          </div>

          <div className="mt-5 pt-5 border-t border-white/5 flex flex-wrap gap-2">
            {traffic.devices.slice(0, 3).map(d => (
              <span key={d.id} className="px-3 py-1.5 rounded-lg bg-white/[0.04] border border-white/5 text-[12px] text-m-text inline-flex items-center gap-2">
                <span className="w-1.5 h-1.5 rounded-full bg-m-ok" /> {d.name}
              </span>
            ))}
            <Button size="sm" variant="ghost" icon="plus" onClick={() => onRoute('devices')} className="ml-auto">
              Управление
            </Button>
          </div>
        </Card>

        {/* Quick links */}
        <Card className="lg:col-span-2">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
            {[
              { icon: 'card',  title: 'Оплата',    sub: 'Пополнение и история', route: 'payments' },
              { icon: 'gift',  title: 'Рефералы',  sub: '+30 дней за друга',    route: 'referral', badge: 'gold' },
              { icon: 'globe', title: 'Локации',   sub: '12 стран · 87 серверов', route: null },
              { icon: 'help',  title: 'Помощь',    sub: 'Инструкции и поддержка', route: 'help' },
            ].map((q, i) => (
              <button
                key={i}
                onClick={() => q.route && onRoute(q.route)}
                className="flex items-center gap-3 p-3 rounded-xl bg-white/[0.02] hover:bg-white/[0.06] border border-white/5 transition text-left"
              >
                <div className={`w-10 h-10 rounded-xl grid place-items-center border ${
                  q.badge === 'gold' ? 'bg-m-gold/15 border-m-gold/30 text-m-gold' :
                  'bg-m-bg2 border-white/5 text-m-text'
                }`}>
                  <Icon name={q.icon} size={18} />
                </div>
                <div className="min-w-0">
                  <div className="text-[13px] font-medium text-m-text">{q.title}</div>
                  <div className="text-[11px] text-m-dim truncate">{q.sub}</div>
                </div>
              </button>
            ))}
          </div>
        </Card>

      </div>
    </div>
  );
}

function DashboardSkeleton() {
  return (
    <div className="slide-up">
      <Skeleton className="h-8 w-56 mb-6" />
      <div className="grid lg:grid-cols-2 gap-4">
        <div className="lg:col-span-2"><Skeleton className="h-64 rounded-2xl" /></div>
        <Skeleton className="h-48 rounded-2xl" />
        <Skeleton className="h-48 rounded-2xl" />
      </div>
    </div>
  );
}

// ============================================
// SUBSCRIPTION
// ============================================
function SubscriptionScreen({ onRoute, onRefresh }) {
  const [me, setMe] = useState(null);
  const [plans, setPlans] = useState(null);
  const [selected, setSelected] = useState(null);
  const [busy, setBusy] = useState(false);
  const toast = useToast();

  useEffect(() => {
    Promise.all([api('/me'), api('/plans')]).then(([m, p]) => {
      setMe(m); setPlans(p);
      setSelected(m.subscription.plan_id);
    });
  }, []);

  if (!me || !plans) return <Skeleton className="h-96" />;
  const s = me.subscription;

  const setAutoRenew = async (v) => {
    setMe({ ...me, subscription: { ...s, auto_renew: v } });
    try {
      await api('/subscription/auto-renew', { method: 'POST', body: { enabled: v } });
      toast.success(v ? 'Автопродление включено' : 'Автопродление отключено');
    } catch { toast.error('Не удалось изменить настройку'); }
  };

  const renew = async () => {
    if (!selected) return;
    const plan = plans.find(p => p.id === selected);
    setBusy(true);
    try {
      const res = await api('/subscription/renew', { method: 'POST', body: { plan_id: selected, period_months: plan.period_months } });
      if (res.payment_url) {
        toast.info('Открываю страницу оплаты…');
        window.location.href = res.payment_url;
        return;
      } else if (res.balance_ok) {
        toast.success('Подписка продлена с баланса');
        onRefresh?.();
      }
    } catch { toast.error('Не удалось оформить продление'); }
    setBusy(false);
  };

  return (
    <div className="slide-up">
      <ScreenHeader title="Подписка" subtitle="Тариф, автопродление и оплата" />

      {/* Current */}
      <Card className="mb-4">
        <div className="flex items-start justify-between gap-4">
          <div>
            <div className="text-[11px] uppercase tracking-widest text-m-dim">Текущий тариф</div>
            <div className="mt-1.5 text-xl font-semibold text-m-text">{s.plan_name} · {s.period_label}</div>
            <div className="text-[13px] text-m-mute mt-1">
              {FMT.money(s.price_per_month, s.currency)}/мес · истекает {FMT.date(s.expires_at)}
            </div>
          </div>
          {s.status === 'expired'
            ? <Badge tone="err">Истекла</Badge>
            : <Badge tone={s.status === 'trial' ? 'gold' : 'ok'} icon="check">{s.status === 'trial' ? 'Пробный' : 'Активна'}</Badge>}
        </div>

        <div className="mt-5 pt-5 border-t border-white/5 flex items-center justify-between gap-3">
          <div>
            <div className="text-[14px] text-m-text">Автопродление</div>
            <div className="text-[12px] text-m-dim mt-0.5">
              Подписка будет продлеваться автоматически за {FMT.money(s.price_per_month, s.currency)}/мес
            </div>
          </div>
          <Toggle checked={s.auto_renew} onChange={setAutoRenew} />
        </div>
      </Card>

      {/* Plans */}
      <div className="text-[11px] uppercase tracking-widest text-m-dim mb-2 px-1">Сменить тариф или продлить</div>
      <div className="grid md:grid-cols-2 gap-3 mb-5">
        {plans.map(p => {
          const isCurrent = p.id === s.plan_id;
          const isSelected = p.id === selected;
          return (
            <button
              key={p.id}
              onClick={() => setSelected(p.id)}
              className={`relative text-left p-4 rounded-2xl border transition-all
                ${isSelected
                  ? 'border-m-accent/50 bg-m-accent/[0.05] shadow-glow'
                  : 'border-white/5 bg-m-card hover:bg-m-card-hi'}`}
            >
              {p.popular && (
                <span className="absolute -top-2 left-4 text-[10px] uppercase tracking-widest font-medium px-2 py-0.5 rounded-full bg-m-gold text-m-bg">
                  выгодно
                </span>
              )}
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <span className="font-medium text-m-text text-[15px]">{p.name}</span>
                  {isCurrent && <Badge tone="accent" size="sm">текущий</Badge>}
                </div>
                <div className={`w-5 h-5 rounded-full border grid place-items-center transition
                  ${isSelected ? 'bg-m-accent border-m-accent' : 'border-white/15'}`}>
                  {isSelected && <Icon name="check" size={12} className="text-m-bg" strokeWidth={3} />}
                </div>
              </div>
              <div className="mt-3 flex items-baseline gap-2 tabular-nums">
                <span className="text-2xl font-semibold text-m-text">{FMT.money(p.per_month, p.currency)}</span>
                <span className="text-[12px] text-m-mute">/мес</span>
              </div>
              <div className="text-[12px] text-m-dim mt-1">
                всего {FMT.money(p.price, p.currency)} за {p.period_months} мес.
                {p.discount_pct > 0 && <span className="text-m-ok ml-2">экономия {p.discount_pct}%</span>}
              </div>
            </button>
          );
        })}
      </div>

      <Button variant="primary" size="lg" fullWidth icon="card" loading={busy} onClick={renew}>
        {selected === s.plan_id ? 'Продлить подписку' : 'Перейти на этот тариф'}
      </Button>
      <div className="text-center text-[11px] text-m-dim mt-3">
        Безопасная оплата · можно отменить в любой момент
      </div>
    </div>
  );
}

// ============================================
// PAYMENTS — top-up + history
// ============================================
function PaymentsScreen() {
  const [methods, setMethods] = useState(null);
  const [history, setHistory] = useState(null);
  const [amount, setAmount] = useState(500);
  const [method, setMethod] = useState(null);
  const [busy, setBusy] = useState(false);
  const toast = useToast();

  useEffect(() => {
    Promise.all([api('/payments/methods'), api('/payments/history')]).then(([m, h]) => {
      setMethods(m); setHistory(h);
      const first = m.find(x => x.enabled);
      if (first) setMethod(first.id);
    });
  }, []);

  if (!methods || !history) return <Skeleton className="h-96" />;

  const topup = async () => {
    if (!amount || amount < 50) { toast.error('Минимальная сумма — 50 ₽'); return; }
    if (!method) { toast.error('Выберите способ оплаты'); return; }
    setBusy(true);
    try {
      const res = await api('/payments/topup', { method: 'POST', body: { amount: +amount, method } });
      if (res.payment_url) {
        toast.info('Открываю страницу оплаты…');
        window.location.href = res.payment_url;
        return;
      }
    } catch { toast.error('Ошибка оплаты'); }
    setBusy(false);
  };

  const statusBadge = (s) => {
    if (s === 'paid')      return <Badge tone="ok"  size="sm">оплачено</Badge>;
    if (s === 'pending')   return <Badge tone="gold" size="sm">ожидание</Badge>;
    if (s === 'cancelled') return <Badge tone="err" size="sm">отменён</Badge>;
    return <Badge size="sm">{s}</Badge>;
  };

  return (
    <div className="slide-up">
      <ScreenHeader title="Оплата" subtitle="Пополнение баланса и история платежей" />

      <div className="grid lg:grid-cols-5 gap-4">

        {/* Top-up form */}
        <Card className="lg:col-span-3">
          <div className="text-[11px] uppercase tracking-widest text-m-dim mb-3">Пополнение баланса</div>

          <Field label="Сумма" className="mb-4">
            <div className="flex items-center gap-2 bg-m-bg2 border border-white/5 rounded-xl pl-4 pr-2 h-12">
              <input
                type="number" inputMode="numeric" min="50" step="50"
                className="flex-1 bg-transparent outline-none text-m-text text-lg tabular-nums"
                value={amount}
                onChange={e => setAmount(e.target.value)}
              />
              <span className="text-m-mute">₽</span>
            </div>
            <div className="flex gap-2 mt-2.5">
              {[500, 1000, 2000, 5000].map(v => (
                <button key={v} onClick={() => setAmount(v)}
                  className={`flex-1 h-9 rounded-lg text-[12px] font-medium border transition
                    ${amount == v ? 'bg-m-accent/15 border-m-accent/40 text-m-accent' : 'bg-white/[0.03] border-white/5 text-m-mute hover:text-m-text'}`}>
                  {v} ₽
                </button>
              ))}
            </div>
          </Field>

          <Field label="Способ оплаты">
            <div className="space-y-2">
              {methods.filter(m => m.enabled).map(m => (
                <button
                  key={m.id}
                  onClick={() => setMethod(m.id)}
                  className={`w-full flex items-center gap-3 p-3 rounded-xl border transition text-left
                    ${method === m.id
                      ? 'border-m-accent/40 bg-m-accent/[0.05]'
                      : 'border-white/5 bg-m-bg2 hover:bg-white/[0.04]'}`}
                >
                  <div className="w-10 h-10 rounded-xl bg-white/[0.04] border border-white/5 grid place-items-center text-m-text">
                    <Icon name={m.icon === 'card' ? 'card' : m.icon === 'crypto' ? 'zap' : 'check'} size={18} />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="text-[14px] text-m-text">{m.name}</div>
                    <div className="text-[11px] text-m-dim">{m.description}</div>
                  </div>
                  <div className={`w-5 h-5 rounded-full border grid place-items-center
                    ${method === m.id ? 'bg-m-accent border-m-accent' : 'border-white/15'}`}>
                    {method === m.id && <Icon name="check" size={12} className="text-m-bg" strokeWidth={3} />}
                  </div>
                </button>
              ))}
              {methods.filter(m => !m.enabled).map(m => (
                <div key={m.id} className="flex items-center gap-3 p-3 rounded-xl border border-white/5 bg-m-bg2/40 opacity-50">
                  <div className="w-10 h-10 rounded-xl bg-white/[0.04] border border-white/5 grid place-items-center text-m-mute">
                    <Icon name="close" size={16} />
                  </div>
                  <div>
                    <div className="text-[14px] text-m-text">{m.name}</div>
                    <div className="text-[11px] text-m-dim">{m.description}</div>
                  </div>
                </div>
              ))}
            </div>
          </Field>

          <Button variant="primary" size="lg" fullWidth icon="card" loading={busy} onClick={topup} className="mt-5">
            Оплатить {FMT.money(amount || 0)}
          </Button>
        </Card>

        {/* History */}
        <Card className="lg:col-span-2">
          <div className="text-[11px] uppercase tracking-widest text-m-dim mb-3">История платежей</div>
          <div className="-mx-2">
            {history.map(h => (
              <div key={h.id} className="px-2 py-3 border-b border-white/5 last:border-0">
                <div className="flex items-start justify-between gap-3">
                  <div className="min-w-0">
                    <div className="text-[13px] text-m-text truncate">{h.description}</div>
                    <div className="text-[11px] text-m-dim mt-0.5 font-mono">
                      {FMT.dateShort(h.date)} · {h.method}
                    </div>
                  </div>
                  <div className="text-right shrink-0">
                    <div className="text-[14px] text-m-text font-medium tabular-nums">{FMT.money(h.amount, h.currency)}</div>
                    <div className="mt-1">{statusBadge(h.status)}</div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </Card>

      </div>
    </div>
  );
}

// ============================================
// DEVICES
// ============================================
function DevicesScreen({ onRefresh }) {
  const [me, setMe] = useState(null);
  const [devices, setDevices] = useState(null);
  const [showAdd, setShowAdd] = useState(false);
  const [showConfig, setShowConfig] = useState(null); // device id
  const [renaming, setRenaming] = useState(null);     // device obj
  const [deleting, setDeleting] = useState(null);     // device obj
  const [syncing, setSyncing] = useState(false);
  const [repairing, setRepairing] = useState(false);
  const toast = useToast();

  const repairVpn = async () => {
    setRepairing(true);
    try {
      const r = await api('/repair', { method: 'POST' });
      if (r && r.ok) {
        toast.success('Готово! Ключи обновлены на ' + r.nodes + ' серверах. Обновите подписку в приложении, выберите сервер «' + r.recommended + '» и переподключитесь.');
        onRefresh && onRefresh();
      } else {
        toast.error((r && r.message) || 'Не удалось починить автоматически');
      }
    } catch (e) {
      toast.error('Ошибка при починке, попробуйте ещё раз');
    } finally {
      setRepairing(false);
    }
  };
  const syncDevices = async () => {
    setSyncing(true);
    try { await api('/sync', { method: 'POST' }); toast.success('VPN синхронизирован на всех серверах. Обновите конфиг в приложении.'); onRefresh?.(); }
    catch { toast.error('Ошибка синхронизации'); }
    finally { setSyncing(false); }
  };

  const reload = async () => {
    const [m, d] = await Promise.all([api('/me'), api('/devices')]);
    setMe(m); setDevices(d);
  };
  useEffect(() => { reload(); }, []);

  if (!me || !devices) return <Skeleton className="h-96" />;

  const lim = me.limits;
  const atLimit = lim.devices_used >= lim.devices_max;

  const addDevice = async (name, platform) => {
    const res = await api('/devices', { method: 'POST', body: { name, platform } });
    await reload(); onRefresh?.();
    toast.success('Устройство добавлено');
    setShowAdd(false);
    setShowConfig(res.device.id);
  };
  const renameDevice = async (id, name) => {
    await api(`/devices/${id}`, { method: 'PATCH', body: { name } });
    await reload();
    toast.success('Переименовано');
    setRenaming(null);
  };
  const removeDevice = async (id) => {
    await api(`/devices/${id}`, { method: 'DELETE' });
    await reload(); onRefresh?.();
    toast.success('Устройство удалено');
    setDeleting(null);
  };

  return (
    <div className="slide-up">
      <ScreenHeader
        title="Устройства"
        subtitle={`${lim.devices_used} из ${lim.devices_max} активных`}
        right={
          <div className="flex gap-2 items-center">
            <Button variant="secondary" size="sm" loading={syncing} onClick={syncDevices}>🔄 Синх.</Button>
            <Button variant="secondary" size="sm" loading={repairing} onClick={repairVpn}>🆘 VPN не работает</Button>
            <Button variant="primary" icon="plus" onClick={() => setShowAdd(true)}>
              Добавить устройство
            </Button>
          </div>
        }
      />

      {atLimit && (
        <Card padding="p-4" className="mb-4 border-m-gold/30 bg-m-gold/[0.05]">
          <div className="flex items-start gap-3">
            <div className="w-9 h-9 rounded-xl bg-m-gold/15 border border-m-gold/30 grid place-items-center text-m-gold shrink-0">
              <Icon name="bell" size={18} />
            </div>
            <div className="min-w-0">
              <div className="text-[14px] text-m-text font-medium">Достигнут лимит устройств</div>
              <div className="text-[12px] text-m-mute mt-0.5">
                Удалите неиспользуемое устройство или подключите дополнительное за {FMT.money(lim.extra_device_price, lim.extra_device_currency)}/мес.
              </div>
            </div>
            <Button size="sm" variant="gold" onClick={() => setShowAdd(true)}>Доп. устройство</Button>
          </div>
        </Card>
      )}

      <div className="space-y-3">
        {devices.map(d => (
          <Card key={d.id} padding="p-4">
            <div className="flex items-center gap-3 md:gap-4">
              <div className="w-11 h-11 md:w-12 md:h-12 rounded-xl bg-m-bg2 border border-white/5 grid place-items-center shrink-0">
                <Icon name={PLATFORM_ICON[d.platform]} size={22} />
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 flex-wrap">
                  <span className="text-[15px] text-m-text font-medium truncate">{d.name}</span>
                  {d.online
                    ? <Badge tone="ok" size="sm"><span className="w-1.5 h-1.5 rounded-full bg-m-ok pulse-dot" />online</Badge>
                    : <Badge size="sm">offline</Badge>}
                </div>
                <div className="text-[11px] text-m-dim mt-1 font-mono truncate">
                  {PLATFORM_LABEL[d.platform]} · HWID {d.hwid} · {d.last_activity}
                </div>
              </div>
              <div className="hidden md:flex items-center gap-1.5">
                <IconButton icon="qr" onClick={() => setShowConfig(d.id)} />
                <IconButton icon="edit" onClick={() => setRenaming(d)} />
                <IconButton icon="trash" onClick={() => setDeleting(d)} />
              </div>
              <details className="md:hidden relative">
                <summary className="list-none cursor-pointer w-9 h-9 rounded-xl bg-white/[0.04] border border-white/5 grid place-items-center text-m-text">
                  <Icon name="more" size={16} />
                </summary>
                <div className="absolute right-0 top-10 z-20 bg-m-card-hi border border-white/8 rounded-xl shadow-lift p-1 w-44">
                  <button onClick={() => setShowConfig(d.id)} className="w-full text-left px-3 py-2 rounded-lg text-[13px] hover:bg-white/5 inline-flex items-center gap-2"><Icon name="qr" size={14}/> Конфиг и QR</button>
                  <button onClick={() => setRenaming(d)}   className="w-full text-left px-3 py-2 rounded-lg text-[13px] hover:bg-white/5 inline-flex items-center gap-2"><Icon name="edit" size={14}/> Переименовать</button>
                  <button onClick={() => setDeleting(d)}    className="w-full text-left px-3 py-2 rounded-lg text-[13px] hover:bg-white/5 text-m-err inline-flex items-center gap-2"><Icon name="trash" size={14}/> Удалить</button>
                </div>
              </details>
            </div>
          </Card>
        ))}
        {devices.length === 0 && (
          <Card padding="p-10" className="text-center">
            <div className="w-14 h-14 rounded-2xl bg-m-bg2 border border-white/5 grid place-items-center mx-auto mb-3">
              <Icon name="device" size={26} className="text-m-mute" />
            </div>
            <div className="text-m-text font-medium">Нет подключённых устройств</div>
            <div className="text-[13px] text-m-mute mt-1">Добавьте устройство, чтобы получить конфигурацию.</div>
          </Card>
        )}
      </div>

      <AddDeviceModal open={showAdd} onClose={() => setShowAdd(false)} onSubmit={addDevice} />
      <ConfigSheet
        open={!!showConfig}
        deviceId={showConfig}
        device={devices.find(d => d.id === showConfig)}
        onClose={() => setShowConfig(null)}
      />
      <RenameModal
        open={!!renaming} device={renaming}
        onClose={() => setRenaming(null)}
        onSubmit={(name) => renameDevice(renaming.id, name)}
      />
      <ConfirmModal
        open={!!deleting}
        title="Удалить устройство?"
        message={deleting ? `Конфигурация «${deleting.name}» будет аннулирована немедленно.` : ''}
        confirmLabel="Удалить"
        onConfirm={() => removeDevice(deleting.id)}
        onClose={() => setDeleting(null)}
      />
    </div>
  );
}

function AddDeviceModal({ open, onClose, onSubmit }) {
  const [name, setName] = useState('');
  const [platform, setPlatform] = useState('ios');
  const [loading, setLoading] = useState(false);
  useEffect(() => { if (open) { setName(''); setPlatform('ios'); } }, [open]);

  const submit = async (e) => {
    e.preventDefault();
    if (!name.trim()) return;
    setLoading(true);
    await onSubmit(name.trim(), platform);
    setLoading(false);
  };

  return (
    <Modal open={open} onClose={onClose} title="Новое устройство" maxWidth="max-w-md">
      <form onSubmit={submit} className="space-y-4">
        <Field label="Название">
          <Input
            placeholder="Например, iPhone 15 Pro"
            value={name}
            onChange={e => setName(e.target.value)}
            autoFocus
          />
        </Field>
        <Field label="Платформа">
          <div className="grid grid-cols-4 gap-2">
            {['ios','android','windows','macos'].map(p => (
              <button
                type="button"
                key={p}
                onClick={() => setPlatform(p)}
                className={`p-3 rounded-xl border flex flex-col items-center gap-1.5 transition
                  ${platform === p ? 'border-m-accent/40 bg-m-accent/[0.06] text-m-accent' : 'border-white/5 bg-m-bg2 text-m-text hover:bg-white/[0.04]'}`}
              >
                <Icon name={PLATFORM_ICON[p]} size={20} />
                <span className="text-[11px]">{PLATFORM_LABEL[p]}</span>
              </button>
            ))}
          </div>
        </Field>
        <Button type="submit" variant="primary" size="lg" fullWidth loading={loading}>
          Создать устройство
        </Button>
      </form>
    </Modal>
  );
}

// QR generator (offline, uses qrcode-generator if available, otherwise falls back to qrserver)
function QrCode({ data }) {
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current) return;
    if (typeof window.qrcode === 'function') {
      try {
        const qr = window.qrcode(0, 'M');
        qr.addData(data);
        qr.make();
        // createSvgTag returns inline SVG; expand it to fill container
        const svg = qr.createSvgTag({ cellSize: 4, margin: 4, scalable: true });
        ref.current.innerHTML = svg.replace('<svg ', '<svg style="width:100%;height:100%;display:block" ');
      } catch (e) {
        ref.current.innerHTML = '<div style="color:#888;font-size:11px;text-align:center;padding:8px;font-family:monospace">QR-ошибка</div>';
      }
    } else {
      // Fallback to remote (only if available)
      ref.current.innerHTML = `<img alt="QR" style="width:100%;height:100%" src="https://api.qrserver.com/v1/create-qr-code/?size=300x300&margin=8&data=${encodeURIComponent(data)}" />`;
    }
  }, [data]);
  return <div ref={ref} className="w-full h-full" />;
}

function ConfigSheet({ open, deviceId, device, onClose }) {
  const [cfg, setCfg] = useState(null);
  useEffect(() => {
    if (!open || !deviceId) { setCfg(null); return; }
    api(`/devices/${deviceId}/config`).then(setCfg);
  }, [open, deviceId]);

  return (
    <Sheet open={open} onClose={onClose} title={device ? `Конфиг — ${device.name}` : 'Конфигурация'}>
      {!cfg ? <Skeleton className="h-64" /> : (
        <div className="space-y-5">
          <div>
            <div className="text-[11px] uppercase tracking-widest text-m-dim mb-2">Ссылка-подписка</div>
            <CopyField value={cfg.sub_url} />
          </div>

          <div>
            <div className="text-[11px] uppercase tracking-widest text-m-dim mb-2">VLESS конфиг</div>
            <CopyField value={cfg.vless} />
          </div>

          <div>
            <div className="text-[11px] uppercase tracking-widest text-m-dim mb-2">QR-код</div>
            <div className="flex gap-4 items-center">
              <div className="w-40 h-40 bg-white rounded-xl p-2 shrink-0">
                <QrCode data={cfg.sub_url} />
              </div>
              <div className="text-[12px] text-m-mute leading-relaxed">
                Отсканируйте код в клиенте Happ, v2RayTun, Hiddify — подписка импортируется автоматически.
              </div>
            </div>
          </div>

          <Button variant="primary" size="lg" fullWidth icon="arrowRight"
            onClick={() => {
              const url = `happ://add/${encodeURIComponent(cfg.sub_url)}`;
              window.location.href = url;
            }}
          >
            Открыть в приложении
          </Button>
        </div>
      )}
    </Sheet>
  );
}

function RenameModal({ open, device, onClose, onSubmit }) {
  const [name, setName] = useState('');
  useEffect(() => { if (open && device) setName(device.name); }, [open, device]);
  const submit = (e) => { e.preventDefault(); onSubmit(name.trim()); };
  return (
    <Modal open={open} onClose={onClose} title="Переименовать">
      <form onSubmit={submit} className="space-y-4">
        <Field label="Название">
          <Input value={name} onChange={e => setName(e.target.value)} autoFocus />
        </Field>
        <div className="flex gap-2">
          <Button variant="secondary" fullWidth onClick={onClose} type="button">Отмена</Button>
          <Button variant="primary" fullWidth type="submit">Сохранить</Button>
        </div>
      </form>
    </Modal>
  );
}

function ConfirmModal({ open, title, message, confirmLabel = 'Подтвердить', onConfirm, onClose }) {
  return (
    <Modal open={open} onClose={onClose} title={title}>
      <p className="text-[14px] text-m-mute leading-relaxed mb-5">{message}</p>
      <div className="flex gap-2">
        <Button variant="secondary" fullWidth onClick={onClose}>Отмена</Button>
        <Button variant="danger"    fullWidth onClick={onConfirm}>{confirmLabel}</Button>
      </div>
    </Modal>
  );
}

// ============================================
// TRAFFIC
// ============================================
function TrafficScreen({ onRefresh }) {
  const [traffic, setTraffic] = useState(null);
  const [showBuy, setShowBuy] = useState(false);
  const toast = useToast();

  const reload = () => api('/traffic').then(setTraffic);
  useEffect(() => { reload(); }, []);
  if (!traffic) return <Skeleton className="h-96" />;

  const b = traffic.bypass;
  const pct = (b.used_gb / b.quota_gb) * 100;

  const buy = async (gb) => {
    await api('/traffic/buy-gb', { method: 'POST', body: { gb } });
    await reload(); onRefresh?.();
    toast.success(`Докуплено ${gb} ГБ`);
    setShowBuy(false);
  };

  return (
    <div className="slide-up">
      <ScreenHeader title="Трафик" subtitle="Общий расход и сервер обхода" />

      <div className="grid lg:grid-cols-2 gap-4 mb-4">
        {/* Total */}
        <Card>
          <div className="text-[11px] uppercase tracking-widest text-m-dim mb-3">Общий трафик</div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <div className="text-[12px] text-m-mute flex items-center gap-1.5"><Icon name="arrowDown" size={12} className="text-m-ok"/>скачано</div>
              <div className="text-3xl font-medium text-m-text mt-1 tabular-nums">{FMT.gb(traffic.total.down_gb)}</div>
            </div>
            <div>
              <div className="text-[12px] text-m-mute flex items-center gap-1.5"><Icon name="arrowUp" size={12} className="text-m-accent"/>отправлено</div>
              <div className="text-3xl font-medium text-m-text mt-1 tabular-nums">{FMT.gb(traffic.total.up_gb)}</div>
            </div>
          </div>
        </Card>

        {/* Bypass */}
        <Card className="relative overflow-hidden">
          <div className="absolute -top-16 -right-16 w-48 h-48 rounded-full bg-m-accent/10 blur-3xl pointer-events-none" />
          <div className="relative">
            <div className="flex items-center justify-between mb-3">
              <div className="text-[11px] uppercase tracking-widest text-m-dim flex items-center gap-1.5"><Icon name="globe" size={12}/>Сервер обхода</div>
              <Button size="sm" variant="primary" icon="plus" onClick={() => setShowBuy(true)}>
                Докупить ГБ
              </Button>
            </div>
            <div className="flex items-baseline gap-3 tabular-nums">
              <div className="text-3xl font-medium text-m-text">{FMT.gb(b.used_gb)}</div>
              <div className="text-[13px] text-m-mute">из {FMT.gb(b.quota_gb)}</div>
            </div>
            <div className="mt-4"><ProgressBar value={b.used_gb} max={b.quota_gb} height={8} /></div>
            <div className="grid grid-cols-2 gap-3 mt-4 pt-4 border-t border-white/5">
              <div>
                <div className="text-[11px] text-m-dim">базовый лимит</div>
                <div className="text-[14px] text-m-text mt-0.5">{FMT.gb(b.base_cap_gb)}</div>
              </div>
              <div>
                <div className="text-[11px] text-m-dim">докуплено</div>
                <div className="text-[14px] text-m-text mt-0.5">{FMT.gb(b.extra_gb)}</div>
              </div>
            </div>
          </div>
        </Card>
      </div>

      {/* Per-device breakdown */}
      <Card>
        <div className="text-[11px] uppercase tracking-widest text-m-dim mb-3">По устройствам</div>
        <div className="space-y-1">
          {traffic.devices.map(d => {
            const total = d.up_gb + d.down_gb;
            const max = Math.max(...traffic.devices.map(x => x.up_gb + x.down_gb));
            return (
              <div key={d.id} className="py-3 border-b border-white/5 last:border-0">
                <div className="flex items-center justify-between mb-2">
                  <div className="text-[14px] text-m-text">{d.name}</div>
                  <div className="text-[12px] text-m-mute font-mono tabular-nums">
                    <span className="text-m-ok">↓{FMT.gb(d.down_gb)}</span>
                    <span className="mx-1.5 text-m-dim">·</span>
                    <span className="text-m-accent">↑{FMT.gb(d.up_gb)}</span>
                  </div>
                </div>
                <ProgressBar value={total} max={max} tone="bg-gradient-to-r from-m-accent/60 to-cyan-400/60" />
              </div>
            );
          })}
        </div>
      </Card>

      <BuyGbModal open={showBuy} onClose={() => setShowBuy(false)} bypass={b} onBuy={buy} />
    </div>
  );
}

function BuyGbModal({ open, onClose, bypass, onBuy }) {
  const packs = [
    { gb: 10,  price: 10  * bypass.price_per_gb },
    { gb: 25,  price: 25  * bypass.price_per_gb - 50 },
    { gb: 50,  price: 50  * bypass.price_per_gb - 150 },
    { gb: 100, price: 100 * bypass.price_per_gb - 400 },
  ];
  const [pick, setPick] = useState(25);
  const [loading, setLoading] = useState(false);
  return (
    <Modal open={open} onClose={onClose} title="Докупить трафик">
      <p className="text-[13px] text-m-mute mb-4">
        Пакет добавится к лимиту сервера обхода и сохранится до конца расчётного периода.
      </p>
      <div className="grid grid-cols-2 gap-2 mb-5">
        {packs.map(p => (
          <button key={p.gb} onClick={() => setPick(p.gb)}
            className={`p-3 rounded-xl border text-left transition
              ${pick === p.gb ? 'border-m-accent/40 bg-m-accent/[0.06]' : 'border-white/5 bg-m-bg2 hover:bg-white/[0.04]'}`}>
            <div className="text-[18px] font-semibold text-m-text tabular-nums">{p.gb} ГБ</div>
            <div className="text-[12px] text-m-mute mt-0.5 tabular-nums">{FMT.money(p.price)}</div>
          </button>
        ))}
      </div>
      <Button variant="primary" size="lg" fullWidth icon="card" loading={loading}
        onClick={async () => { setLoading(true); await onBuy(pick); setLoading(false); }}>
        Оплатить и активировать
      </Button>
    </Modal>
  );
}

// ============================================
// REFERRAL
// ============================================
function ReferralScreen() {
  const [ref, setRef] = useState(null);
  const toast = useToast();
  useEffect(() => { api('/referral').then(setRef); }, []);
  if (!ref) return <Skeleton className="h-96" />;

  const share = (platform) => {
    const text = `Быстрый и удобный VPN. Регистрируйся по моей ссылке и получи первый месяц в подарок: ${ref.link}`;
    if (platform === 'tg') window.open(`https://t.me/share/url?url=${encodeURIComponent(ref.link)}&text=${encodeURIComponent(text)}`);
    if (platform === 'wa') window.open(`https://wa.me/?text=${encodeURIComponent(text)}`);
  };

  return (
    <div className="slide-up">
      <ScreenHeader title="Рефералы" subtitle="Приглашайте друзей и получайте бонусные дни" />

      <Card className="relative overflow-hidden mb-4">
        <div className="absolute -top-20 -right-20 w-72 h-72 rounded-full bg-m-gold/10 blur-3xl pointer-events-none" />
        <div className="relative grid md:grid-cols-2 gap-6 items-center">
          <div>
            <div className="w-12 h-12 rounded-2xl bg-m-gold/15 border border-m-gold/30 text-m-gold grid place-items-center mb-3">
              <Icon name="gift" size={22} />
            </div>
            <div className="text-[22px] font-semibold text-m-text tracking-tight leading-snug">
              Подарите другу VPN<br/>и получите +30 дней
            </div>
            <p className="text-[13px] text-m-mute mt-3 leading-relaxed">{ref.rule_text}</p>
          </div>
          <div className="grid grid-cols-3 gap-2">
            <Card padding="p-3.5" className="text-center">
              <div className="text-[10px] uppercase tracking-widest text-m-dim">Приглашено</div>
              <div className="text-2xl font-medium text-m-text mt-1 tabular-nums">{ref.invited_count}</div>
            </Card>
            <Card padding="p-3.5" className="text-center">
              <div className="text-[10px] uppercase tracking-widest text-m-dim">Оплатили</div>
              <div className="text-2xl font-medium text-m-text mt-1 tabular-nums">{ref.paid_count}</div>
            </Card>
            <Card padding="p-3.5" className="text-center">
              <div className="text-[10px] uppercase tracking-widest text-m-dim">Бонус</div>
              <div className="text-2xl font-medium text-m-gold mt-1 tabular-nums">+{ref.balance}</div>
              <div className="text-[10px] text-m-dim">{ref.balance_unit}</div>
            </Card>
          </div>
        </div>
      </Card>

      <Card className="mb-4">
        <div className="text-[11px] uppercase tracking-widest text-m-dim mb-3">Ваша реферальная ссылка</div>
        <CopyField value={ref.link} />
        <div className="text-[11px] text-m-dim mt-2 font-mono">код: {ref.code}</div>

        <div className="text-[11px] uppercase tracking-widest text-m-dim mt-5 mb-2">Поделиться</div>
        <div className="grid grid-cols-2 gap-2">
          <button onClick={() => share('tg')}
            className="flex items-center gap-3 p-3 rounded-xl bg-[#229ED9]/15 border border-[#229ED9]/30 text-m-text hover:bg-[#229ED9]/25 transition">
            <div className="w-9 h-9 rounded-xl bg-[#229ED9] text-white grid place-items-center"><Icon name="telegram" size={18}/></div>
            <span className="text-[14px]">Telegram</span>
          </button>
          <button onClick={() => share('wa')}
            className="flex items-center gap-3 p-3 rounded-xl bg-[#25D366]/15 border border-[#25D366]/30 text-m-text hover:bg-[#25D366]/25 transition">
            <div className="w-9 h-9 rounded-xl bg-[#25D366] text-white grid place-items-center font-bold">W</div>
            <span className="text-[14px]">WhatsApp</span>
          </button>
        </div>
      </Card>
    </div>
  );
}

// ============================================
// HELP
// ============================================
function HelpScreen() {
  const [help, setHelp] = useState(null);
  const [tab, setTab] = useState('ios');
  const [openFaq, setOpenFaq] = useState(null);
  useEffect(() => { api('/help').then(setHelp); }, []);
  if (!help) return <Skeleton className="h-96" />;

  const platform = help.platforms.find(p => p.id === tab) || help.platforms[0];

  return (
    <div className="slide-up">
      <ScreenHeader
        title="Помощь"
        subtitle="Пошаговые инструкции и ответы на вопросы"
        right={
          <Button variant="primary" icon="telegram" as="a" href={help.support_url} target="_blank" rel="noopener">
            Написать в поддержку
          </Button>
        }
      />

      <Card className="mb-4">
        <div className="flex gap-1 bg-m-bg2 p-1 rounded-xl mb-5 overflow-x-auto">
          {help.platforms.map(p => (
            <button key={p.id} onClick={() => setTab(p.id)}
              className={`flex items-center gap-2 px-4 h-9 rounded-lg text-[13px] font-medium whitespace-nowrap transition
                ${tab === p.id ? 'bg-m-card-hi text-m-text shadow' : 'text-m-mute hover:text-m-text'}`}>
              <Icon name={PLATFORM_ICON[p.id]} size={14} />
              {p.name}
            </button>
          ))}
        </div>

        <ol className="space-y-3">
          {platform.steps.map(step => (
            <li key={step.n} className="flex gap-4 items-start">
              <div className="w-9 h-9 rounded-xl bg-m-accent/10 border border-m-accent/30 text-m-accent grid place-items-center font-mono text-[13px] shrink-0">
                {String(step.n).padStart(2, '0')}
              </div>
              <div className="text-[14px] text-m-text leading-relaxed pt-1.5">{step.text}</div>
            </li>
          ))}
        </ol>
      </Card>

      <Card>
        <div className="text-[11px] uppercase tracking-widest text-m-dim mb-3">Частые вопросы</div>
        <div className="space-y-1">
          {help.faq.map((f, i) => {
            const isOpen = openFaq === i;
            return (
              <div key={i} className="border-b border-white/5 last:border-0">
                <button onClick={() => setOpenFaq(isOpen ? null : i)}
                  className="w-full py-3.5 flex items-center justify-between gap-3 text-left">
                  <span className="text-[14px] text-m-text">{f.q}</span>
                  <Icon name={isOpen ? 'chevU' : 'chevD'} size={16} className="text-m-mute shrink-0" />
                </button>
                {isOpen && (
                  <div className="pb-4 text-[13px] text-m-mute leading-relaxed fade-in">{f.a}</div>
                )}
              </div>
            );
          })}
        </div>
      </Card>
    </div>
  );
}

// expose
Object.assign(window, {
  LoginScreen, DashboardScreen, SubscriptionScreen, PaymentsScreen,
  DevicesScreen, TrafficScreen, ReferralScreen, HelpScreen,
});
