/* ============================================
   SHARED COMPONENTS — Sidebar, Topbar, Card primitives
   ============================================ */
const { useState, useEffect, useRef, useMemo, useCallback } = React;
// Expose hooks globally so screen files can use bare names
Object.assign(window, {
  useState: React.useState,
  useEffect: React.useEffect,
  useRef: React.useRef,
  useMemo: React.useMemo,
  useCallback: React.useCallback
});

/* ----- NAV STRUCTURE ----- */
const NAV = [
{ key: "workspace", label: "Workspace", icon: "Workspace" },
{ key: "chat-history", label: "Chat History", icon: "History" },
{
  key: "content",
  label: "Content Management",
  icon: "Content",
  children: [
  { key: "knowledge", label: "Knowledge Management" },
  { key: "ingestion", label: "Ingestion Dashboard" },
  { key: "inspector", label: "Document Inspector" }]

},
{
  key: "governance",
  label: "Governance",
  icon: "Governance",
  children: [
  { key: "analytics", label: "Analytics & Audit" },
  { key: "cost", label: "Cost Tracking" },
  { key: "system-health", label: "System Health" },
  { key: "users", label: "User Management" },
  { key: "prompt-tuning", label: "System Configuration" }]

}];


const SCREEN_META = {
  "login": { title: "Sign In", crumbs: ["Account", "Sign In"] },
  "profile": { title: "User Profile", crumbs: ["Account", "Profile"] },
  "workspace": { title: "Workspace", crumbs: ["Workspace"] },
  "chat-history": { title: "Chat History", crumbs: ["Chat History"] },
  "knowledge": { title: "Knowledge Management", crumbs: ["Content Management", "Knowledge"] },
  "ingestion": { title: "Ingestion Dashboard", crumbs: ["Content Management", "Ingestion"] },
  "inspector": { title: "Document Inspector", crumbs: ["Content Management", "Inspector"] },
  "analytics": { title: "Analytics & Audit", crumbs: ["Governance", "Analytics"] },
  "cost": { title: "Cost Tracking", crumbs: ["Governance", "Cost"] },
  "system-health": { title: "System Health", crumbs: ["Governance", "System Health"] },
  "users": { title: "User Management", crumbs: ["Governance", "Users"] },
  "prompt-tuning": { title: "System Configuration", crumbs: ["Governance", "System Configuration"] }
};

/* ----- SIDEBAR ----- */
function _initials(name) {
  if (!name) return "?";
  return name.trim().split(/\s+/).map(s => s[0] || "").slice(0, 2).join("").toUpperCase();
}

function Sidebar({ active, onNavigate, user, onLogout }) {
  const [expanded, setExpanded] = useState(() => {
    // auto-expand parent of active route
    const init = new Set(["content", "governance"]);
    return init;
  });

  const toggle = (key) => {
    setExpanded((prev) => {
      const next = new Set(prev);
      if (next.has(key)) next.delete(key);else next.add(key);
      return next;
    });
  };

  return (
    <aside className="sidebar">
      <div className="sidebar__brand">
        <div className="sidebar__logo">ORS</div>
        <div className="sidebar__title">
          <span className="sidebar__title-line1">BHUMI JATI POWER</span>
          <span className="sidebar__title-line2">Operation Reference System</span>
        </div>
      </div>

      <nav className="sidebar__nav">
        <div className="sidebar__section-label">Main</div>
        {NAV.map((item) => {
          const Icn = Icons[item.icon];
          if (!item.children) {
            return (
              <button
                key={item.key}
                className={`nav-item ${active === item.key ? "is-active" : ""}`}
                onClick={() => onNavigate(item.key)}>
                
                <span className="nav-icon"><Icn /></span>
                <span>{item.label}</span>
              </button>);

          }
          const isOpen = expanded.has(item.key);
          const childActive = item.children.some((c) => c.key === active);
          return (
            <React.Fragment key={item.key}>
              <button
                className={`nav-item ${childActive ? "is-active" : ""} ${isOpen ? "is-expanded" : ""}`}
                onClick={() => toggle(item.key)}>
                
                <span className="nav-icon"><Icn /></span>
                <span>{item.label}</span>
                <span className="nav-chev"><Icons.Chevron size={14} /></span>
              </button>
              {isOpen &&
              <div className="nav-sub">
                  {item.children.map((c) =>
                <button
                  key={c.key}
                  className={`nav-item ${active === c.key ? "is-active" : ""}`}
                  onClick={() => onNavigate(c.key)}>
                  
                      <span>{c.label}</span>
                    </button>
                )}
                </div>
              }
            </React.Fragment>);

        })}
      </nav>

      <div className="sidebar__profile" onClick={() => onNavigate("profile")} style={{ cursor: "pointer" }}>
        <div className="avatar">{_initials(user && user.full_name)}</div>
        <div className="sidebar__profile-info">
          <div className="sidebar__profile-name">{user ? user.full_name : "Signed out"}</div>
          <div className="sidebar__profile-role">{user ? user.role.toUpperCase() : "—"}</div>
        </div>
        <button
          className="sidebar__profile-menu"
          title="Sign out"
          onClick={(e) => { e.stopPropagation(); onLogout && onLogout(); }}>
          <Icons.Lock size={16} />
        </button>
      </div>
    </aside>);

}

