/* ============ Main App (Sidebar Layout): Sidebar + Topbar + Routing + State ============ */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#5B6AC9",
  "density": "comfortable",
  "showSidebarContext": true
}/*EDITMODE-END*/;

/* ====== Sidebar ====== */
const ENT_ALT_CLASSES = ["","alt1","alt2","alt3","alt4","alt5"];

const AdminSidebar = ({ view, nav, state, pendingCount, accessCount, tweaks, onLogout, collapsed, onToggleCollapse }) => {
  const [pwOpen, setPwOpen] = React.useState(false);
  const inEntityArea = ["entities","entity-detail","project-new","project-draft","project-structure"].includes(view.view);

  /* Home badge — mirrors what Home actually renders for this user:
       all roles  → my to-do count
       Admin only → + drafts pending + access requests pending */
  const myTodoCount = (typeof HOME_TODO_SEED !== "undefined" ? HOME_TODO_SEED : [])
    .filter(t => t.assignee === CURRENT_ADMIN.id).length;
  const homePendingTotal = CURRENT_ADMIN.role === "Admin"
    ? myTodoCount + pendingCount + accessCount
    : myTodoCount;

  /* resolve the entity currently in context */
  const currentEntity = view.entityId
    ? state.entities.find(e => e.id === view.entityId)
    : (view.projectId ? (() => {
        const p = state.projects.find(x => x.id === view.projectId);
        return p ? state.entities.find(e => e.id === p.entityId) : null;
      })() : null);
  const currentProject = view.projectId
    ? state.projects.find(p => p.id === view.projectId)
    : null;

  /* colour slot for entity avatar */
  const entIdx = currentEntity ? state.entities.indexOf(currentEntity) : 0;
  const entAltClass = ENT_ALT_CLASSES[entIdx % ENT_ALT_CLASSES.length];

  return (
    <aside className="sidebar">
      {/* Brand */}
      <div className="sidebar-head">
        <div className="logo" onClick={collapsed ? onToggleCollapse : undefined}
          title={collapsed ? "Expand sidebar" : undefined}
          style={collapsed ? {cursor:"pointer"} : undefined}>ASV</div>
        <div className="brand-block" style={{minWidth:0}}>
          <div className="brand-name">Audit Safe Vault</div>
          <div className="brand-tag">Admin · TumWebSME PIP2</div>
        </div>
        <button className="icon-btn sb-toggle" title="Collapse sidebar" onClick={onToggleCollapse}>
          <Icon n="arrow-l" s={13}/>
        </button>
      </div>

      {/* The old ACTIVE CLIENT picker is gone — once inside an entity the
         breadcrumb + page-head already carry the client/project context,
         so the sidebar block was pure duplication. */}
      <nav className="nav">
        {/* Workspace section — visible to every role */}
        <div className="nav-section">Workspace</div>
        <button
          className={`nav-item ${view.view==="home" ? "active" : ""}`}
          onClick={()=>nav.go({view:"home"})} title="Home">
          <Icon n="home" s={15}/> Home
          {homePendingTotal > 0 && <span className="count amber">{homePendingTotal}</span>}
        </button>
        <button
          className={`nav-item ${inEntityArea ? "active" : ""}`}
          onClick={()=>nav.go({view:"entities"})} title="Entities & Projects">
          <Icon n="building" s={15}/> Entities &amp; Projects <span className="count">{state.entities.length}</span>
        </button>

        {/* Pinned projects — quick access. Added from each project's head;
           here you can only jump to one or unpin it (hover ×). */}
        {(state.pinnedIds || []).length > 0 && (() => {
          const pinnedProjects = state.pinnedIds
            .map(id => state.projects.find(p => p.id === id))
            .filter(Boolean);
          if (!pinnedProjects.length) return null;
          return (
            <>
              <div className="nav-section">Pinned</div>
              {pinnedProjects.map(p => (
                <button key={p.id}
                  className={`nav-item ${view.projectId === p.id ? "active" : ""}`}
                  onClick={()=>nav.go(p.status === "draft"
                    ? {view:"project-draft", projectId:p.id}
                    : {view:"project-structure", projectId:p.id})}
                  title={p.name}>
                  <Icon n="pin" s={15}/>
                  <span className="pinned-label truncate" style={{flex:1,minWidth:0}}>{p.name}</span>
                  <span className="pin-x" title="Unpin"
                    onClick={(e)=>{ e.stopPropagation(); nav.togglePin(p.id); }}>
                    <Icon n="x" s={12}/>
                  </span>
                </button>
              ))}
            </>
          );
        })()}

        {/* Admin section — system-management tools, gated by role */}
        {CURRENT_ADMIN.role === "Admin" && (
          <>
            <div className="nav-section">Admin</div>
            <button
              className={`nav-item ${view.view==="workspace-activity" ? "active" : ""}`}
              onClick={()=>nav.go({view:"workspace-activity"})} title="Activity Log">
              <Icon n="history" s={15}/> Activity Log
            </button>
            <button
              className={`nav-item ${view.view==="users" ? "active" : ""}`}
              onClick={()=>nav.go({view:"users"})}
              title="Manage system users — display name, username, password, role">
              <Icon n="users" s={15}/> Users &amp; Roles
            </button>
            <button
              className={`nav-item ${view.view==="archive" ? "active" : ""}`}
              onClick={()=>nav.go({view:"archive"})}
              title="Closed engagements + 60-day auto-archive countdown">
              <Icon n="archive" s={15}/> Archive
            </button>

            {/* Setting catalogs — flat items (no sub-group) so every entry
               stays reachable from the collapsed icon rail */}
            <div className="nav-section">Setting</div>
            <button
              className={`nav-item ${view.view==="templates" ? "active" : ""}`}
              onClick={()=>nav.go({view:"templates"})}
              title="SOP Templates — reusable folder + WPID structures copied into projects at creation">
              <Icon n="template" s={15}/> SOP Templates <span className="count">{TEMPLATES.length}</span>
            </button>
            <button
              className={`nav-item ${view.view==="service-types" ? "active" : ""}`}
              onClick={()=>nav.go({view:"service-types"})}
              title="Service Types — admin-managed catalog">
              <Icon n="layers" s={15}/> Service Types <span className="count">{SERVICE_TYPE_CATALOG.length}</span>
            </button>
            <button
              className={`nav-item ${view.view==="company-categories" ? "active" : ""}`}
              onClick={()=>nav.go({view:"company-categories"})}
              title="Company Categories — classification catalog (Cat A–D and any custom)">
              <Icon n="grid" s={15}/> Company Categories <span className="count">{Object.keys(CATEGORY_INFO).length}</span>
            </button>
            <button
              className={`nav-item ${view.view==="plan-usage" ? "active" : ""}`}
              onClick={()=>nav.go({view:"plan-usage"})}
              title="Usage — users, projects, and cloud storage">
              <Icon n="progress" s={15}/> Usage
            </button>
          </>
        )}

      </nav>

      <div className="sidebar-foot">
        <Avatar id={CURRENT_ADMIN.id} name={CURRENT_ADMIN.name} size="md"/>
        <div className="foot-meta" style={{flex:1,minWidth:0}}>
          <div style={{fontSize:12,fontWeight:500,lineHeight:1.2}} className="truncate">{CURRENT_ADMIN.name}</div>
          <div className="mono" style={{fontSize:10,color:"var(--muted)",marginTop:2}}>{CURRENT_ADMIN.role} · online</div>
        </div>
        <button className="icon-btn" style={{width:28,height:28}} title="Change password" onClick={()=>setPwOpen(true)}><Icon n="lock" s={13}/></button>
        <button className="icon-btn" style={{width:28,height:28}} title="Sign out" onClick={onLogout}><Icon n="log-out" s={13}/></button>
      </div>

      {pwOpen && (
        <ChangePasswordModal
          onClose={()=>setPwOpen(false)}
          onSave={()=>{ setPwOpen(false); nav.toast("Password updated", "ok"); }}/>
      )}
    </aside>
  );
};

