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

/* App shell — sidebar nav for the logged-in user area */

function AppShell({ go, current, user, children }) {
  const ciq = window.ContactIQ ? window.ContactIQ.useContactIQ() : { isAuthed: false, profile: null, isAdmin: false };

  // When signed in, the sidebar's identity should reflect the real profile —
  // not the demo CURRENT_USER mock. We merge so the rest of the screens that
  // still read `user.*` keep working.
  const displayUser = ciq.profile ? {
    ...user,
    name:    ciq.profile.full_name || ciq.profile.email,
    email:   ciq.profile.email,
    company: ciq.profile.company || user.company,
    role:    ciq.profile.role,
  } : user;

  const items = [
    { k: "dashboard", label: "Lookup history", icon: <I.History/> },
    { k: "map",       label: "Live Map",       icon: <I.Pin/> },
    { k: "billing",   label: "Billing",        icon: <I.Card/> },
    { k: "extension", label: "Extension",      icon: <I.Box/> },
  ];
  const adminItems = [
    { k: "admin_users",     label: "Users",     icon: <I.Users/> },
    { k: "admin_analytics", label: "Analytics", icon: <I.Chart/> },
  ];

  const initials = (displayUser.name || "?").split(/\s+/).map(p => p[0]).slice(0,2).join("").toUpperCase();

  const signOut = async () => {
    if (window.ContactIQ) {
      try { await window.ContactIQ.clearExtensionJwt(); } catch (_) {}
      try { await window.ContactIQ.signOut(); } catch (_) {}
    }
    go("landing");
  };

  return (
    <div className="shell">
      <aside className="sidebar">
        <div className="row" style={{ padding: "4px 8px 8px", justifyContent: "space-between" }}>
          <Logo size="md"/>
        </div>

        <div className="sb-section">
          <div className="sb-eyebrow">Workspace</div>
          {items.map(it => (
            <a key={it.k} className={"sb-item " + (current === it.k ? "on" : "")} onClick={() => go(it.k)}>
              <span className="ico">{it.icon}</span>
              <span>{it.label}</span>
              {it.count != null && <span className="count">{it.count}</span>}
            </a>
          ))}
        </div>

        {/* Only show Admin section to users who actually have the role */}
        {ciq.isAdmin && (
          <div className="sb-section">
            <div className="sb-eyebrow">Admin</div>
            {adminItems.map(it => (
              <a key={it.k} className={"sb-item " + (current === it.k ? "on" : "")} onClick={() => go(it.k)}>
                <span className="ico">{it.icon}</span>
                <span>{it.label}</span>
              </a>
            ))}
          </div>
        )}

        <div className="sb-foot">
          <div className="sb-user">
            <Avatar name={displayUser.name}/>
            <div className="who">
              <span className="nm">{displayUser.name}</span>
              <span className="em">{displayUser.email}</span>
            </div>
            <button className="btn icon" style={{ width: 24, height: 24 }} title="Sign out" onClick={signOut}>
              <I.Logout/>
            </button>
          </div>
        </div>
      </aside>

      <main className="work">
        {children}
      </main>
    </div>
  );
}

window.AppShell = AppShell;
