// Sidebar + Topbar chrome — reads AppState for live counts and routes actions through dispatch.

function Sidebar() {
  const { state, dispatch } = useApp();

  // Derive live counts from state so badges reflect user actions.
  const rosterAttn = state.rosterRows.filter(r => r.staff.open || r.shifts.some(s => s.blocked)).length;
  const payrollCount = state.payrollOpen.filter(r => r.tone !== "block").length;
  const complianceBlocks = (state.expiries || []).filter(e => e.tone === "block").length;
  const pendingLeave = state.leaveRequests.filter(l => l.status === "pending").length;

  const agentPending = (state.agents || []).reduce((a, x) => a + (x.pending || 0), 0);

  const workforce = [
    { key: "dashboard",  label: "Dashboard",   icon: "home" },
    { key: "roster",     label: "Roster",      icon: "calendar", count: rosterAttn || null, tone: "warn" },
    { key: "people",     label: "People",      icon: "users" },
    { key: "leave",      label: "Leave",       icon: "clock",    count: pendingLeave || null, tone: "warn" },
    { key: "payroll",    label: "Payroll",     icon: "coin",     count: payrollCount || null, tone: "warn" },
  ];
  const intelligence = [
    { key: "agents",     label: "Agents",      icon: "sparkle",  count: agentPending || null, tone: "warn" },
    { key: "compliance", label: "Compliance",  icon: "shield",   count: complianceBlocks || null, tone: "block" },
    { key: "data",       label: "Data",        icon: "link" },
  ];
  const workspace = [
    { key: "audit",      label: "Audit trail", icon: "eye" },
    { key: "reports",    label: "Reports",     icon: "trend" },
    { key: "settings",   label: "Settings",    icon: "settings" },
  ];

  const activeFac = state.activeFacility === "all" ? null : state.facilities.find(f => f.id === state.activeFacility);

  return (
    <aside className="sidebar">
      <div className="brand">
        <div className="brand-mark">N</div>
        <div>
          <div className="brand-name">NuCo</div>
          <div className="brand-sub">Connected Care OS</div>
        </div>
      </div>

      <Dropdown align="left" trigger={
        <div className="facility-switcher">
          <div className="facility-dot" />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="facility-name" style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{activeFac ? activeFac.name : "All facilities"}</div>
            <div className="facility-meta">{activeFac ? `${activeFac.suburb} · ${activeFac.beds} beds` : `${state.facilities.length} sites · ${state.facilities.reduce((a, f) => a + f.beds, 0)} beds`}</div>
          </div>
          <Icon name="chevronDown" size={14} />
        </div>
      }>
        {(close) => (
          <>
            <div className="dropdown-label">Your facilities</div>
            <div className="dropdown-item" onClick={() => { dispatch({ type: "SET_FACILITY", facilityId: "all" }); close(); }}>
              <span className="facility-dot" style={{ background: state.activeFacility === "all" ? "var(--sage)" : "var(--line-2)" }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 500 }}>All facilities</div>
                <div className="sub" style={{ fontSize: 11 }}>Executive roll-up · {state.facilities.length} sites</div>
              </div>
              {state.activeFacility === "all" && <Icon name="check" size={13} />}
            </div>
            <div className="dropdown-divider" />
            {state.facilities.map(f => (
              <div key={f.id} className="dropdown-item" onClick={() => {
                dispatch({ type: "SET_FACILITY", facilityId: f.id });
                dispatch({ type: "PUSH_TOAST", toast: { tone: "ok", text: `Switched to ${f.name}` } });
                close();
              }}>
                <span className="facility-dot" style={{ background: state.activeFacility === f.id ? "var(--sage)" : f.risk === "warn" ? "var(--amber)" : "var(--line-2)" }} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 500 }}>{f.name}</div>
                  <div className="sub" style={{ fontSize: 11 }}>{f.suburb} · {f.beds} beds · {f.staff} staff</div>
                </div>
                {state.activeFacility === f.id && <Icon name="check" size={13} />}
              </div>
            ))}
            <div className="dropdown-divider" />
            <DropdownItem icon="plus" label="Add facility…" onClick={() => { dispatch({ type: "PUSH_TOAST", toast: { tone: "ok", text: "Facility onboarding flow coming soon." } }); close(); }} />
          </>
        )}
      </Dropdown>

      {[
        { label: "Workforce",    items: workforce },
        { label: "Intelligence", items: intelligence },
        { label: "Workspace",    items: workspace },
      ].map(group => (
        <div key={group.label} className="nav-group">
          <div className="nav-label">{group.label}</div>
          {group.items.map(n => (
            <button key={n.key} className="nav-item" data-active={state.page === n.key} onClick={() => dispatch({ type: "SET_PAGE", page: n.key })}>
              <span className="nav-ico"><Icon name={n.icon} size={15} /></span>
              <span>{n.label}</span>
              {n.count != null && <span className="nav-count" data-tone={n.tone}>{n.count}</span>}
            </button>
          ))}
        </div>
      ))}

      <div className="sidebar-foot">
        <AvatarInitials name="Jess Palmer" tone="sage" />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="user-name">Jess Palmer</div>
          <div className="user-role">Roster Coordinator</div>
        </div>
        <Dropdown align="right" trigger={<button className="icon-btn" style={{ width: 26, height: 26 }}><Icon name="more" size={14} /></button>}>
          {(close) => (
            <>
              <div className="dropdown-label">Signed in as {state.user || "nuco-user"}</div>
              <DropdownItem icon="eye" label="View profile" onClick={() => { dispatch({ type: "SET_PAGE", page: "people" }); close(); }} />
              <DropdownItem icon="settings" label="Preferences" onClick={() => { dispatch({ type: "PUSH_TOAST", toast: { tone: "ok", text: "Preferences coming soon." } }); close(); }} />
              <div className="dropdown-divider" />
              <DropdownItem icon="wand" label="Reset demo" onClick={() => { dispatch({ type: "RESET_DEMO" }); close(); }} />
              <DropdownItem icon="x" label="Sign out" tone="terra" onClick={() => { dispatch({ type: "AUTH_LOGOUT" }); close(); }} />
            </>
          )}
        </Dropdown>
      </div>
    </aside>
  );
}

