// ============================================
// MariusVPN — App shell, navigation, entry
// ============================================

const { useState, useEffect, useCallback } = React;
const {
  api, Icon, FMT, MOCK,
  Logo, Card, Button, IconButton, Badge, Spinner,
  ToastHost, useToast,
  LoginScreen, DashboardScreen, SubscriptionScreen, PaymentsScreen,
  DevicesScreen, TrafficScreen, ReferralScreen, HelpScreen,
} = window;

const NAV = [
  { id: 'dashboard',    label: 'Главная',     icon: 'home',   shortLabel: 'Главная' },
  { id: 'subscription', label: 'Подписка',    icon: 'crown',  shortLabel: 'Подписка' },
  { id: 'devices',      label: 'Устройства',  icon: 'device', shortLabel: 'Устройства' },
  { id: 'traffic',      label: 'Трафик',      icon: 'chart',  shortLabel: 'Трафик' },
  { id: 'payments',     label: 'Оплата',      icon: 'card',   shortLabel: 'Оплата' },
  { id: 'referral',     label: 'Рефералы',    icon: 'gift',   shortLabel: 'Рефералы' },
  { id: 'help',         label: 'Помощь',      icon: 'help',   shortLabel: 'Помощь' },
];

// Mobile bottom-nav: 4 primary + "more"
const MOBILE_NAV = ['dashboard', 'devices', 'traffic', 'payments'];

// ============================================
// SIDEBAR (desktop)
// ============================================
function Sidebar({ route, onRoute, me, onLogout }) {
  return (
    <aside className="hidden md:flex w-[240px] shrink-0 flex-col bg-m-bg2 border-r border-white/5 sticky top-0 h-screen">
      <div className="px-5 pt-5 pb-3">
        <Logo size={26} />
      </div>

      {/* Plan card */}
      {me && (
        <div className="mx-3 mt-2 mb-3 p-3 rounded-xl bg-m-card border border-white/5">
          <div className="flex items-center justify-between">
            <div className="text-[11px] uppercase tracking-widest text-m-dim">Тариф</div>
            <Badge tone={me.subscription.status === 'expired' ? 'err' : (me.subscription.status === 'trial' ? 'gold' : 'ok')} size="sm">
              {me.subscription.status === 'expired' ? 'истекла' : (me.subscription.status === 'trial' ? 'пробный' : 'активна')}
            </Badge>
          </div>
          <div className="mt-1.5 text-[13px] font-medium text-m-text">
            {me.brand || ''} {me.subscription.plan_name}
          </div>
          <div className="text-[11px] text-m-mute mt-0.5">
            осталось <span className="text-m-text font-medium tabular-nums">{me.subscription.days_left}</span> {FMT.daysWord(me.subscription.days_left)}
          </div>
        </div>
      )}

      <nav className="flex-1 px-2 py-2 overflow-y-auto">
        {NAV.map(item => {
          const active = route === item.id;
          return (
            <button
              key={item.id}
              onClick={() => onRoute(item.id)}
              className={`w-full flex items-center gap-3 px-3 h-10 rounded-xl mb-0.5 text-[14px] transition
                ${active
                  ? 'bg-m-accent/[0.08] text-m-accent font-medium'
                  : 'text-m-mute hover:text-m-text hover:bg-white/[0.03]'}`}
            >
              <Icon name={item.icon} size={18} />
              {item.label}
              {active && <span className="ml-auto w-1.5 h-1.5 rounded-full bg-m-accent" />}
            </button>
          );
        })}
      </nav>

      <div className="p-3 border-t border-white/5">
        {me && (
          <div className="flex items-center gap-3 px-2 py-2">
            <div className="w-9 h-9 rounded-full bg-gradient-to-br from-cyan-500/30 to-cyan-700/20 border border-white/10 grid place-items-center text-[12px] text-m-text font-medium">
              {me.user.initials}
            </div>
            <div className="flex-1 min-w-0">
              <div className="text-[13px] text-m-text truncate">{me.user.name}</div>
              <div className="text-[11px] text-m-dim truncate font-mono">{me.user.telegram}</div>
            </div>
            <button onClick={onLogout} title="Выйти"
              className="w-9 h-9 grid place-items-center rounded-lg text-m-mute hover:text-m-text hover:bg-white/5 transition">
              <Icon name="logout" size={16} />
            </button>
          </div>
        )}
      </div>
    </aside>
  );
}

