// =======================================================================
// MariusVPN Franchise — App shell (auth, sidebar, router).
// =======================================================================

const { frApi } = window.FR_API;

function FrShell() {
  const [me, setMe]       = React.useState(null);
  const [booted, setBooted] = React.useState(false);
  const [tab, setTab]     = React.useState('dashboard');

  React.useEffect(() => {
    (async () => {
      // Telegram Mini App: if opened inside Telegram, auth via initData.
      const tg = window.Telegram && window.Telegram.WebApp;
      if (tg) { try { tg.ready(); tg.expand(); } catch (e) {} }
      if (tg && tg.initData) {
        try {
          await fetch('/api/tg/franchise-auth', {
            method: 'POST', credentials: 'include',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ init_data: tg.initData }),
          });
        } catch (e) {}
      }
      try { setMe(await frApi('/whoami')); } catch (e) {}
      setBooted(true);
    })();
  }, []);

  if (!booted) return <div className="min-h-screen flex items-center justify-center text-m-mute"><Spinner/></div>;
  if (!me)     return <FrLogin onLogin={(m) => setMe(m)}/>;

  return <FrApp me={me} onLogout={() => setMe(null)} tab={tab} setTab={setTab}/>;
}

const NAV = [
  { id: 'dashboard', label: 'Дашборд',   icon: ICONS.dashboard },
  { id: 'users',     label: 'Пользователи', icon: ICONS.users },
  { id: 'broadcast', label: 'Рассылка',  icon: ICONS.broadcast },
  { id: 'settings',  label: 'Настройки', icon: ICONS.settings },
  { id: 'payouts',   label: 'Выплаты',   icon: ICONS.wallet },
];

function FrApp({ me, onLogout, tab, setTab }) {
  const t = useToast();

  const logout = async () => {
    try { await frApi('/logout', { method: 'POST' }); } catch (e) {}
    onLogout();
  };

  return (
    <div className="min-h-screen grid-bg flex">
      {/* sidebar */}
      <aside className="hidden md:flex w-[240px] shrink-0 flex-col border-r border-m-line bg-m-bg2/40 backdrop-blur-sm sticky top-0 h-screen">
        <div className="px-5 py-5 border-b border-m-line">
          <div className="flex items-center gap-3">
            <div className="h-10 w-10 rounded-xl bg-m-accent/15 border border-m-accent/30 flex items-center justify-center text-m-accent">
              <Icon d={ICONS.shield} size={20}/>
            </div>
            <div>
              <div className="text-[15px] font-bold leading-none">{me.franchise_name || 'VPN'}</div>
              <div className="text-[11px] text-m-mute mt-1">Панель управления</div>
            </div>
          </div>
        </div>

        <nav className="flex-1 px-3 py-4 flex flex-col gap-1">
          {NAV.map(n => (
            <button
              key={n.id}
              onClick={() => setTab(n.id)}
              data-screen-label={n.label}
              className={
                'group flex items-center gap-3 px-3 py-2.5 rounded-xl transition text-sm font-medium ' +
                (tab === n.id
                  ? 'bg-m-accent/12 text-m-accent shadow-[inset_0_0_0_1px_rgba(34,211,238,0.20)]'
                  : 'text-m-mute hover:text-m-text hover:bg-white/[0.04]')
              }
            >
              <Icon d={n.icon} size={16}/>
              <span className="flex-1 text-left">{n.label}</span>
            </button>
          ))}
        </nav>

        <div className="px-3 pb-3 pt-2 border-t border-m-line">
          <div className="px-3 py-2.5 mb-1.5">
            <div className="text-xs text-m-mute">Франшиза</div>
            <div className="text-sm font-semibold truncate">{me.franchise_name}</div>
            <div className="text-[11px] text-m-dim font-mono mt-0.5">{me.bot_username}</div>
          </div>
          <button onClick={logout} className="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm text-m-mute hover:text-m-err hover:bg-m-err/8 transition">
            <Icon d={ICONS.logout} size={16}/> Выйти
          </button>
        </div>
      </aside>

      {/* main */}
      <main className="flex-1 min-w-0 flex flex-col">
        {/* mobile topbar */}
        <div className="md:hidden flex items-center justify-between px-4 h-14 border-b border-m-line bg-m-bg2/60 backdrop-blur sticky top-0 z-20">
          <div className="flex items-center gap-2.5">
            <div className="h-8 w-8 rounded-lg bg-m-accent/15 border border-m-accent/30 flex items-center justify-center text-m-accent">
              <Icon d={ICONS.shield} size={16}/>
            </div>
            <div className="text-sm font-bold">{me.franchise_name || 'VPN'}</div>
          </div>
          <Select value={tab} onChange={e => setTab(e.target.value)} className="!w-[180px] !h-9">
            {NAV.map(n => <option key={n.id} value={n.id}>{n.label}</option>)}
          </Select>
        </div>

        <div className="flex-1 p-6 md:p-8 max-w-[1400px] w-full">
          {tab === 'dashboard' && <FrDashboard goto={setTab} openWithdraw={() => setTab('payouts')}/>}
          {tab === 'users'     && <FrUsers/>}
          {tab === 'broadcast' && <FrBroadcast/>}
          {tab === 'settings'  && <FrSettings/>}
          {tab === 'payouts'   && <FrPayouts/>}
        </div>
      </main>
    </div>
  );
}

// --------------- Mount ---------------------------------------------------

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <ToastProvider>
    <FrShell/>
  </ToastProvider>
);
