// DataLoop Cabinet — shell + routing
const { useState: useStateCab, useEffect: useEffectCab } = React;

// Curated accent palettes (mirror the landing page)
const ACCENT_INK_CAB = {
  "#ff5b2e": "#1a0a04",
  "#c9f24a": "#0e1602",
  "#38e8d6": "#022119",
  "#ff4dc2": "#1f0414",
};
const ACCENT_NAMES_CAB = {
  "#ff5b2e": "коралл",
  "#c9f24a": "лайм",
  "#38e8d6": "циан",
  "#ff4dc2": "маджента",
};
const ACCENT_HEXES_CAB = Object.keys(ACCENT_INK_CAB);

const DEFAULTS_CAB = /*EDITMODE-BEGIN*/{
  "direction": "a",
  "accent": "#ff5b2e",
  "section": "overview",
  "env": "live"
}/*EDITMODE-END*/;

const NAV = [
  { id: "overview", label: "Обзор", icon: "home" },
  { id: "keys",     label: "API ключи", icon: "key", badge: "4" },
  { id: "logs",     label: "Логи запросов", icon: "logs" },
  { id: "billing",  label: "Биллинг", icon: "billing" },
  { id: "team",     label: "Команда", icon: "team" },
  { id: "settings", label: "Настройки", icon: "settings" },
];

const CRUMBS = {
  overview: "Обзор",
  keys: "API ключи",
  logs: "Логи запросов",
  billing: "Биллинг",
  team: "Команда",
  settings: "Настройки",
};

