/* =========================================================
   shell.jsx — left rail (department directory), topbar, screen frame
   ========================================================= */

/* The sidebar stays intentionally small. Most days the owner lives in Today. */
const NAV_PRIMARY = [
  { id: "today",    label: "Today",    icon: "home",   count: 5 },
  { id: "project",  label: "History",  icon: "receipt" },
];

const EMPLOYEE_TEAMS = [
  {
    id:"daily",
    name:"Daily staff",
    flow:"bills, logs, updates, hours, money",
    people:[
      { id:"books", goto:"bills", initials:"BK", tone:"ink", name:"Bookkeeper", role:"bills to QuickBooks", status:"wait", needs:1 },
      { id:"field", goto:"field", initials:"FI", tone:"amber", name:"Field Intake", role:"texts to daily logs", status:"busy", needs:1 },
      { id:"liaison", goto:"client", initials:"CL", tone:"rust", name:"Client Liaison", role:"homeowner updates", status:"wait", needs:1 },
      { id:"time", goto:"timekeeper", initials:"TK", tone:"navy", name:"Timekeeper", role:"crew hours", status:"wait", needs:1 },
      { id:"analyst", goto:"accounting", initials:"AA", tone:"rust", name:"Accounting Analyst", role:"money questions", status:"idle", needs:0 },
    ],
  },
  {
    id:"onboarding",
    name:"Client onboarding",
    flow:"plans to budget to quotes to schedule",
    people:[
      { id:"takeoff", goto:"takeoff", initials:"TR", tone:"green", name:"Takeoff Reader", role:"plans to budget", status:"wait", needs:1 },
      { id:"trades", goto:"quotes", initials:"TC", tone:"amber", name:"Trade Coordinator", role:"trade quotes", status:"wait", needs:1 },
      { id:"scheduler", goto:"schedule", initials:"SC", tone:"slate", name:"Scheduler", role:"first schedule", status:"wait", needs:1 },
    ],
  },
];

const EMPLOYEES = EMPLOYEE_TEAMS.flatMap((team) => team.people);

const RailRow = ({ d, current, onGo }) => (
  <button
    className={"rail-item " + (current === d.id ? "is-active" : "")}
    onClick={(event) => {
      event.currentTarget.blur();
      onGo(d.id);
    }}
  >
    <Icon name={d.icon} size={15} color="currentColor" />
    <span>{d.label}</span>
    {d.count ? <span className="count">{d.count}</span> : null}
  </button>
);

const EmpRow = ({ e, current, onGo }) => (
  <button
    className={"rail-emp " + (current === e.goto ? "is-active" : "")}
    onClick={(event) => {
      event.currentTarget.blur();
      onGo(e.goto);
    }}
    title={e.name}
  >
    <span className={"emp-badge t-" + e.tone}>
      {e.initials}
      <span className={"emp-status is-" + e.status} />
    </span>
    <span className="emp-copy">
      <span className="emp-name">{e.name}</span>
      <span className="emp-role">{e.role}</span>
    </span>
    {e.needs > 0
      ? <span className="emp-needs">{e.needs}</span>
      : <span className="emp-needs is-clear">·</span>}
  </button>
);

const Sidebar = ({ current, onGo }) => {
  const [openTeams, setOpenTeams] = React.useState({});
  const [mobileMenu, setMobileMenu] = React.useState("");
  const teamIsOpen = (team) => {
    if (Object.prototype.hasOwnProperty.call(openTeams, team.id)) return openTeams[team.id];
    return current !== "today" && team.people.some((person) => person.goto === current);
  };
  const toggleTeam = (team) => {
    setOpenTeams((currentOpen) => {
      const currentValue = Object.prototype.hasOwnProperty.call(currentOpen, team.id)
        ? currentOpen[team.id]
        : teamIsOpen(team);
      return { ...currentOpen, [team.id]: !currentValue };
    });
  };

  return (
    <aside className="rail">
      <div className="rail-brand">
        <Logo size={30} color="#FBF8F2" />
        <div>
          <div className="wordmark">CoordOS</div>
          <div className="sub">Custom home builder</div>
        </div>
      </div>

      <div className="rail-group">
        <div className="rail-section-label">CoordOS</div>
        <div className="rail-list">
          {NAV_PRIMARY.map(d => <RailRow key={d.id} d={d} current={current} onGo={onGo} />)}
        </div>
      </div>

      <div className="rail-staff-groups">
        {EMPLOYEE_TEAMS.map((team) => (
          <StaffRailGroup
            key={team.id}
            team={team}
            current={current}
            isOpen={teamIsOpen(team)}
            onToggle={() => toggleTeam(team)}
            onGo={onGo}
          />
        ))}
      </div>

      <div className="rail-foot">
        <div className="avatar">AB</div>
        <div className="who">
          Aaron Beaufort
          <small>Owner · Approver</small>
        </div>
      </div>

      <MobileTabBar
        current={current}
        openMenu={mobileMenu}
        onToggleMenu={(menu) => setMobileMenu((open) => open === menu ? "" : menu)}
        onGo={(screen) => {
          setMobileMenu("");
          onGo(screen);
        }}
      />
    </aside>
  );
};