// ============================================
// BOTTOM NAV (mobile)
// ============================================
function BottomNav({ route, onRoute, onMore }) {
  return (
    <nav className="md:hidden fixed bottom-0 inset-x-0 z-50 bg-m-bg2/95 backdrop-blur-xl border-t border-white/5 pb-safe">
      <div className="grid grid-cols-5 px-1">
        {MOBILE_NAV.map(id => {
          const item = NAV.find(n => n.id === id);
          const active = route === id;
          return (
            <button key={id} onClick={() => onRoute(id)}
              className={`flex flex-col items-center gap-0.5 py-2.5 transition
                ${active ? 'text-m-accent' : 'text-m-mute hover:text-m-text'}`}>
              <Icon name={item.icon} size={20} />
              <span className="text-[10px] font-medium tracking-tight">{item.shortLabel}</span>
            </button>
          );
        })}
        <button onClick={onMore}
          className="flex flex-col items-center gap-0.5 py-2.5 text-m-mute hover:text-m-text transition">
          <Icon name="menu" size={20} />
          <span className="text-[10px] font-medium tracking-tight">Ещё</span>
        </button>
      </div>
    </nav>
  );
}

// ============================================
// MOBILE TOP BAR
// ============================================
function MobileHeader({ me, onMore }) {
  return (
    <header className="md:hidden flex items-center justify-between px-4 py-3 bg-m-bg/90 backdrop-blur-xl sticky top-0 z-40 border-b border-white/5">
      <Logo size={24} />
      <div className="flex items-center gap-2">
        <button className="relative w-9 h-9 rounded-xl bg-white/[0.04] border border-white/5 grid place-items-center text-m-text">
          <Icon name="bell" size={16} />
          <span className="absolute top-2 right-2 w-1.5 h-1.5 rounded-full bg-m-accent" />
        </button>
        {me && (
          <button onClick={onMore} className="w-9 h-9 rounded-full bg-gradient-to-br from-cyan-500/30 to-cyan-700/20 border border-white/10 grid place-items-center text-[11px] text-m-text font-medium">
            {me.user.initials}
          </button>
        )}
      </div>
    </header>
  );
}

// ============================================
// "MORE" SHEET — mobile-only side links
// ============================================
function MoreSheet({ open, onClose, onRoute, me, onLogout }) {
  if (!open) return null;
  const items = NAV.filter(n => !MOBILE_NAV.includes(n.id));
  return (
    <div className="md:hidden fixed inset-0 z-[100] fade-in">
      <div className="absolute inset-0 bg-black/70 backdrop-blur-md" onClick={onClose} />
      <div className="absolute bottom-0 inset-x-0 bg-m-card rounded-t-2xl border-t border-white/8 sheet-in pb-safe">
        <div className="flex justify-center pt-2 pb-1">
          <div className="w-10 h-1 rounded-full bg-white/15" />
        </div>
        {me && (
          <div className="flex items-center gap-3 px-5 py-4 border-b border-white/5">
            <div className="w-11 h-11 rounded-full bg-gradient-to-br from-cyan-500/30 to-cyan-700/20 border border-white/10 grid place-items-center text-[13px] text-m-text font-medium">
              {me.user.initials}
            </div>
            <div className="flex-1 min-w-0">
              <div className="text-[14px] text-m-text">{me.user.name}</div>
              <div className="text-[11px] text-m-dim font-mono">{me.user.telegram}</div>
            </div>
          </div>
        )}
        <div className="p-2">
          {items.map(item => (
            <button key={item.id} onClick={() => { onRoute(item.id); onClose(); }}
              className="w-full flex items-center gap-3 px-3 h-12 rounded-xl text-[14px] text-m-text hover:bg-white/[0.04] transition">
              <div className="w-9 h-9 rounded-xl bg-m-bg2 border border-white/5 grid place-items-center">
                <Icon name={item.icon} size={18} className="text-m-mute" />
              </div>
              {item.label}
              <Icon name="chevR" size={16} className="ml-auto text-m-dim" />
            </button>
          ))}
          <div className="my-2 h-px bg-white/5" />
          <button onClick={onLogout}
            className="w-full flex items-center gap-3 px-3 h-12 rounded-xl text-[14px] text-m-err hover:bg-m-err/10 transition">
            <div className="w-9 h-9 rounded-xl bg-m-err/10 border border-m-err/20 grid place-items-center">
              <Icon name="logout" size={18} />
            </div>
            Выйти
          </button>
        </div>
      </div>
    </div>
  );
}

