/* Shell.jsx — sidebar + topbar layout */

const NAV_ITEMS = [
  { id: "overview",    label: "Огляд",       icon: "◉", group: "main" },
  { id: "stops",       label: "Зупинки",     icon: "📍", group: "main", badge: "1 247" },
  { id: "routes",      label: "Маршрути",    icon: "🛤",  group: "main", badge: "42" },
  { id: "monitoring",  label: "Моніторинг",  icon: "📡", group: "main", badgeKind: "bad", badge: "3" },
  { id: "analytics",   label: "Аналітика",   icon: "📊", group: "main" },
  { id: "history",     label: "Історія змін",icon: "🕓", group: "ops" },
  { id: "settings",    label: "Налаштування",icon: "⚙",  group: "ops" },
];

const ROLE_LABEL = { admin: "Адміністратор", engineer: "Інженер мережі", dispatcher: "Диспетчер" };

function Sidebar({ active, onNav, user, onLogout }) {
  const caps = user?.capabilities || {};
  const main = NAV_ITEMS.filter(n => n.group === "main");
  const ops  = NAV_ITEMS.filter(n => n.group === "ops").filter(item => {
    if (item.id === "settings") return !!caps.settings_write;
    return true;
  });
  const display = user?.actor || user?.name || "?";
  const initials = display.split(/[ @.]/).filter(Boolean).map(w => w[0]).join("").slice(0, 2).toUpperCase() || "?";

  return (
    <aside className="sidebar">
      {/* Logo */}
      <div className="sidebar-logo">
        <div className="sidebar-logo-mark">P</div>
        <div>
          <div className="sidebar-logo-name">passenger</div>
          <div className="sidebar-logo-sub">routes panel</div>
        </div>
      </div>

      {/* Nav */}
      <nav className="sidebar-nav">
        <div className="nav-section-label">Основне</div>
        {main.map(item => (
          <button key={item.id}
            className={"nav-item" + (active === item.id ? " active" : "")}
            onClick={() => onNav(item.id)}>
            <span className="nav-item-icon">{item.icon}</span>
            <span style={{ flex: 1 }}>{item.label}</span>
            {item.badge && (
              <span className={"nav-badge" + (item.badgeKind === "bad" ? " bad" : "")}>
                {item.badge}
              </span>
            )}
          </button>
        ))}

        <div className="nav-section-label" style={{ marginTop: 8 }}>Система</div>
        {ops.map(item => (
          <button key={item.id}
            className={"nav-item" + (active === item.id ? " active" : "")}
            onClick={() => onNav(item.id)}>
            <span className="nav-item-icon">{item.icon}</span>
            <span style={{ flex: 1 }}>{item.label}</span>
          </button>
        ))}
      </nav>

      {/* User */}
      <div className="sidebar-user">
        <div className="user-avatar">{initials}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="user-name" style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
            {user?.actor || user?.name}
          </div>
          <div className="user-role">{ROLE_LABEL[user?.role] || user?.role || ""}</div>
        </div>
        <button onClick={onLogout} title="Вийти" style={{
          border: "none", background: "transparent", cursor: "pointer",
          color: "rgba(255,255,255,0.4)", fontSize: 16, padding: 4,
          transition: "color 0.12s", flexShrink: 0,
        }}
          onMouseEnter={e => e.currentTarget.style.color = "rgba(255,255,255,0.8)"}
          onMouseLeave={e => e.currentTarget.style.color = "rgba(255,255,255,0.4)"}
        >⏻</button>
      </div>
    </aside>
  );
}

function AutoRefreshToggle() {
  const api = window.passengerApi;
  const [enabled, setEnabled] = React.useState(api ? api.getAutoRefresh() : true);
  const onClick = () => {
    const next = !enabled;
    setEnabled(next);
    api && api.setAutoRefresh(next);
  };
  return (
    <button
      onClick={onClick}
      title={enabled ? "Авто-оновлення увімкнено (30с / 60с)" : "Авто-оновлення вимкнено"}
      style={{
        display: "flex", alignItems: "center", gap: 6,
        padding: "5px 10px", borderRadius: "var(--radius-sm)",
        border: "1px solid var(--border)",
        background: enabled ? "var(--accent-soft)" : "var(--surface-2)",
        color: enabled ? "var(--accent)" : "var(--text-3)",
        fontSize: 12.5, cursor: "pointer", fontFamily: "inherit",
      }}>
      <span style={{ display: "inline-block", animation: enabled ? "spin 4s linear infinite" : "none" }}>⟳</span>
      <span>{enabled ? "Авто" : "Стоп"}</span>
    </button>
  );
}

function Topbar({ title, subtitle, actions, user }) {
  return (
    <header className="topbar">
      <div>
        <div className="topbar-title">{title}</div>
        {subtitle && <div className="topbar-sub">{subtitle}</div>}
      </div>
      <div className="topbar-actions" style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <button
          onClick={() => window.openPalette && window.openPalette()}
          style={{
            display: "flex", alignItems: "center", gap: 8,
            padding: "5px 12px", borderRadius: "var(--radius-sm)",
            border: "1px solid var(--border)", background: "var(--surface-2)",
            color: "var(--text-3)", fontSize: 13, cursor: "pointer",
            fontFamily: "inherit", minWidth: 160,
          }}>
          <span>🔍</span>
          <span style={{ flex: 1, textAlign: "left" }}>Пошук…</span>
          <kbd style={{ fontSize: 11, background: "var(--surface-3)", border: "1px solid var(--border)", padding: "1px 5px", borderRadius: 4, fontFamily: "monospace" }}>⌘K</kbd>
        </button>
        <AutoRefreshToggle />
        <div className="topbar-scope">
          <span>🏙</span>
          <span>Київ — основний</span>
          <span style={{ color: "var(--text-3)" }}>▾</span>
        </div>
        {actions}
      </div>
    </header>
  );
}

Object.assign(window, { Sidebar, Topbar, AutoRefreshToggle });