/* ====== Topbar — breadcrumbs only.
   Global search lives inside each list view; notifications route via
   email; Tweaks panel is reachable through the host's edit-mode
   postMessage handshake (no in-app trigger needed). ====== */
const Topbar = ({ crumbs }) => (
  <div className="top">
    <div className="crumbs">
      {crumbs.map((c, i) => (
        <React.Fragment key={i}>
          {i > 0 && <span className="sep">/</span>}
          {i === crumbs.length - 1
            ? <span className="cur">{c.label}</span>
            : <a onClick={c.onClick}>{c.label}</a>}
        </React.Fragment>
      ))}
    </div>
  </div>
);

/* ====== App ====== */
const App = () => {
  const [authed, setAuthed] = React.useState(false);
  const [sbCollapsed, setSbCollapsed] = React.useState(false);
  const [view, setView] = React.useState({ view: "home" });
  const [pendingDelete, setPendingDelete] = React.useState(null);
  const [pinnedIds, setPinnedIds] = React.useState(["P-2025-008"]);
  const [entities, setEntities] = React.useState(ENTITIES_SEED);
  const [projects, setProjects] = React.useState(PROJECTS_SEED);
  const [accessRequests, setAccessRequests] = React.useState(ACCESS_REQUESTS_SEED);
  const [events, setEvents] = React.useState(ACT_LOG);
  const [toast, setToast] = React.useState(null);
  const [tweaksOpen, setTweaksOpen] = React.useState(false);
  const [tweaks, setTweaks] = React.useState(TWEAK_DEFAULTS);

  React.useEffect(() => {
    const onMsg = (ev) => {
      if (!ev.data) return;
      if (ev.data.type === "__activate_edit_mode") setTweaksOpen(true);
      if (ev.data.type === "__deactivate_edit_mode") setTweaksOpen(false);
    };
    window.addEventListener("message", onMsg);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", onMsg);
  }, []);

  const setTweak = (k, v) => {
    const next = { ...tweaks, [k]: v };
    setTweaks(next);
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: { [k]: v } }, "*");
  };

  React.useEffect(() => {
    document.documentElement.style.setProperty("--accent-hex", tweaks.accent);
  }, [tweaks.accent]);

  const showToast = (msg, kind="ok") => {
    setToast({ msg, kind });
    setTimeout(()=>setToast(null), 2400);
  };

  /* Demo clock — anchored to 2026-05-22T10:00 (same base as relTime) so "ago" stays correct.
     Advances by 1 second per call so subsequent events stay ordered. */
  const demoClockRef = React.useRef(new Date('2026-05-22T10:30:00').getTime());
  const nowIso = () => {
    demoClockRef.current += 1000;
    const d = new Date(demoClockRef.current);
    const pad = n => n < 10 ? "0"+n : ""+n;
    return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
  };
  const fakeHash = () => "sha256:" + Math.random().toString(36).slice(2,6) + "…" + Math.random().toString(36).slice(2,6);
  const logEvent = (ev) => {
    const full = {
      id: "L-" + Date.now() + "-" + Math.random().toString(36).slice(2,5),
      ts: ev.ts || nowIso(),
      actor: ev.actor || CURRENT_ADMIN.id,
      scope: ev.scope ?? null,
      action: ev.action || "edit",
      obj: ev.obj || "",
      detail: ev.detail || "",
      ip: ev.ip || "10.0.4.02",
      device: ev.device || "Chrome · macOS",
      hash: ev.hash || fakeHash(),
      severity: ev.severity || "normal",
    };
    setEvents(prev => [full, ...prev]);
  };

  const nav = {
    go: (v) => { setView(v); window.scrollTo(0,0); },
    toast: showToast,
    log: logEvent,
    addEntity: (ent) => {
      setEntities(es => [ent, ...es]);
      logEvent({ action:"edit", obj:`Entity ${ent.name}`, detail:`Entity created · Tax ID ${ent.taxId}`, severity:"critical" });
    },
    updateEntity: (id, patch) => {
      setEntities(es => es.map(e => e.id===id ? {...e, ...patch} : e));
      const e = entities.find(x => x.id === id);
      if (e) logEvent({ action:"edit", obj:`Entity ${e.name}`, detail:`Entity updated · ${Object.keys(patch).join(", ")}` });
    },
    addProject: (p) => {
      setProjects(ps => [p, ...ps]);
      /* drafts/pending not logged per design rule — only on publish */
    },
    /* Inline edits from the Review & publish detail — Admin fixes Category/Risk before publishing */
    editProjectFields: (id, patch) => {
      setProjects(ps => ps.map(p => p.id===id ? {...p, ...patch, lastEditAt: nowIso(), lastEditBy: CURRENT_ADMIN.id} : p));
      const fields = Object.keys(patch).join(", ");
      PROJECT_TIMELINE[id] = [ ...(PROJECT_TIMELINE[id]||[]), { ts: nowIso(), actor: CURRENT_ADMIN.id, kind:"edit", text:`Admin inline-edit before publish: ${fields}` } ];
    },
    /* Soft Lock / Hard Lock / Unlock — γ archive flow */
    setReportDate: (id, t0) => {
      const now = nowIso();
      setProjects(ps => ps.map(p => p.id===id ? {...p, auditorReportDate: t0, lastEditAt: now, lastEditBy: CURRENT_ADMIN.id} : p));
      PROJECT_TIMELINE[id] = [ ...(PROJECT_TIMELINE[id]||[]), { ts: now, actor: CURRENT_ADMIN.id, kind:"edit", text:`Soft Lock opened — T0 set to ${t0}` } ];
      logEvent({ action:"perm", scope:id, obj:`Project ${id}`, detail:`Soft Lock opened (T0 = ${t0}, 60-day countdown started)`, severity:"critical" });
      showToast("Soft Lock active — project is read-only","warn");
    },
    archiveProjectNow: (id) => {
      const now = nowIso();
      setProjects(ps => ps.map(p => p.id===id ? {...p, status:"archived", archivedAt: now, archivedBy: CURRENT_ADMIN.id, archiveReason:"manual", members:[CURRENT_ADMIN.id]} : p));
      PROJECT_TIMELINE[id] = [ ...(PROJECT_TIMELINE[id]||[]), { ts: now, actor: CURRENT_ADMIN.id, kind:"approve", text:`Archived early (before 60-day auto)` } ];
      logEvent({ action:"perm", scope:id, obj:`Project ${id}`, detail:`Hard Lock applied (manual Archive Now). Members removed except Admin.`, severity:"critical" });
      showToast("Project archived — Hard Lock active","ok");
    },
    normalUnlockProject: (id) => {
      const now = nowIso();
      setProjects(ps => ps.map(p => p.id===id ? {...p, auditorReportDate: null, lastEditAt: now, lastEditBy: CURRENT_ADMIN.id} : p));
      PROJECT_TIMELINE[id] = [ ...(PROJECT_TIMELINE[id]||[]), { ts: now, actor: CURRENT_ADMIN.id, kind:"edit", text:`Normal Unlock — Soft Lock cleared, project back to Active` } ];
      logEvent({ action:"perm", scope:id, obj:`Project ${id}`, detail:`Normal Unlock — Soft Lock cleared, project back to Active`, severity:"critical" });
      showToast("Normal Unlock — project is Active again","ok");
    },
    /* Publish — draft → active (Admin only) */
    approveProject: (id, comment) => {
      const now = nowIso();
      setProjects(ps => ps.map(p => p.id===id ? {...p, status:"active", approvedAt: now, approvedBy: CURRENT_ADMIN.id} : p));
      PROJECT_TIMELINE[id] = [ ...(PROJECT_TIMELINE[id]||[]), { ts: now, actor: CURRENT_ADMIN.id, kind:"approve", text: comment ? `Published — "${comment}"` : "Published by Admin" } ];
      logEvent({ action:"publish", scope:id, obj:`Project ${id}`, detail:`Published by Admin. Activity logging begins here.${comment ? " Comment: " + comment : ""}`, severity:"critical" });
      showToast("Project published","ok");
      setView({ view:"home" });
    },
    /* Pin / unpin a project to the sidebar for quick access. Local UI
       preference only — not logged to the Activity Log. Capped at 10
       (user decision 2026-06-12) so the sidebar stays scannable. */
    togglePin: (id) => {
      setPinnedIds(prev => {
        if (prev.includes(id)) {
          showToast("Project unpinned", "ok");
          return prev.filter(x => x !== id);
        }
        if (prev.length >= 10) {
          showToast("Pin limit reached (10) — unpin another project first", "warn");
          return prev;
        }
        showToast("Project pinned to sidebar", "ok");
        return [...prev, id];
      });
    },
    deleteProject: (id) => {
      setPinnedIds(prev => prev.filter(x => x !== id));
      setProjects(ps => ps.filter(p => p.id !== id));
      delete PROJECT_TIMELINE[id];
      showToast("Project deleted","warn");
      setView({ view:"home" });
    },
    /* Decline reason is MANDATORY per req §3.4/§4.10 — Home's Pending access
       section collects it via DeclineReasonModal and passes it through here. */
    decideAccess: (id, decision, reason) => {
      const now = nowIso();
      const req = accessRequests.find(r => r.id === id);
      const usr = req ? USERS.find(u => u.id === req.userId) : null;
      setAccessRequests(rs => rs.map(r => r.id === id
        ? { ...r, status: decision, decidedBy: CURRENT_ADMIN.id, decidedAt: now, note: decision === "granted" ? "Granted by Admin" : (reason || "Declined by Admin") }
        : r));
      logEvent({
        action: decision === "granted" ? "grant" : "decline",
        scope: req?.projectId || null,
        obj: `Access · ${usr?.name || req?.userId} · ${req?.projectId || ""}`,
        detail: decision === "granted" ? "Granted by Admin" : `Declined by Admin · reason: "${reason || "—"}" · requester notified`,
        severity: decision === "granted" ? "normal" : "critical",
      });
      showToast(decision === "granted" ? "Access granted" : "Request declined — requester notified with reason", decision === "granted" ? "ok" : "warn");
    },
    confirmDelete: (p) => setPendingDelete(p),
  };

  const state = { entities, projects, accessRequests, events, tweaks, pinnedIds };
  const pendingCount = projects.filter(isAwaitingActivation).length;
  const arCount = accessRequests.filter(r => r.status === "pending").length;
  const densityClass = tweaks.density === "compact" ? " density-compact" : "";

  /* Compute breadcrumbs per view */
  const currentEntityForCrumbs = view.entityId
    ? entities.find(e => e.id === view.entityId)
    : (view.projectId ? (() => {
        const p = projects.find(x => x.id === view.projectId);
        return p ? entities.find(e => e.id === p.entityId) : null;
      })() : null);
  const currentProjectForCrumbs = view.projectId ? projects.find(p => p.id === view.projectId) : null;

  const crumbs = (() => {
    const ws = { label: "Workspace", onClick: () => nav.go({view:"home"}) };
    switch (view.view) {
      case "home":             return [ws, {label:"Home"}];
      case "entities":         return [ws, {label:"Entities & Projects"}];
      case "entity-detail":    return [ws, {label:"Entities", onClick:()=>nav.go({view:"entities"})}, {label: currentEntityForCrumbs?.name || view.entityId}];
      case "project-new":      return [ws, {label:"Entities", onClick:()=>nav.go({view:"entities"})}, {label: currentEntityForCrumbs?.name || "", onClick:()=>nav.go({view:"entity-detail",entityId:view.entityId})}, {label:"New Project"}];
      case "project-draft":    return [ws, {label:"Entities", onClick:()=>nav.go({view:"entities"})}, {label: currentEntityForCrumbs?.name || "", onClick:()=>nav.go({view:"entity-detail",entityId:currentEntityForCrumbs?.id})}, {label: currentProjectForCrumbs?.name || view.projectId}];
      case "templates":        return [ws, {label:"Admin"}, {label:"Setting"}, {label:"SOP Templates"}];
      case "project-structure": return [ws, {label:"Entities", onClick:()=>nav.go({view:"entities"})}, {label: currentEntityForCrumbs?.name || "", onClick:()=>nav.go({view:"entity-detail",entityId:currentEntityForCrumbs?.id})}, {label: currentProjectForCrumbs?.name || view.projectId}];
      case "activity":         return [ws, {label:"Entities", onClick:()=>nav.go({view:"entities"})}, {label: currentEntityForCrumbs?.name || "", onClick:()=>nav.go({view:"entity-detail",entityId:currentEntityForCrumbs?.id})}, {label:"Activity Log"}];
      case "workspace-activity": return [ws, {label:"Admin"}, {label:"Workspace Activity Log"}];
      case "recycle-bin":      return [ws, {label:"Recycle Bin"}];
      case "users":            return [ws, {label:"Admin"}, {label:"Users & Roles"}];
      case "archive":          return [ws, {label:"Admin"}, {label:"Archive"}];
      case "service-types":    return [ws, {label:"Admin"}, {label:"Setting"}, {label:"Service Types"}];
      case "company-categories": return [ws, {label:"Admin"}, {label:"Setting"}, {label:"Company Categories"}];
      case "plan-usage":         return [ws, {label:"Admin"}, {label:"Setting"}, {label:"Usage"}];
      case "lane-view":        return [ws, {label:"Lane View"}];
      default:                 return [ws];
    }
  })();

  /* Gate the workspace behind the persona login */
  if (!authed) {
    return <LoginScreen onLogin={(u)=>{ setCurrentUser(u); setView({ view:"home" }); setAuthed(true); }}/>;
  }

  return (
    <div className={"app" + densityClass + (sbCollapsed ? " sb-collapsed" : "")} data-screen-label={view.view}>
      <AdminSidebar
        view={view} nav={nav} state={state}
        pendingCount={pendingCount} accessCount={arCount}
        tweaks={tweaks} onLogout={()=>setAuthed(false)}
        collapsed={sbCollapsed} onToggleCollapse={()=>setSbCollapsed(v=>!v)}
      />
      <div className="main">
        <Topbar crumbs={crumbs}/>
        <div className="page">
          {view.view === "home" && <MyWorkspace state={state} nav={nav}/>}
          {view.view === "entities" && <EntityList state={state} nav={nav}/>}
          {view.view === "entity-detail" && <EntityDetail state={state} nav={nav} entityId={view.entityId} tab={view.tab || "projects"}/>}
          {view.view === "project-new" && <ProjectDraftForm state={state} nav={nav} entityId={view.entityId}/>}
          {view.view === "project-draft" && <ProjectDraftDetail state={state} nav={nav} projectId={view.projectId}/>}
          {view.view === "templates" && <TemplatesScreen state={state} nav={nav}/>}
          {view.view === "project-structure" && <ProjectStructureScreen key={view.projectId} state={state} nav={nav} projectId={view.projectId}/>}
          {view.view === "activity" && <ActivityScreen state={state} nav={nav} projectId={view.projectId}/>}
          {view.view === "workspace-activity" && <ActivityScreen state={state} nav={nav} workspace={true}/>}
          {view.view === "recycle-bin" && <RecycleBinScreen state={state} nav={nav} scopedProjectId={view.projectId}/>}
          {view.view === "users" && <UsersScreen state={state} nav={nav}/>}
          {view.view === "archive" && <ArchiveScreen state={state} nav={nav}/>}
          {view.view === "service-types" && <ServiceTypeScreen state={state} nav={nav}/>}
          {view.view === "company-categories" && <CompanyCategoryScreen state={state} nav={nav}/>}
          {view.view === "plan-usage" && <PlanUsageScreen state={state} nav={nav}/>}
          {view.view === "lane-view" && <LaneViewScreen state={state} nav={nav}/>}
        </div>
      </div>

      {/* Delete-draft confirm from list views (Home, etc.) */}
      {pendingDelete && <DeleteDraftModal
        project={pendingDelete}
        onClose={()=>setPendingDelete(null)}
        onConfirm={()=>{ const id = pendingDelete.id; setPendingDelete(null); nav.deleteProject(id); }}
      />}

      {/* TOAST */}
      {toast && <div className={`toast ${toast.kind}`}>
        <Icon n={toast.kind==="ok"?"check":"alert"} s={14}/>
        {toast.msg}
      </div>}

      {/* TWEAKS PANEL */}
      {tweaksOpen && (
        <div className="tweaks">
          <h4>
            <span style={{display:"inline-flex",alignItems:"center",gap:6}}><Icon n="settings" s={13}/> Tweaks</span>
            <button className="icon-btn" style={{width:24,height:24}} onClick={()=>{
              setTweaksOpen(false);
              window.parent.postMessage({type:"__edit_mode_dismissed"},"*");
            }}><Icon n="x" s={13}/></button>
          </h4>

          <div className="field">
            <label>Density</label>
            <div className="seg">
              <button className={tweaks.density==="comfortable"?"active":""} onClick={()=>setTweak("density","comfortable")}>Comfortable</button>
              <button className={tweaks.density==="compact"?"active":""} onClick={()=>setTweak("density","compact")}>Compact</button>
            </div>
          </div>

          <div className="field">
            <label>Sidebar context block</label>
            <div className="seg">
              <button className={tweaks.showSidebarContext?"active":""} onClick={()=>setTweak("showSidebarContext", true)}>Show</button>
              <button className={!tweaks.showSidebarContext?"active":""} onClick={()=>setTweak("showSidebarContext", false)}>Hide</button>
            </div>
          </div>

          <div className="field">
            <label>Accent</label>
            <div style={{display:"flex",gap:6}}>
              {["#18181b","#5B6AC9","#1F8A5B","#D97757","#7B3FE4"].map(c => (
                <button key={c} onClick={()=>setTweak("accent",c)} title={c}
                  style={{width:28,height:28,borderRadius:8,border:tweaks.accent===c?"2px solid var(--ink)":"1px solid var(--line)",background:c,cursor:"pointer"}}/>
              ))}
            </div>
          </div>

          <div className="field" style={{marginBottom:0}}>
            <label>Quick jump</label>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:6}}>
              <button className="btn sm" onClick={()=>nav.go({view:"home"})}>Home</button>
              <button className="btn sm" onClick={()=>nav.go({view:"entities"})}>Entities</button>
              <button className="btn sm" onClick={()=>nav.go({view:"templates"})}>Templates</button>
              <button className="btn sm" onClick={()=>nav.go({view:"workspace-activity"})}>Activity</button>
              <button className="btn sm" onClick={()=>nav.go({view:"service-types"})}>Service Types</button>
              <button className="btn sm" onClick={()=>nav.go({view:"company-categories"})}>Company Cat.</button>
              <button className="btn sm" onClick={()=>nav.go({view:"lane-view"})}>Lane View</button>
              <button className="btn sm" onClick={()=>nav.go({view:"project-draft",projectId:"P-2026-014"})}>Draft (pending)</button>
              <button className="btn sm" onClick={()=>nav.go({view:"project-draft",projectId:"P-2026-013"})}>Draft (old reject)</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

/* Templates placeholder — out of scope, just a polite stub */
const TemplatesPlaceholder = () => (
  <>
    <div className="page-head">
      <div className="page-title-row">
        <h1 className="page-title">SOP Templates</h1>
        <span className="badge">Out of scope this phase</span>
      </div>
      <div className="page-sub">SOP Template library — copied once into Projects (no live link back). Designed in the next phase.</div>
    </div>
    <div className="page-body">
      <div className="card">
        <EmptyState
          icon="template"
          title="Templates library coming next phase"
          sub="This phase's brief covers Entity & Project Creation only. Template authoring/preview is out of scope here — the brief notes that the Project form already lets you pick a template at creation time."
        />
      </div>
    </div>
  </>
);

/* Density-compact CSS injection — applied via class on .app */
const compactCss = `
.app.density-compact .tbl td{padding:8px 12px}
.app.density-compact .tbl th{padding:7px 12px}
.app.density-compact .page-head{padding:16px 24px 12px}
.app.density-compact .sec-body{padding:14px}
.app.density-compact .page-body{padding:16px}
.app.density-compact .card-body{padding:14px}
.app.density-compact .sbadge{padding:2px 7px 2px 5px;font-size:11px}
`;
const styleEl = document.createElement("style");
styleEl.textContent = compactCss;
document.head.appendChild(styleEl);

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