/* ----- TOPBAR ----- */
function Topbar({ screen, rightSlot, onNavigate }) {
  const meta = SCREEN_META[screen] || { crumbs: [screen] };
  return (
    <div className="topbar">
      <div className="topbar__crumbs">
        {meta.crumbs.map((c, i) =>
        <React.Fragment key={i}>
            {i > 0 && <span className="crumb-sep">/</span>}
            <span className={i === meta.crumbs.length - 1 ? "crumb-current" : ""}>{c}</span>
          </React.Fragment>
        )}
      </div>
      <div className="topbar__actions">
        {rightSlot}
        <div className="topbar__search">
          <Icons.Search />
          <input placeholder="Search documents, chats, IDs…" />
          <span className="mono text-xs muted" style={{ padding: "1px 5px", border: "1px solid var(--ink-200)", borderRadius: 3 }}>⌘K</span>
        </div>
        <button className="topbar__icon-btn" title="Notifications"><Icons.Bell /></button>
        <button className="topbar__icon-btn" title="Help"><Icons.Help /></button>
      </div>
    </div>);

}

/* ----- SHELL ----- */
function Shell({ screen, onNavigate, children, topbarRight, user, onLogout }) {
  return (
    <div className="app">
      <Sidebar active={screen} onNavigate={onNavigate} user={user} onLogout={onLogout} />
      <div className="main">
        <Topbar screen={screen} rightSlot={topbarRight} onNavigate={onNavigate} />
        <div className="content">
          {children}
        </div>
      </div>
    </div>);

}

/* ----- Reusable bits ----- */
function Card({ title, subtitle, right, children, bodyFlush, style, className = "" }) {
  return (
    <div className={`card ${className}`} style={style}>
      {(title || right) &&
      <div className="card__header">
          <div>
            {title && <h3 className="card__title">{title}</h3>}
            {subtitle && <p className="card__subtitle">{subtitle}</p>}
          </div>
          {right}
        </div>
      }
      <div className={`card__body ${bodyFlush ? "card__body--flush" : ""}`}>{children}</div>
    </div>);

}

function Badge({ kind = "neutral", children, dot = true }) {
  return (
    <span className={`badge badge--${kind}`}>
      {dot && <span className="dot" />}
      {children}
    </span>);

}

function Checkbox({ checked, onChange }) {
  return (
    <button
      className={`checkbox ${checked ? "is-checked" : ""}`}
      onClick={() => onChange && onChange(!checked)}
      type="button"
      aria-checked={checked}
      role="checkbox" />);


}

function Toggle({ on, onChange }) {
  return (
    <button
      className={`toggle ${on ? "is-on" : ""}`}
      onClick={() => onChange && onChange(!on)}
      type="button"
      aria-checked={on}
      role="switch" />);


}

function Progress({ value, kind, large }) {
  const cls = `progress ${large === "xl" ? "progress--xl" : large === "lg" ? "progress--lg" : ""} ${kind ? "progress--" + kind : ""}`;
  return (
    <div className={cls}>
      <div className="progress__fill" style={{ width: `${Math.min(100, Math.max(0, value))}%` }} />
    </div>);

}

function Stat({ label, value, sub, accent }) {
  return (
    <div style={{ padding: "14px 18px", borderRight: "1px solid var(--ink-200)" }}>
      <div className="text-xs muted" style={{ textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 600 }}>{label}</div>
      <div style={{ fontSize: 26, fontWeight: 700, marginTop: 4, letterSpacing: "-0.02em", color: accent || "var(--ink-900)" }}>{value}</div>
      {sub && <div className="text-xs muted" style={{ marginTop: 2 }}>{sub}</div>}
    </div>);

}

window.Sidebar = Sidebar;
window.Topbar = Topbar;
window.Shell = Shell;
window.Card = Card;
window.Badge = Badge;
window.Checkbox = Checkbox;
window.Toggle = Toggle;
window.Progress = Progress;
window.Stat = Stat;
window.NAV = NAV;
window.SCREEN_META = SCREEN_META;