/* Sidebar — Linear-esque navigation */

// JARVIS logo — hexagonal AI emblem used across the site (sidebar, overlay, chat avatars).
const JarvisLogo = ({ size = 16, pulse = false, glow = true }) => (
  <svg width={size} height={size} viewBox="0 0 40 40" style={{ display: "block", flexShrink: 0 }}>
    <defs>
      <linearGradient id="jv-grad" x1="0" y1="0" x2="1" y2="1">
        <stop offset="0%" stopColor="oklch(0.85 0.18 248)" />
        <stop offset="50%" stopColor="oklch(0.72 0.17 270)" />
        <stop offset="100%" stopColor="oklch(0.58 0.18 300)" />
      </linearGradient>
      <radialGradient id="jv-core" cx="50%" cy="50%" r="50%">
        <stop offset="0%" stopColor="oklch(0.98 0.04 250)" stopOpacity="1"/>
        <stop offset="60%" stopColor="oklch(0.78 0.18 250)" stopOpacity="0.9"/>
        <stop offset="100%" stopColor="oklch(0.55 0.18 270)" stopOpacity="0"/>
      </radialGradient>
      <filter id="jv-blur"><feGaussianBlur stdDeviation="1.2" /></filter>
    </defs>
    {/* Outer hexagon ring */}
    <polygon points="20,3 34,11 34,29 20,37 6,29 6,11"
             fill="none" stroke="url(#jv-grad)" strokeWidth="1.5"
             style={pulse ? { animation: "jv-rotate 12s linear infinite", transformOrigin: "center" } : null}/>
    {/* Inner hexagon */}
    <polygon points="20,9 29,14 29,26 20,31 11,26 11,14"
             fill="none" stroke="url(#jv-grad)" strokeWidth="1" opacity="0.5"/>
    {/* Core glow */}
    {glow && <circle cx="20" cy="20" r="9" fill="url(#jv-core)" filter="url(#jv-blur)"/>}
    {/* Core dot */}
    <circle cx="20" cy="20" r="3" fill="oklch(0.95 0.05 250)"
            style={pulse ? { animation: "jv-pulse 2s ease-in-out infinite" } : null}/>
    {/* Orbital marks */}
    <circle cx="20" cy="3" r="1.2" fill="oklch(0.85 0.18 248)"/>
    <circle cx="34" cy="29" r="1.2" fill="oklch(0.72 0.17 270)"/>
    <circle cx="6" cy="29" r="1.2" fill="oklch(0.58 0.18 300)"/>
  </svg>
);
window.JarvisLogo = JarvisLogo;

// Compute a count from a possibly-undefined global array
const _len = (arr) => (Array.isArray(arr) ? arr.length : 0);