function CabinetApp() {
  const [t, setTweak] = useTweaks(DEFAULTS_CAB);
  const [section, setSection] = useStateCab(t.section || "overview");
  const [env, setEnv] = useStateCab(t.env || "live");
  const [navOpen, setNavOpen] = useStateCab(false);

  useEffectCab(() => {
    const ink = ACCENT_INK_CAB[t.accent] || "#1a0a04";
    document.documentElement.style.setProperty("--accent", t.accent);
    document.documentElement.style.setProperty("--accent-ink", ink);
  }, [t.accent]);

  useEffectCab(() => {
    document.body.className = t.direction === "b" ? "dir-b" : "dir-a";
  }, [t.direction]);

  // lock body scroll while mobile drawer open
  useEffectCab(() => {
    document.body.style.overflow = navOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [navOpen]);

  // auto-close drawer when section changes on mobile
  function gotoSection(id) {
    setSection(id);
    setNavOpen(false);
  }

  const D = window.__CAB;

  function renderView() {
    switch (section) {
      case "overview": return <ViewOverview goto={gotoSection} />;
      case "keys":     return <ViewKeys />;
      case "logs":     return <ViewLogs />;
      case "billing":  return <ViewBilling />;
      case "team":     return <ViewTeam />;
      case "settings": return <ViewSettings />;
      default:         return <ViewOverview goto={gotoSection} />;
    }
  }

  return (
    <div className={`cab-app ${navOpen ? "nav-open" : ""}`}>
      {/* SIDEBAR */}
      <aside className="cab-sidebar">
        <div className="cab-sb-head">
          <a href="index.html" className="logo" style={{ color: "var(--ink)" }}>
            <svg width="26" height="26" viewBox="0 0 32 32" fill="none" aria-hidden="true">
              <rect x="2" y="2" width="28" height="28" rx="6" fill="currentColor" />
              <path d="M10 11 h6 a5 5 0 1 1 0 10 h-6 z M10 11 v10 M19.5 11.5 L13 21"
                stroke="var(--accent)" strokeWidth="2.4" strokeLinecap="square" fill="none" />
            </svg>
            <span>dataloop<span className="dot">.</span>ru</span>
          </a>
          <div className="cab-env">
            <span className={`cab-env-opt ${env === "test" ? "active" : ""}`} onClick={() => setEnv("test")}>test</span>
            <span className={`cab-env-opt ${env === "live" ? "active" : ""}`} onClick={() => setEnv("live")}>live</span>
          </div>
          <button className="cab-sb-close" aria-label="Закрыть меню" onClick={() => setNavOpen(false)}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
              <path d="M6 6l12 12M18 6L6 18" />
            </svg>
          </button>
        </div>

        <nav className="cab-nav">
          <div className="cab-nav-section">Главное</div>
          {NAV.slice(0, 4).map((n) => (
            <div key={n.id} className={`cab-nav-item ${section === n.id ? "active" : ""}`} onClick={() => gotoSection(n.id)}>
              <Icon name={n.icon} size={17} />
              <span>{n.label}</span>
              {n.badge && <span className="cab-nav-badge">{n.badge}</span>}
            </div>
          ))}
          <div className="cab-nav-section">Аккаунт</div>
          {NAV.slice(4).map((n) => (
            <div key={n.id} className={`cab-nav-item ${section === n.id ? "active" : ""}`} onClick={() => gotoSection(n.id)}>
              <Icon name={n.icon} size={17} />
              <span>{n.label}</span>
            </div>
          ))}
          <div className="cab-nav-section">Ресурсы</div>
          <a className="cab-nav-item" href="#" target="_blank" rel="noreferrer">
            <Icon name="docs" size={17} />
            <span>Документация ↗</span>
          </a>
          <a className="cab-nav-item" href="index.html">
            <Icon name="arrow-right" size={17} />
            <span>На главную</span>
          </a>
        </nav>

        <div className="cab-sb-foot">
          <div className="cab-avatar">{D.user.initials}</div>
          <div className="cab-userblock">
            <div className="cab-username">{D.user.name}</div>
            <div className="cab-userrole">{D.user.role}</div>
          </div>
          <button className="cab-icon-btn" title="Выйти"><Icon name="logout" size={14} /></button>
        </div>
      </aside>

      {/* MAIN */}
      <div className="cab-main">
        <div className="cab-topbar">
          <button className="cab-burger" aria-label="Меню" onClick={() => setNavOpen(true)}>
            <span></span><span></span><span></span>
          </button>
          <div className="cab-crumbs">
            <span className="cab-crumb-root">Кабинет</span>
            <span className="cab-crumb-sep">/</span>
            <strong>{CRUMBS[section] || section}</strong>
          </div>
          <div className="cab-search">
            <Icon name="search" size={14} />
            <input placeholder="Поиск по логам, ключам, эндпоинтам…" />
            <span className="kbd">⌘K</span>
          </div>
          <div className="cab-top-status">
            <span className="status-dot"></span>
            <span>API · 27 мс</span>
          </div>
          <button className="cab-icon-btn" style={{ width: 34, height: 34, position: "relative" }} title="Уведомления">
            <Icon name="bell" size={16} />
            <span style={{ position: "absolute", top: 7, right: 8, width: 6, height: 6, borderRadius: "50%", background: "var(--accent)" }}></span>
          </button>
        </div>

        <div className="cab-page">
          {renderView()}
        </div>
      </div>

      {/* Mobile scrim */}
      <div className="cab-scrim" onClick={() => setNavOpen(false)} />

      {/* Tweaks panel */}
      <TweaksPanel title="Tweaks">
        <TweakSection label="Направление">
          <TweakRadio
            label="Тема"
            value={t.direction}
            onChange={(v) => setTweak("direction", v)}
            options={[
              { value: "a", label: "Светлое" },
              { value: "b", label: "Тёмное" },
            ]}
          />
        </TweakSection>
        <TweakSection label="Акцент">
          <TweakColor
            label="Цвет"
            value={t.accent}
            onChange={(v) => setTweak("accent", v)}
            options={ACCENT_HEXES_CAB}
          />
          <div style={{ fontSize: 11, color: "#888", fontFamily: "var(--mono)", marginTop: -4, marginLeft: 96 }}>
            {ACCENT_NAMES_CAB[t.accent] || ""}
          </div>
        </TweakSection>
        <TweakSection label="Раздел">
          <TweakSelect
            label="Перейти"
            value={section}
            onChange={(v) => gotoSection(v)}
            options={NAV.map((n) => ({ value: n.id, label: n.label }))}
          />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

const rootCab = ReactDOM.createRoot(document.getElementById("root"));
rootCab.render(<CabinetApp />);
