// shell.jsx — sidebar, topbar, command bar (wired to live store)

const { useState, useEffect, useRef, useMemo } = React;

function Sidebar({ active, onNav, collapsed, onSignOut, onClose }) {
  const [userMenuOpen, setUserMenuOpen] = useState(false);
  const store = window.MSStore.useStore();
  const t = window.MSStore.useT();
  const profile = store && store.profile;
  const account = store && store.activeAccount;
  const role = store && store.activeRole;

  const rawName = (profile && profile.name) || "";
  const displayName = rawName
    ? (/^Dr\.?\s/i.test(rawName) ? rawName : "Dr. " + rawName)
    : "MedSync user";
  const subline = ((profile && profile.specialty) || "").trim() ||
    (role === "owner" ? t("set.role.adminDoctor") :
     role === "admin_doctor" ? t("set.role.adminDoctor") :
     role === "doctor" ? t("set.role.doctor") :
     role === "staff" ? t("set.role.staff") : t("set.role.doctor"));
  const clinicName = (account && account.name) || (profile && profile.clinic_name) || "MedSync";
  const userInitials = (rawName || "MS").replace(/^Dr\.?\s+/i, "")
    .split(/\s+/).filter(Boolean).map(s => s[0]).slice(0, 2).join("").toUpperCase() || "MS";
  const avatarBg = (profile && profile.avatar_color) || "var(--primary-soft)";
  const avatarBorder = (profile && profile.avatar_color) || "var(--primary-line)";
  const avatarFg = profile && profile.avatar_color ? "white" : "var(--primary-ink)";

  const primary = [
    { id: "dashboard", label: t("nav.today"),     icon: Icon.Dashboard },
    { id: "schedule",  label: t("nav.schedule"),  icon: Icon.Calendar },
    { id: "patients",  label: t("nav.patients"),  icon: Icon.Patients },
    { id: "analytics", label: t("nav.analytics"), icon: Icon.Pulse },
    { id: "assistant", label: t("nav.assistant"), icon: Icon.Sparkle },
    { id: "whatsapp",  label: t("nav.whatsapp"),  icon: Icon.Phone },
    { id: "dictionary", label: t("nav.dictionary"), icon: Icon.Clipboard },
    { id: "transcribe",label: t("nav.transcribe"),icon: Icon.Mic },
  ];
  const handleNav = (page) => {
    onNav(page);
    if (onClose) onClose();
  };
  return (
    <aside className={"ms-sidebar" + (collapsed ? " is-collapsed" : "")}>
      <div className="ms-mobile-drawer-head">
        <div className="ms-mobile-drawer-title">
          <div className="ms-brand-mark">
            <Icon.Logo/>
          </div>
          <div>
            <div className="ms-brand-name">MedSync</div>
            <div className="ms-brand-clinic">{clinicName}</div>
          </div>
        </div>
        <button className="btn btn-ghost btn-icon btn-sm" onClick={onClose} aria-label="Close navigation">
          <Icon.X size={17}/>
        </button>
      </div>
      <div className="ms-brand">
        <div className="ms-brand-mark">
          <Icon.Logo/>
        </div>
        {!collapsed && (
          <div className="ms-brand-text">
            <div className="ms-brand-name">MedSync</div>
            <div className="ms-brand-clinic">{clinicName}</div>
          </div>
        )}
      </div>

      <button className="ms-newvisit" onClick={() => handleNav("transcribe")}>
        <Icon.Plus size={16}/>
        {!collapsed && <span>{t("nav.newVisit")}</span>}
      </button>

      <nav className="ms-nav scroll">
        {primary.map(item => {
          const I = item.icon;
          return (
            <button key={item.id} className={"ms-nav-item" + (active === item.id ? " is-active" : "")} onClick={() => handleNav(item.id)} title={collapsed ? item.label : undefined}>
              <I size={18}/>
              {!collapsed && <span className="ms-nav-label">{item.label}</span>}
              {!collapsed && item.badge ? <span className="ms-nav-badge">{item.badge}</span> : null}
            </button>
          );
        })}
      </nav>

      <div style={{position: "relative"}}>
        <button className="ms-userbox" style={{width: "100%", appearance: "none", border: 0, cursor: "pointer", background: userMenuOpen ? "var(--bg-soft)" : "transparent"}} onClick={() => setUserMenuOpen(o => !o)}>
          <div className="avatar avatar-sm" style={{background: avatarBg, color: avatarFg, borderColor: avatarBorder}}>{userInitials}</div>
          {!collapsed && (
            <>
              <div style={{minWidth: 0, flex: 1, textAlign: "left"}}>
                <div style={{fontSize: 12.5, fontWeight: 600, lineHeight: 1.2, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis"}}>{displayName}</div>
                <div style={{fontSize: 11, color: "var(--ink-4)"}}>{subline}</div>
              </div>
              <Icon.ChevronDown size={14} style={{color: "var(--ink-4)", flexShrink: 0, transform: userMenuOpen ? "rotate(180deg)" : "none", transition: "transform .15s"}}/>
            </>
          )}
        </button>
        {userMenuOpen && (
          <div className="ms-user-menu slide-up" onClick={() => setUserMenuOpen(false)}>
            <button className="ms-nav-item ms-nav-item-sm" onClick={() => handleNav("settings")} style={{width: "100%"}}>
              <Icon.Settings size={15}/>
              <span className="ms-nav-label">{t("nav.settings")}</span>
            </button>
            <div className="divider" style={{margin: "4px 8px"}}/>
            <button className="ms-nav-item ms-nav-item-sm" onClick={onSignOut} style={{width: "100%", color: "var(--accent-danger)"}}>
              <Icon.ArrowRight size={15}/>
              <span className="ms-nav-label">{t("nav.signOut")}</span>
            </button>
          </div>
        )}
      </div>
    </aside>
  );
}

function Topbar({ onCmd, onNav, onMenu, title, subtitle, actions }) {
  const [lang, setLang] = window.MSStore.useLang();
  const store = window.MSStore.useStore();
  const unread = (store && store.unreadNotifications) || 0;
  return (
    <header className="ms-topbar">
      <div className="ms-topbar-left">
        <button className="btn btn-ghost btn-icon btn-sm ms-mobile-menu-btn" onClick={onMenu} aria-label="Open navigation">
          <Icon.Menu size={18}/>
        </button>
        <div className="ms-mobile-top-logo" aria-label="MedSync">
          <div className="ms-brand-mark">
            <Icon.Logo size={24}/>
          </div>
          <span>MedSync</span>
        </div>
      </div>
      <div className="spacer"/>
      <div className="ms-topbar-right">
        {actions}
        <div className="ms-segmented" style={{height: 30}} role="group" aria-label="Language">
          {window.MSi18n && window.MSi18n.SUPPORTED.map(code => (
            <button
              key={code}
              className={lang === code ? "is-active" : ""}
              onClick={() => setLang(code)}
              style={{padding: "0 10px", fontSize: 11, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.04em"}}
              aria-pressed={lang === code}
            >
              {code}
            </button>
          ))}
        </div>
        <button className="btn btn-ghost btn-icon btn-sm" onClick={onCmd} title="Search (⌘K)" aria-label="Search">
          <Icon.Search size={16}/>
        </button>
        <button className="btn btn-icon btn-sm" title="Notifications" aria-label="Notifications" onClick={() => onNav && onNav("notifications")} style={{position: "relative"}}>
          <Icon.Bell size={16}/>
          {unread > 0 && <span style={{position: "absolute", top: 4, right: 5, minWidth: 7, height: 7, borderRadius: 999, background: "var(--accent-danger)", border: "1.5px solid white"}}/>}
        </button>
      </div>
    </header>
  );
}

function CommandBar({ open, onClose, onNav }) {
  const [q, setQ] = useState("");
  const inputRef = useRef(null);
  const store = window.MSStore.useStore();

  useEffect(() => { if (open) setTimeout(() => inputRef.current?.focus(), 30); }, [open]);
  useEffect(() => {
    function onKey(e) { if (e.key === "Escape") onClose(); }
    if (open) window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  const items = useMemo(() => {
    const patientItems = (store && store.patients || []).slice(0, 50).map(p => ({
      kind: "Patient",
      label: `${p.first} ${p.last}`.trim() || "Unnamed patient",
      sub: [p.age && `${p.age}y`, p.phone, p.email].filter(Boolean).join(" · "),
      action: () => { onNav("patients", p.id); onClose(); },
      avatar: p.avatar,
    }));
    const navItems = [
      { kind: "Go to", label: "Today's dashboard", icon: Icon.Dashboard, action: () => { onNav("dashboard"); onClose(); } },
      { kind: "Go to", label: "Schedule",          icon: Icon.Calendar,  action: () => { onNav("schedule"); onClose(); } },
      { kind: "Go to", label: "Patients",          icon: Icon.Patients,  action: () => { onNav("patients"); onClose(); } },
      { kind: "Go to", label: "Analytics",         icon: Icon.Pulse,     action: () => { onNav("analytics"); onClose(); } },
      { kind: "Go to", label: "MedSync Assist",    icon: Icon.Sparkle,   action: () => { onNav("assistant"); onClose(); } },
      { kind: "Go to", label: "Dictionary",        icon: Icon.Clipboard, action: () => { onNav("dictionary"); onClose(); } },
      { kind: "Action", label: "Start a transcription session", icon: Icon.Mic, action: () => { onNav("transcribe"); onClose(); } },
      { kind: "Go to", label: "Settings",          icon: Icon.Settings,  action: () => { onNav("settings"); onClose(); } },
    ];
    const all = [...navItems, ...patientItems];
    if (!q) return all.slice(0, 8);
    const ql = q.toLowerCase();
    return all.filter(i => i.label.toLowerCase().includes(ql) || (i.sub || "").toLowerCase().includes(ql)).slice(0, 12);
  }, [q, store && store.patients]);

  if (!open) return null;
  return (
    <div className="ms-cmd-overlay" onClick={onClose}>
      <div className="ms-cmd slide-up" onClick={e => e.stopPropagation()}>
        <div className="ms-cmd-input">
          <Icon.Search size={18}/>
          <input ref={inputRef} value={q} onChange={e => setQ(e.target.value)} placeholder="Patient, command, or page…" />
          <span className="ms-kbd">esc</span>
        </div>
        <div className="ms-cmd-list scroll">
          {items.length === 0 && <div style={{padding: 24, textAlign: "center", color: "var(--ink-4)", fontSize: 13}}>No results</div>}
          {items.map((it, i) => (
            <button key={i} className="ms-cmd-item" onClick={it.action}>
              <div className="ms-cmd-icon">
                {it.avatar
                  ? <span className="avatar avatar-sm">{it.avatar}</span>
                  : it.icon ? <it.icon size={16}/> : <Icon.ArrowRight size={16}/>}
              </div>
              <div style={{flex: 1, minWidth: 0}}>
                <div style={{fontSize: 13.5, fontWeight: 500, color: "var(--ink)"}}>{it.label}</div>
                {it.sub && <div style={{fontSize: 12, color: "var(--ink-4)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis"}}>{it.sub}</div>}
              </div>
              <span className="badge">{it.kind}</span>
            </button>
          ))}
        </div>
        <div className="ms-cmd-foot">
          <span><span className="ms-kbd">↑↓</span> navigate</span>
          <span><span className="ms-kbd">↵</span> select</span>
          <span><span className="ms-kbd">esc</span> close</span>
        </div>
      </div>
    </div>
  );
}

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