// Build the nav with tags derived from real data (so the numbers stay coherent when arrays are empty).
const buildNav = () => {
  const picks      = _len(window.DAILY_PICKS) || _len(window.REAL_PICKS);
  const research   = _len(window.PRODUCTS);
  const alerts     = _len(window.ALERTS);
  const accounts   = _len(window.OPEN_ACCOUNTS);

  const tag = (n, tone) => (n > 0 ? { tag: String(n), tagTone: tone } : {});

  return [
    { kind: "section", title: "Pilotage" },
    { id: "dashboard", icon: "dashboard", label: "Dashboard" },

    { kind: "section", title: "Sourcing" },
    { id: "daily-picks", icon: "target",  label: "Picks du jour",          ...tag(picks, "accent") },
    { id: "research",    icon: "grid",    label: "Recherche de produits", ...tag(research) },
    { id: "asin",        icon: "box",     label: "Bibliothèque ASIN" },
    { id: "profit-calc", icon: "dollar",  label: "ProfitCalcPro",          tag: "PRO", tagTone: "accent" },
    { id: "landed-cost", icon: "truck",   label: "Landed Cost",             tag: "NEW", tagTone: "accent" },
    { id: "opportunity", icon: "target",  label: "OpportunityFinder" },
    { id: "team-board",  icon: "layers",  label: "TeamBoard" },
    { id: "supplier-cmp",icon: "flask",   label: "Comparatif fournisseurs" },
    { id: "alerts",      icon: "bell",    label: "Alertes sourcing",       ...tag(alerts, "red") },

    { kind: "section", title: "Intelligence" },
    { id: "jarvis",      icon: "jarvis",  label: "JARVIS",                  tag: "IA",  tagTone: "accent" },
    { id: "messages",    icon: "mail",    label: "Messages équipe",          tag: "LIVE",tagTone: "accent" },

    { kind: "section", title: "Fournisseurs" },
    { id: "supplier",    icon: "users",   label: "Annuaire" },
    { id: "catalogs",    icon: "book",    label: "Catalogues" },
    { id: "open-acct",   icon: "dollar",  label: "Comptes ouverts",         ...tag(accounts, "amber") },

  { kind: "section", title: "Finance & Ops" },
  { id: "finance",     icon: "chart",   label: "Finances" },
  { id: "expenses",    icon: "receipt", label: "Dépenses & Impôts",       tag: "QC",  tagTone: "accent" },
  { id: "shipments",   icon: "truck",   label: "Expéditions FBA" },
  { id: "returns",     icon: "refresh", label: "Retours" },
  { id: "prep",        icon: "cube",    label: "Prep Center" },
  { id: "import",      icon: "upload",  label: "Import" },

  { kind: "section", title: "Système" },
  { id: "calendar",    icon: "calendar",label: "Calendrier" },
  { id: "resources",   icon: "book",    label: "Ressources" },
  { id: "workshop",    icon: "wrench",  label: "Atelier SQL" },
  { id: "email",       icon: "mail",    label: "Daily Digest" },
  { id: "settings",    icon: "shield",  label: "Paramètres & 2FA" },
  ];
};

const Sidebar = ({ page, onNavigate, collapsed, onToggle, onOpenCmdK }) => {
  const [me] = useCurrentUser();
  const NAV_DYN = buildNav();
  return (
    <aside className="sidebar">
      <div className="sidebar-head">
        <div className="logo">KC</div>
        <div className="logo-wrap">
          <span className="name">KCC Holdings</span>
          <span className="org">Portail admin · v3.0</span>
        </div>
        <button className="icon-btn" onClick={onToggle} title={collapsed ? "Ouvrir" : "Réduire"} style={{ marginLeft: "auto" }}>
          <Icon name="panelLeft" />
        </button>
      </div>

      <div className="sidebar-search">
        <button className="search-pill" onClick={onOpenCmdK}>
          <Icon name="search" size={13} />
          <span>Rechercher ou commander…</span>
          <kbd>⌘K</kbd>
        </button>
      </div>

      <nav className="nav">
        {NAV_DYN.map((item, i) => {
          if (item.kind === "section") {
            return <div key={i} className="nav-section-title">{item.title}</div>;
          }
          const active = page === item.id;
          return (
            <div key={item.id}
                 className="nav-item"
                 data-active={active}
                 onClick={() => { onNavigate(item.id); const app = document.querySelector('.app'); if (app && app.getAttribute('data-mobile-nav') === 'open') app.setAttribute('data-mobile-nav', 'closed'); }}
                 title={item.label}>
              <span className="nav-icon">{item.icon === "jarvis" ? <JarvisLogo size={15}/> : <Icon name={item.icon} size={15} />}</span>
              <span className="nav-label">{item.label}</span>
              {item.tag && <span className="nav-tag" data-tone={item.tagTone}>{item.tag}</span>}
            </div>
          );
        })}
      </nav>

      <div className="sidebar-footer">
        <Avatar user={me.id} />
        <div className="sidebar-footer-meta">
          <span className="who">{me.name}</span>
          <span className="role">{me.role.split(" · ")[0]} · {me.id}@kcc.ca</span>
        </div>
      </div>
    </aside>
  );
};

window.Sidebar = Sidebar;