function Topbar() {
  const { state, dispatch } = useApp();
  const activeFac = state.activeFacility === "all" ? null : state.facilities.find(f => f.id === state.activeFacility);
  const titles = {
    dashboard: ["Today", state.dashboardPersona === "executive" ? "Executive roll-up · all facilities" : "Operations overview"],
    roster:    ["Roster", state.rosterWeekMode ? "Banksia · Week 17 Apr 2026" : "Banksia · Fri 24 Apr 2026"],
    people:    ["People", "Active workforce"],
    leave:     ["Leave", "Requests & balances"],
    payroll:   ["Payroll", "Period closes today 17:00"],
    compliance:["Compliance", "Live credential monitoring"],
    agents:    ["Agents", "Gartner-tiered · human in the loop"],
    data:      ["Data & Integrations", "Datalake · live sources"],
    audit:     ["Audit trail", "Cross-module event stream"],
    reports:   ["Reports", "Regulatory & operational"],
    settings:  ["Settings", ""],
  };
  const [t, s] = titles[state.page] || [state.page, ""];

  function onSearch(v) {
    dispatch({ type: "SET_FILTER", key: "peopleSearch", value: v });
    if (v && state.page !== "people") dispatch({ type: "SET_PAGE", page: "people" });
  }

  return (
    <header className="topbar">
      <div className="crumbs">
        <span>{activeFac ? activeFac.name : "All facilities"}</span>
        <span className="sep">/</span>
        <strong>{t}</strong>
        {s && <><span className="sep">·</span><span>{s}</span></>}
      </div>
      <SearchInput
        placeholder="Search people, shifts, credentials…"
        value={state.filters.peopleSearch}
        onChange={onSearch}
        kbd="⌘ K"
      />
      <div className="topbar-actions">
        <div className="seg" style={{ background: "var(--paper)", border: "1px solid var(--line)" }}>
          <button data-active={state.view === "manager"} onClick={() => dispatch({ type: "SET_VIEW", view: "manager" })}>Manager</button>
          <button data-active={state.view === "ess"} onClick={() => dispatch({ type: "SET_VIEW", view: "ess" })}>My NuCo</button>
        </div>
        <Dropdown align="right" trigger={<button className="btn ghost"><Icon name="plus" size={13} /> New</button>}>
          {(close) => (
            <>
              <div className="dropdown-label">Create</div>
              <DropdownItem icon="users" label="Add person" onClick={() => { dispatch({ type: "SET_PAGE", page: "people" }); dispatch({ type: "PUSH_TOAST", toast: { tone: "ok", text: "Person onboarding drawer — coming soon." } }); close(); }} />
              <DropdownItem icon="calendar" label="New shift" onClick={() => { dispatch({ type: "SET_PAGE", page: "roster" }); close(); }} />
              <DropdownItem icon="coin" label="Payroll adjustment" onClick={() => { dispatch({ type: "SET_PAGE", page: "payroll" }); close(); }} />
              <DropdownItem icon="shield" label="Credential record" onClick={() => { dispatch({ type: "SET_PAGE", page: "compliance" }); close(); }} />
            </>
          )}
        </Dropdown>
        <Dropdown align="right" trigger={<button className="icon-btn"><Icon name="bell" size={15} /><span className="dot" /></button>}>
          {(close) => (
            <div style={{ minWidth: 280 }}>
              <div className="dropdown-label">Notifications · 3</div>
              {state.activity.slice(0, 3).map((a, i) => (
                <div key={i} className="dropdown-item" style={{ alignItems: "flex-start" }}>
                  <div className="activity-dot" data-tone={a.tone} style={{ marginTop: 3 }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12, fontWeight: 500 }}>{a.title}</div>
                    <div className="sub" style={{ fontSize: 11, whiteSpace: "normal" }}>{a.body}</div>
                    <div className="activity-time">{a.time}</div>
                  </div>
                </div>
              ))}
              <div className="dropdown-divider" />
              <DropdownItem icon="sparkle" label="Open NuCo copilot" onClick={() => { dispatch({ type: "SET_COPILOT", open: true }); close(); }} />
            </div>
          )}
        </Dropdown>
        <button className="icon-btn" data-active={state.copilotOpen} onClick={() => dispatch({ type: "SET_COPILOT", open: !state.copilotOpen })} title="NuCo copilot">
          <Icon name="sparkle" size={15} />
        </button>
      </div>
    </header>
  );
}

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