// ============================================
// APP
// ============================================
function App() {
  const [authed, setAuthed] = useState(MOCK);   // MOCK: auto-authed
  const [booted, setBooted] = useState(MOCK);    // auth check finished?
  const [route, setRoute] = useState('dashboard');
  const [me, setMe] = useState(null);
  const [moreOpen, setMoreOpen] = useState(false);
  const [refreshKey, setRefreshKey] = useState(0);
  const toast = useToast();

  // Auth bootstrap: WebApp initData > ?token= OTP > existing session cookie.
  useEffect(() => {
    if (MOCK) return;
    (async () => {
      const url = new URL(window.location.href);
      const token = url.searchParams.get('token');
      try {
        const tgInitData = window.Telegram?.WebApp?.initData;
        if (tgInitData) {
          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) throw new Error('initData auth failed');
          setAuthed(true);
        } else if (token) {
          await api('/login', { method: 'POST', body: { token } });
          url.searchParams.delete('token');
          window.history.replaceState({}, '', url.pathname + url.search);
          setAuthed(true);
        } else {
          await api('/whoami');
          setAuthed(true);
        }
      } catch (e) {
        setAuthed(false);
      } finally {
        setBooted(true);
      }
    })();
  }, []);

  // Load /me on auth
  const loadMe = useCallback(() => api('/me').then(setMe).catch(() => {}), []);
  useEffect(() => { if (authed) loadMe(); }, [authed, refreshKey, loadMe]);

  // Scroll to top on route change
  useEffect(() => { window.scrollTo({ top: 0, behavior: 'smooth' }); }, [route]);

  if (!booted) {
    return <div className="min-h-screen grid place-items-center bg-m-bg">
      <Spinner size={28} /></div>;
  }
  if (!authed) {
    return <LoginScreen onLogin={() => { setAuthed(true); setBooted(true); }} />;
  }

  const onRoute = (r) => { setRoute(r); setMoreOpen(false); };
  const onRefresh = () => setRefreshKey(k => k + 1);
  const logout = async () => {
    try { if (!MOCK) await api('/logout', { method: 'POST' }); } catch (e) {}
    setAuthed(false);
    toast.info('Вы вышли из аккаунта');
  };

  const ScreenComponent = ({
    dashboard:    <DashboardScreen   onRoute={onRoute} refreshKey={refreshKey} />,
    subscription: <SubscriptionScreen onRoute={onRoute} onRefresh={onRefresh} />,
    devices:      <DevicesScreen     onRefresh={onRefresh} />,
    traffic:      <TrafficScreen     onRefresh={onRefresh} />,
    payments:     <PaymentsScreen />,
    referral:     <ReferralScreen />,
    help:         <HelpScreen />,
  })[route] || <DashboardScreen onRoute={onRoute} refreshKey={refreshKey} />;

  return (
    <div className="min-h-screen flex bg-m-bg text-m-text">
      <Sidebar route={route} onRoute={onRoute} me={me} onLogout={logout} />
      <div className="flex-1 min-w-0 flex flex-col">
        <MobileHeader me={me} onMore={() => setMoreOpen(true)} />
        <main className="flex-1 px-4 md:px-8 py-5 md:py-7 pb-36 md:pb-10 max-w-[1200px] w-full mx-auto">
          {ScreenComponent}
        </main>
      </div>
      <BottomNav route={route} onRoute={onRoute} onMore={() => setMoreOpen(true)} />
      <MoreSheet open={moreOpen} onClose={() => setMoreOpen(false)} onRoute={onRoute} me={me} onLogout={logout} />
    </div>
  );
}

// ============================================
// MOUNT
// ============================================
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <ToastHost>
    <App />
  </ToastHost>
);
