

const { useState: useStateA, useEffect: useEffectA, useMemo: useMemoA } = React;

function useAuth() {
  const [user, setUser] = useStateA(null);   
  const [checked, setChecked] = useStateA(false);
  useEffectA(() => {
    fetch('/api/auth/me')
      .then((r) => {
        if (r.ok) return r.json();
        
        if (r.status === 404 || r.status === 501) return { user: "dev", __dev: true };
        return null;
      })
      .then((d) => {
        const u = d ? d.user : "";
        setUser(u);
        if (u && !d.__dev) { Live.bootstrap(); Live.connect(); }
      })
      .catch(() => setUser("dev"))
      .finally(() => setChecked(true));
  }, []);
  return { user, checked, setUser };
}

function App() {
  const { user, checked, setUser } = useAuth();

  if (!checked) {
    return (
      <div style={{ height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--bg-deep)' }}>
        <span style={{ color: 'var(--ink-4)', fontSize: 14 }}>…</span>
      </div>
    );
  }

  if (!user) {
    return <LoginScreen onLogin={(u) => { setUser(u); Live.bootstrap(); Live.connect(); }} />;
  }

  return <AuthedApp user={user} onLogout={() => setUser("")} />;
}

function AuthedApp({ user, onLogout }) {
  const handleLogout = async () => {
    await fetch('/api/auth/logout', { method: 'POST' });
    onLogout();
  };

  const instances = useLiveInstances();
  const liveStatus = useLiveStatus();
  const [toasts, dismissToast] = useToasts();

  
  
  const [extraCodes, setExtraCodes] = useStateA([]);
  const codes = useMemoA(() => {
    const set = new Set(extraCodes);
    instances.forEach((i) => { if (i.code) set.add(i.code); });
    return [...set];
  }, [instances, extraCodes]);

  const [selected, setSelected] = useStateA(new Set());
  const [filterCode, setFilterCode] = useStateA(null);
  const [filterStatus, setFilterStatus] = useStateA(null);
  const [screen, setScreen] = useStateA("scheduler");
  const [confirm, setConfirm] = useStateA(null);
  const [tzSync, setTzSync] = useStateA(false);

  const colorForCode = useMemoA(() => makeColorLookup(codes), [codes]);

  
  const codeFolders = [];
  const distinctCodes = codes.length;

  
  
  const onLaunch = (id) => Live.control([id], "launch");
  const onStop   = (id) => Live.control([id], "stop");
  const onReset  = (id) => setConfirm({
    title: "Reset устройства",
    message: `Сбросить устройство [${id}]? Будет полная переинициализация VMOS (данные стираются, IP меняется).`,
    confirmLabel: "Reset",
    danger: true,
    onConfirm: () => Live.control([id], "reset"),
  });
  const onSelectFolder = (code) => { setScreen("instances"); setFilterCode(code); };
  const onSidebarChange = (key) => { setScreen(key); setFilterCode(null); };
  const onCreateCode = (name) => setExtraCodes(prev => prev.includes(name) ? prev : [...prev, name]);
  const askConfirm = (opts) => setConfirm(opts);

  return (
    <CodesContext.Provider value={{ codes, colorForCode }}>
      <div className="app" data-density="comfortable" data-sidebar="labels">
        <Sidebar
          active={screen}
          onChange={onSidebarChange}
          instancesCount={instances.length}
          sidebarStyle="labels"
          codeFolders={codeFolders}
          codeStats={{ distinct: distinctCodes }}
          onSelectFolder={onSelectFolder}
          selectedCode={filterCode}
          liveStatus={liveStatus}
          user={user}
          onLogout={handleLogout}
        />

        {screen === "scheduler" && (
          <SchedulerScreen codes={codes} instances={instances}/>
        )}
        {screen === "instances" && (
          <InstancesScreen
            instances={instances}
            codes={codes}
            codeFolders={codeFolders}
            density="comfortable"
            tableZebra={false}
            selected={selected} setSelected={setSelected}
            filterCode={filterCode} setFilterCode={setFilterCode}
            filterStatus={filterStatus} setFilterStatus={setFilterStatus}
            onLaunch={onLaunch} onStop={onStop} onReset={onReset}
            askConfirm={askConfirm}
          />
        )}
        {screen === "refresher" && <RefresherScreen instances={instances}/>}
        {screen === "codes" && <MapCodesScreen instances={instances} codes={codes} onCreateCode={onCreateCode}/>}
        {screen === "stats" && <StatsScreen instances={instances} codes={codes} codeFolders={codeFolders} tzSync={tzSync} onTzSyncChange={setTzSync}/>}

        <ConfirmModal
          open={!!confirm}
          onClose={() => setConfirm(null)}
          onConfirm={() => confirm?.onConfirm?.()}
          title={confirm?.title}
          message={confirm?.message}
          summary={confirm?.summary}
          confirmLabel={confirm?.confirmLabel}
          danger={confirm?.danger}
        />

        <ToastStack toasts={toasts} onDismiss={dismissToast} />
      </div>
    </CodesContext.Provider>
  );
}

function ToastStack({ toasts, onDismiss }) {
  if (!toasts.length) return null;
  const color = (lvl) => lvl === "bad" ? "var(--bad)" : lvl === "ok" ? "var(--ok)" : "var(--warn)";
  return (
    <div style={{
      position: 'fixed', right: 20, bottom: 20, zIndex: 200,
      display: 'flex', flexDirection: 'column', gap: 9, maxWidth: 420,
    }}>
      {toasts.map((t) => (
        <div key={t.id} className="anim-pop" style={{
          background: 'var(--card)', border: '1px solid var(--line-strong)',
          borderLeft: `3px solid ${color(t.level)}`, borderRadius: 8,
          padding: '11px 13px', boxShadow: '0 8px 24px rgba(0,0,0,.12)',
          display: 'flex', alignItems: 'flex-start', gap: 10,
        }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13.5, color: 'var(--ink)' }}>{t.message}</div>
            {t.pads && t.pads.length > 0 && (
              <div className="mono" style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 3,
                                             overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {t.pads.join(", ")}
              </div>
            )}
          </div>
          <button className="icon-btn" style={{ width: 22, height: 22 }} onClick={() => onDismiss(t.id)}>
            <I.X size={12}/>
          </button>
        </div>
      ))}
    </div>
  );
}

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