/* ============================================================
   Carebridge Portal — application shell + routing + tweaks
   ============================================================ */
const { useState: useStateA, useEffect: useEffectA, useRef: useRefA } = React;

const NAV = [
  { group: "Overview", items: [
    { id: "dashboard", label: "Dashboard", icon: "layout-dashboard" },
  ]},
  { group: "Patient care", items: [
    { id: "patients", label: "Patients", icon: "users", count: "84" },
    { id: "journey", label: "Treatment journey", icon: "route" },
    { id: "reports", label: "Report review", icon: "file-text", count: "18" },
  ]},
  { group: "Coordination", items: [
    { id: "travel", label: "Travel coordination", icon: "plane" },
    { id: "comms", label: "Communication hub", icon: "messages-square", count: "7" },
  ]},
  { group: "Network & business", items: [
    { id: "hospitals", label: "Hospital network", icon: "hospital" },
    { id: "financial", label: "Financial", icon: "wallet" },
    { id: "analytics", label: "Analytics", icon: "bar-chart-3" },
  ]},
  { group: "Patient experience", items: [
    { id: "mobile", label: "Patient mobile app", icon: "smartphone" },
  ]},
];

const META = {
  dashboard: { title: "Executive dashboard", crumb: "Overview" },
  patients: { title: "Patient management", crumb: "Patient care" },
  patient: { title: "Patient case", crumb: "Patient care · Patients" },
  journey: { title: "Treatment journey", crumb: "Patient care" },
  reports: { title: "Medical report review", crumb: "Patient care" },
  travel: { title: "Medical travel coordination", crumb: "Coordination" },
  comms: { title: "Communication hub", crumb: "Coordination" },
  hospitals: { title: "Hospital network", crumb: "Network & business" },
  financial: { title: "Financial management", crumb: "Network & business" },
  analytics: { title: "Analytics & reporting", crumb: "Network & business" },
  mobile: { title: "Patient mobile app", crumb: "Patient experience" },
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "dashboard": "overview",
  "accent": "teal",
  "density": "comfortable",
  "sidebar": "navy"
}/*EDITMODE-END*/;

function Brandmark() {
  return (
    <div className="cb-side__brand">
      <div className="cb-brandmark">
        <svg viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round">
          <path d="M3 16c3 0 3-6 6-6s3 6 6 6" opacity="0.55" />
          <path d="M2 12c0-2.8 2-4.5 4.5-4.5h11C20 7.5 22 9.2 22 12" />
          <path d="M2 12v3M22 12v3" />
          <path d="M7 12h2l1.5-3 2 6 1.5-3h2" />
        </svg>
      </div>
      <div className="cb-brand__text">
        <div className="cb-brand__name">Carebridge</div>
        <div className="cb-brand__sub">International</div>
      </div>
    </div>
  );
}

function Sidebar({ active, go, role }) {
  const isClient = role === "client";
  const filteredNav = isClient
    ? NAV.map((g) => ({ ...g, items: g.items.filter((it) => ["journey", "comms", "mobile"].includes(it.id)) })).filter((g) => g.items.length)
    : NAV;
  const user = isClient
    ? { initials: "HA", color: "var(--navy-600)", name: "Hodan Ali", urole: "Patient · CB-2039" }
    : { initials: "AY", color: "var(--teal-600)", name: "Amina Yusuf", urole: "Lead coordinator" };
  return (
    <aside className="cb-side">
      <Brandmark />
      <nav className="cb-nav">
        {filteredNav.map((grp) => (
          <div key={grp.group}>
            <div className="cb-nav__label">{grp.group}</div>
            {grp.items.map((it) => {
              const on = active === it.id || (it.id === "patients" && active === "patient");
              return (
                <button key={it.id} className={"cb-nav__item" + (on ? " is-active" : "")} onClick={() => go(it.id)}>
                  <i data-lucide={it.icon} aria-hidden="true" />
                  <span>{it.label}</span>
                  {it.count ? <span className="cb-nav__count">{it.count}</span> : null}
                </button>
              );
            })}
          </div>
        ))}
      </nav>
      <div className="cb-side__foot">
        <div className="cb-side__user">
          <div className="cb-av cb-av--sm" style={{ background: user.color }}>{user.initials}</div>
          <div className="cb-side__utext" style={{ flex: 1 }}>
            <div className="cb-side__uname">{user.name}</div>
            <div className="cb-side__urole">{user.urole}</div>
          </div>
          <a className="cb-signout" href="Carebridge Login.html" aria-label="Sign out" title="Sign out">
            <i data-lucide="log-out" style={{ width: 18, height: 18 }} />
          </a>
        </div>
      </div>
    </aside>
  );
}

