/* global React, PR */
const { useState, useMemo, useRef, useEffect } = React;
const { I, Avatar, StagePill } = PR;

// ============ Sidebar ============
function Sidebar({ active, setActive, theme, setTheme, data, user, onLogout }) {
  const counts = useMemo(() => {
    const c = { all: 0, active: 0, decision: 0, scale: 0, archive: 0 };
    data.hypotheses.forEach(h => {
      c.all++;
      if (h.decision === "kill") c.archive++;
      else if (h.decision === "scale") c.scale++;
      else c.active++;
      if (h.stage === "decision" && !h.decision) c.decision++;
    });
    return c;
  }, [data]);

  const NavItem = ({ id, icon, label, count }) => (
    <div className={"nav-item" + (active === id ? " active" : "")} onClick={() => setActive(id)}>
      <div className="nav-left">
        <span className="nav-icon">{icon}</span>
        <span>{label}</span>
      </div>
      {count != null && <span className="nav-count">{count}</span>}
    </div>
  );

  const userAuthor = user ? { name: user.full_name || user.username, color: user.color || "#7C8BA1" } : null;

  return (
    <aside className="sidebar">
      <div className="sidebar-head">
        <div className="brand-mark">R</div>
        <div>
          <div className="brand-name">R&amp;D Pipeline</div>
          <div className="brand-sub">Core team · v1.0</div>
        </div>
      </div>

      <div className="nav-section">
        <div className="nav-section-title">Workspace</div>
        <NavItem id="registry"  icon={I.list}    label="Registry"   count={counts.all} />
        <NavItem id="kanban"    icon={I.kanban}  label="Pipeline"   count={counts.active} />
        <NavItem id="cards"     icon={I.grid}    label="Cards"      count={counts.active} />
        <NavItem id="dashboard" icon={I.chart}   label="Dashboard" />
      </div>

      <div className="nav-section">
        <div className="nav-section-title">Views</div>
        <NavItem id="passport"  icon={I.doc}     label="R&D Passport" />
        <NavItem id="decision"  icon={I.flag}    label="Awaiting decision" count={counts.decision} />
        <NavItem id="scaled"    icon={I.check}   label="Scaled"     count={counts.scale} />
        <NavItem id="archive"   icon={I.archive} label="Archive"    count={counts.archive} />
      </div>

      {user?.role === "admin" && (
        <div className="nav-section">
          <div className="nav-section-title">Admin</div>
          <NavItem id="users" icon={I.users} label="Users & roles" />
        </div>
      )}

      <div className="sidebar-foot" style={{ flexDirection: "column", gap: 8, alignItems: "stretch" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <span style={{ fontSize: 11, color: "var(--text-4)" }}>v1.0 · pilot</span>
          <div className="theme-toggle" role="tablist">
            <button className={theme === "light" ? "active" : ""} onClick={() => setTheme("light")} title="Light">{I.sun}</button>
            <button className={theme === "dark"  ? "active" : ""} onClick={() => setTheme("dark")}  title="Dark">{I.moon}</button>
          </div>
        </div>
        {userAuthor && (
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <Avatar author={userAuthor} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12, fontWeight: 500, color: "var(--text)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                {user.full_name || user.username}
              </div>
              <div style={{ fontSize: 11, color: "var(--text-3)" }}>{user.role}</div>
            </div>
            <button
              className="btn btn-ghost"
              onClick={onLogout}
              title="Sign out"
              style={{ padding: "2px 6px", height: 24, fontSize: 11, flexShrink: 0 }}
            >
              Out
            </button>
          </div>
        )}
      </div>
    </aside>
  );
}

// ============ Topbar ============
function Topbar({ crumbs, onNew }) {
  return (
    <div className="topbar">
      <div className="crumbs">
        {crumbs.map((c, i) => (
          <React.Fragment key={i}>
            {i > 0 && <span className="crumb-sep">/</span>}
            <span className={i === crumbs.length - 1 ? "crumb-current" : ""}>{c}</span>
          </React.Fragment>
        ))}
      </div>
      <div className="topbar-spacer"></div>
      <div className="search">
        <span style={{ display: "inline-flex" }}>{I.search}</span>
        <span>Search hypotheses</span>
        <kbd>⌘K</kbd>
      </div>
      <button className="btn btn-primary" onClick={onNew}>{I.plus}<span>New hypothesis</span></button>
    </div>
  );
}

// ============ Filter chip with dropdown ============
function FilterChip({ label, value, options, onChange }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    if (!open) return;
    const handler = (e) => {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);

  const selected = options.find(o => o.value === value);
  const isActive = !!value;

  return (
    <div style={{ position: "relative" }} ref={ref}>
      <span
        className={"chip" + (isActive ? " chip-filter-active" : "")}
        onClick={() => setOpen(o => !o)}
      >
        {label}: {selected ? selected.label : "any"}
        {isActive && (
          <span
            onClick={(e) => { e.stopPropagation(); onChange(""); setOpen(false); }}
            style={{ marginLeft: 4, opacity: 0.65, cursor: "pointer" }}
          >×</span>
        )}
      </span>
      {open && (
        <div className="filter-dropdown">
          <div
            className={"filter-option" + (!value ? " filter-option-selected" : "")}
            onClick={() => { onChange(""); setOpen(false); }}
          >
            Any
          </div>
          {options.map(o => (
            <div
              key={o.value}
              className={"filter-option" + (value === o.value ? " filter-option-selected" : "")}
              onClick={() => { onChange(o.value); setOpen(false); }}
            >
              {o.label}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ============ Page header with view switch ============
function PageHead({ title, sub, view, setView, filters, setFilters, filterOptions, currentUserId }) {
  const set = (k, v) => setFilters(f => ({ ...f, [k]: v }));

  return (
    <>
      <div className="page-head">
        <div>
          <h1 className="page-title">{title}</h1>
          <p className="page-sub">{sub}</p>
        </div>
        {view !== undefined && (
          <div className="view-switch">
            <button className={view === "table"  ? "active" : ""} onClick={() => setView("table")}>{I.list}<span>Table</span></button>
            <button className={view === "kanban" ? "active" : ""} onClick={() => setView("kanban")}>{I.kanban}<span>Kanban</span></button>
            <button className={view === "cards"  ? "active" : ""} onClick={() => setView("cards")}>{I.grid}<span>Cards</span></button>
          </div>
        )}
      </div>
      {filters && filterOptions && (
        <div className="filter-bar">
          <span className={"chip" + (filters.set === "all"    ? " active" : "")} onClick={() => set("set", "all")}>All</span>
          <span className={"chip" + (filters.set === "active" ? " active" : "")} onClick={() => set("set", "active")}>Active</span>
          {currentUserId && (
            <span className={"chip" + (filters.set === "mine" ? " active" : "")} onClick={() => set("set", "mine")}>Mine</span>
          )}
          <span className="chip-divider"></span>
          <FilterChip label="Stage"  value={filters.stage}  options={filterOptions.stages}  onChange={v => set("stage", v)} />
          <FilterChip label="Genre"  value={filters.genre}  options={filterOptions.genres}  onChange={v => set("genre", v)} />
          <FilterChip label="Author" value={filters.author} options={filterOptions.authors} onChange={v => set("author", v)} />
          <span className="chip-divider"></span>
          <FilterChip label="Risk"   value={filters.risk}   options={filterOptions.risks}   onChange={v => set("risk", v)} />
        </div>
      )}
    </>
  );
}

window.PRShell = { Sidebar, Topbar, PageHead };