const StaffRailGroup = ({ team, current, isOpen, onToggle, onGo }) => {
  const needs = team.people.reduce((sum, person) => sum + (person.needs || 0), 0);
  return (
    <div className={"rail-staff-group" + (isOpen ? " is-open" : "")}>
      <button className="rail-staff-toggle-v4" type="button" onClick={onToggle} aria-expanded={isOpen}>
        <span className="rail-caret">{isOpen ? "-" : "+"}</span>
        <span className="rail-team-copy">
          <span>{team.name}</span>
          <small>{team.flow}</small>
        </span>
        {needs > 0 && <em>{needs}</em>}
      </button>
      {isOpen && (
        <div className="rail-list">
          {team.people.map((person) => <EmpRow key={person.id} e={person} current={current} onGo={onGo} />)}
        </div>
      )}
    </div>
  );
};

const MobileTabBar = ({ current, openMenu, onToggleMenu, onGo }) => {
  const isDaily = EMPLOYEE_TEAMS[0].people.some((person) => person.goto === current);
  const isOnboarding = EMPLOYEE_TEAMS[1].people.some((person) => person.goto === current);
  return (
    <nav className="mobile-tabbar-v6" aria-label="Mobile navigation">
      {openMenu && (
        <div className="mobile-tab-sheet-v6">
          <div>
            <b>{openMenu === "daily" ? "Daily staff" : "Client onboarding"}</b>
            <button type="button" onClick={() => onToggleMenu(openMenu)} aria-label="Close mobile menu">Close</button>
          </div>
          {(openMenu === "daily" ? EMPLOYEE_TEAMS[0].people : EMPLOYEE_TEAMS[1].people).map((person) => (
            <button
              key={person.id}
              type="button"
              className={current === person.goto ? "is-active" : ""}
              onClick={() => onGo(person.goto)}
            >
              <span className={"emp-badge t-" + person.tone}>{person.initials}</span>
              <span>
                <b>{person.name}</b>
                <small>{person.role}</small>
              </span>
              {person.needs > 0 && <em>{person.needs}</em>}
            </button>
          ))}
        </div>
      )}
      <button type="button" className={current === "today" ? "is-active" : ""} onClick={() => onGo("today")}>
        <Icon name="home" size={16} color="currentColor" />
        <span>Today</span>
      </button>
      <button type="button" className={current === "project" ? "is-active" : ""} onClick={() => onGo("project")}>
        <Icon name="receipt" size={16} color="currentColor" />
        <span>History</span>
      </button>
      <button type="button" className={isDaily || openMenu === "daily" ? "is-active" : ""} onClick={() => onToggleMenu("daily")}>
        <span className="mobile-dot-v6">5</span>
        <span>Daily</span>
      </button>
      <button type="button" className={isOnboarding || openMenu === "onboarding" ? "is-active" : ""} onClick={() => onToggleMenu("onboarding")}>
        <span className="mobile-dot-v6">3</span>
        <span>Onboard</span>
      </button>
    </nav>
  );
};

/* slimmer topbar — crumbs + decision count + date */
const Topbar = ({ crumbs, runningCount = 4 }) => {
  const today = new Date();
  const dateStr = today.toLocaleDateString("en-GB", {
    weekday: "long", day: "numeric", month: "long",
  }).toUpperCase();
  return (
    <div className="topbar v2">
      <div className="crumbs">
        {crumbs.map((c, i) => (
          <React.Fragment key={i}>
            {i > 0 && <span className="sep">/</span>}
            {i === crumbs.length - 1 ? <strong>{c}</strong> : <span>{c}</span>}
          </React.Fragment>
        ))}
      </div>
      <span className="now"><span className="pulse" /> <b>5</b> decisions waiting · <b>{runningCount}</b> employees working</span>
      <span className="date">{dateStr} · 7:42 AM</span>
    </div>
  );
};

/* fixed crumbs per screen so it always says where you are */
const CRUMBS = {
  today:    ["Today"],
  financeToday: ["Today"],
  schedulingToday: ["Today"],
  estimate: ["Staff", "Estimator"],
  quotes:   ["Staff", "Trade Coordinator"],
  bills:    ["Staff", "Bookkeeper"],
  field:    ["Staff", "Field Intake"],
  mailroom: ["History"],
  channels: ["History"],
  schedule: ["Staff", "Scheduler"],
  project:  ["History"],
  client:   ["Staff", "Client Liaison"],
  staff:    ["Staff"],
  receipts: ["History"],
  ask:      ["Ask"],
  timekeeper: ["Staff", "Timekeeper"],
  accounting: ["Staff", "Accounting Analyst"],
  takeoff: ["Staff", "Takeoff Reader"],
  support: ["Today"],
  settings: ["Today"],
  tour: ["Tour"],
};

window.Sidebar = Sidebar;
window.Topbar = Topbar;
window.CRUMBS = CRUMBS;