function Topbar({ view, onMenu }) {
  const m = META[view] || META.dashboard;
  return (
    <header className="cb-top">
      <button className="cb-burger" aria-label="Open menu" onClick={onMenu}><i data-lucide="menu" /></button>
      <div className="cb-top__title">
        <span className="cb-crumb">{m.crumb}</span>
        <h1>{m.title}</h1>
      </div>
      <div className="cb-top__spacer" />
      <div className="cb-search">
        <i data-lucide="search" aria-hidden="true" />
        <input placeholder="Search patients, cases, hospitals…" />
      </div>
      <div className="cb-top__actions">
        <button className="cb-icon-pill cb-help-hide" aria-label="Help"><i data-lucide="life-buoy" /></button>
        <button className="cb-icon-pill" aria-label="Notifications"><i data-lucide="bell" /><span className="cb-dot" /></button>
        <button className="cb-icon-pill" aria-label="Add" style={{ background: "var(--navy-600)", color: "#fff", border: "none" }}><i data-lucide="plus" /></button>
      </div>
    </header>
  );
}

function useLucideObserver(ref) {
  useEffectA(() => {
    if (!window.lucide || !ref.current) return;
    let scheduled = false;
    const run = () => { scheduled = false; if (window.lucide) window.lucide.createIcons(); };
    window.lucide.createIcons();
    const obs = new MutationObserver(() => { if (scheduled) return; scheduled = true; requestAnimationFrame(run); });
    obs.observe(ref.current, { childList: true, subtree: true });
    return () => obs.disconnect();
  }, []);
}

function getRole() {
  try { return new URLSearchParams(window.location.search).get("role") || "admin"; }
  catch (e) { return "admin"; }
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const role = getRole();
  const [view, setView] = useStateA(role === "client" ? { name: "mobile", id: null } : { name: "dashboard", id: null });
  const [navOpen, setNavOpen] = useStateA(false);
  const rootRef = useRefA(null);
  const mainRef = useRefA(null);
  useLucideObserver(rootRef);
  useEffectA(() => {
    const id = requestAnimationFrame(() => { if (window.lucide) window.lucide.createIcons(); });
    return () => cancelAnimationFrame(id);
  });

  const go = (name, id) => {
    setView({ name, id: id || null });
    setNavOpen(false);
    if (mainRef.current) mainRef.current.scrollTop = 0;
  };

  let content = null;
  switch (view.name) {
    case "patients": content = <PatientsView go={go} />; break;
    case "patient": content = <PatientDetail id={view.id} go={go} />; break;
    case "journey": content = <JourneyView go={go} />; break;
    case "reports": content = <ReportsView />; break;
    case "travel": content = <TravelView go={go} />; break;
    case "comms": content = <CommsView />; break;
    case "hospitals": content = <HospitalsView />; break;
    case "financial": content = <FinancialView />; break;
    case "analytics": content = <AnalyticsView />; break;
    case "mobile": content = <MobileView />; break;
    default: content = <Dashboard direction={t.dashboard} go={go} />;
  }

  return (
    <div className={"cb-app" + (navOpen ? " nav-open" : "")} ref={rootRef} data-accent={t.accent} data-density={t.density} data-side={t.sidebar}>
      <div className="cb-scrim" onClick={() => setNavOpen(false)} aria-hidden="true" />
      <Sidebar active={view.name} go={(n) => go(n)} role={role} />
      <main className="cb-main" ref={mainRef}>
        <Topbar view={view.name} onMenu={() => setNavOpen(true)} />
        <div className="cb-page">{content}</div>
      </main>

      <TweaksPanel>
        <TweakSection label="Dashboard direction" />
        <TweakRadio label="Layout" value={t.dashboard}
          options={[{ value: "overview", label: "Overview" }, { value: "operations", label: "Operations" }, { value: "executive", label: "Executive" }]}
          onChange={(v) => { setTweak("dashboard", v); go("dashboard"); }} />
        <TweakSection label="Appearance" />
        <TweakRadio label="Accent emphasis" value={t.accent}
          options={[{ value: "teal", label: "Teal" }, { value: "navy", label: "Navy" }]}
          onChange={(v) => setTweak("accent", v)} />
        <TweakRadio label="Sidebar" value={t.sidebar}
          options={[{ value: "navy", label: "Navy" }, { value: "light", label: "Light" }]}
          onChange={(v) => setTweak("sidebar", v)} />
        <TweakRadio label="Density" value={t.density}
          options={[{ value: "comfortable", label: "Comfortable" }, { value: "compact", label: "Compact" }]}
          onChange={(v) => setTweak("density", v)} />
      </TweaksPanel>
    </div>
  );
}

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