// shell.jsx — Sidebar, topbar, layout, account switcher, tweaks panel

const NAV = [
  { group: "Overview", items: [
    { id: "dashboard",   label: "Dashboard",      icon: "home" },
    { id: "calls",       label: "Calls",          icon: "phone" },
  ]},
  { group: "Tracking", items: [
    { id: "numbers",     label: "Phone numbers",  icon: "list" },
    { id: "campaigns",   label: "Campaigns",      icon: "flag" },
  ]},
  { group: "Account", items: [
    { id: "team",        label: "Team & clients", icon: "users" },
    { id: "billing",     label: "Billing",        icon: "wallet" },
    { id: "whitelabel",  label: "White-label",    icon: "brush" },
    { id: "integrations",label: "Integrations",   icon: "plug" },
    { id: "api",         label: "API & webhooks", icon: "key" },
    { id: "settings",    label: "Settings",       icon: "cog" },
  ]},
];

// Demo fallback. Real data comes from API via props at runtime.
const WORKSPACES = [
  { id: "blue", name: "Bluebird Marketing", kind: "Agency · 12 clients", letters: "BM", type: "agency" },
  { id: "sun",  name: "Sunrise Dental Group", kind: "Client workspace", letters: "SD", type: "client" },
  { id: "mid",  name: "Midtown Plumbing Co.", kind: "Client workspace", letters: "MP", type: "client" },
  { id: "oak",  name: "Oakfield Law Partners", kind: "Client workspace", letters: "OL", type: "client" },
];

function wsLetters(name) {
  if (!name) return "·";
  const words = name.trim().split(/\s+/).filter(Boolean);
  if (words.length >= 2) return (words[0][0] + words[1][0]).toUpperCase();
  return name.slice(0, 2).toUpperCase();
}
function wsKind(w) {
  if (w.kind) return w.kind;
  if (w.type === "agency") return "Agency workspace";
  return "Client workspace";
}
function wsAvatarGradient(w) {
  return w.type === "agency"
    ? "linear-gradient(135deg,#0A84FF,#9333EA)"
    : "linear-gradient(135deg,#F97316,#DB2777)";
}

function AccountSwitcher({ workspace, setWorkspace, workspaces, reloadWorkspaces }) {
  const list = (workspaces && workspaces.length) ? workspaces : WORKSPACES;
  const agencyWs = list.filter((w) => w.type === "agency");
  const clientWs = list.filter((w) => w.type !== "agency");
  const [showCreate, setShowCreate] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef();
  React.useEffect(() => {
    const close = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", close);
    return () => document.removeEventListener("mousedown", close);
  }, []);

  return (
    <div ref={ref} style={{position:"relative"}}>
      <div className="ws-switcher" onClick={() => setOpen(!open)}>
        <div className="ws-avatar" style={{background: wsAvatarGradient(workspace)}}>
          {workspace.letters || wsLetters(workspace.name)}
        </div>
        <div className="ws-meta">
          <div className="ws-name">{workspace.name}</div>
          <div className="ws-sub">{wsKind(workspace)}</div>
        </div>
        <div className="ws-chevron"><I.chevD size={14} /></div>
      </div>
      {open && (
        <div style={{
          position: "absolute", top: "calc(100% + 4px)", left: 0, right: 0, zIndex: 30,
          background: "var(--panel)", borderRadius: "var(--radius-lg)",
          boxShadow: "var(--shadow-lg)", border: ".5px solid var(--line)",
          padding: 6, animation: "fadeSlide .16s ease-out"
        }}>
          {agencyWs.length > 0 && (
            <>
              <div style={{fontSize:10, fontWeight:600, color:"var(--ink-4)", letterSpacing:".06em", textTransform:"uppercase", padding:"8px 10px 4px"}}>Agency</div>
              {agencyWs.map(ws => (
                <div key={ws.id} className="ws-switcher" style={{boxShadow:"none", background:"transparent", margin:0, padding:"8px 10px"}}
                  onClick={() => { setWorkspace(ws); setOpen(false); }}>
                  <div className="ws-avatar" style={{background: wsAvatarGradient(ws)}}>{ws.letters || wsLetters(ws.name)}</div>
                  <div className="ws-meta"><div className="ws-name">{ws.name}</div><div className="ws-sub">{wsKind(ws)}</div></div>
                  {workspace.id === ws.id && <I.check size={14} style={{color:"var(--accent)"}} />}
                </div>
              ))}
            </>
          )}
          {clientWs.length > 0 && (
            <>
              <div style={{fontSize:10, fontWeight:600, color:"var(--ink-4)", letterSpacing:".06em", textTransform:"uppercase", padding:"8px 10px 4px", marginTop: agencyWs.length > 0 ? 4 : 0}}>Clients</div>
              {clientWs.map(ws => (
                <div key={ws.id} className="ws-switcher" style={{boxShadow:"none", background:"transparent", margin:0, padding:"8px 10px"}}
                  onClick={() => { setWorkspace(ws); setOpen(false); }}>
                  <div className="ws-avatar" style={{background: wsAvatarGradient(ws)}}>{ws.letters || wsLetters(ws.name)}</div>
                  <div className="ws-meta"><div className="ws-name">{ws.name}</div><div className="ws-sub">{wsKind(ws)}</div></div>
                  {workspace.id === ws.id && <I.check size={14} style={{color:"var(--accent)"}} />}
                </div>
              ))}
            </>
          )}
          <div style={{borderTop:".5px solid var(--line)", margin:"6px 0"}} />
          <div className="nav-item" style={{color:"var(--accent)", cursor:"pointer"}}
               onClick={() => { setOpen(false); setShowCreate(true); }}>
            <I.plus size={14} /> New client workspace
          </div>
        </div>
      )}
      {showCreate && (
        <NewWorkspaceModal
          parentWorkspace={workspace}
          onClose={() => setShowCreate(false)}
          onCreated={async (ws) => {
            setShowCreate(false);
            if (reloadWorkspaces) await reloadWorkspaces();
            setWorkspace(ws);
            window.toast?.success(`Created ${ws.name}`);
          }}
        />
      )}
    </div>
  );
}

// Modal to create a new client workspace under the current agency. Lives
// here in shell.jsx (rather than reusing screens-a's CampaignModal pattern)
// because the AccountSwitcher already lives here and the form is small.
function NewWorkspaceModal({ parentWorkspace, onClose, onCreated }) {
  const [name, setName] = React.useState("");
  const [linkToAgency, setLinkToAgency] = React.useState(parentWorkspace?.type === "agency");
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);

  async function submit(e) {
    e.preventDefault();
    if (!name.trim()) return;
    setSubmitting(true); setError(null);
    try {
      const payload = { name: name.trim(), type: "client" };
      if (linkToAgency && parentWorkspace?.type === "agency") {
        payload.parentWorkspaceId = parentWorkspace.id;
      }
      const res = await API.workspaces.create(payload);
      onCreated && onCreated(res.data);
    } catch (err) {
      setError(err.message);
      setSubmitting(false);
    }
  }

  // window.Modal is registered by screens-a.jsx (loaded after shell.jsx);
  // it's available by the time this renders.
  const Modal = window.Modal;
  const ErrorChip = window.ErrorChip;

  return (
    <Modal onClose={onClose} title="New client workspace">
      <form onSubmit={submit} className="col g16">
        <div className="field">
          <label>Workspace name</label>
          <input
            className="input"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Sunrise Dental"
            autoFocus
            required
          />
          <div className="muted" style={{fontSize:12}}>
            Each client gets its own numbers, wallet, branding, and team.
          </div>
        </div>
        {parentWorkspace?.type === "agency" && (
          <label className="row g8" style={{cursor:"pointer", fontSize:13.5}}>
            <input
              type="checkbox"
              checked={linkToAgency}
              onChange={(e) => setLinkToAgency(e.target.checked)}
            />
            Link as a child of <strong>{parentWorkspace.name}</strong>
          </label>
        )}
        {error && (ErrorChip ? <ErrorChip msg={error}/> : <div style={{fontSize:12.5, color:"#DC2626"}}>{error}</div>)}
        <div className="row g8" style={{justifyContent:"flex-end"}}>
          <button type="button" className="btn btn-ghost btn-sm" onClick={onClose}>Cancel</button>
          <button type="submit" className="btn btn-primary btn-sm" disabled={submitting}>
            {submitting ? "Creating…" : "Create workspace"}
          </button>
        </div>
      </form>
    </Modal>
  );
}

function Sidebar({ route, setRoute, workspace, setWorkspace, workspaces, reloadWorkspaces, balance, onTopUp, brandName }) {
  return (
    <aside className="sidebar">
      <AccountSwitcher workspace={workspace} setWorkspace={setWorkspace} workspaces={workspaces} reloadWorkspaces={reloadWorkspaces} />

      {NAV.map((sec) => (
        <React.Fragment key={sec.group}>
          <div className="nav-section">{sec.group}</div>
          {sec.items.map((it) => {
            const Ic = I[it.icon];
            return (
              <div key={it.id}
                className={"nav-item" + (route === it.id ? " active" : "")}
                onClick={() => setRoute(it.id)}>
                <Ic />
                <span>{it.label}</span>
                {it.badge && <span className="badge">{it.badge}</span>}
              </div>
            );
          })}
        </React.Fragment>
      ))}

      <div className="sidebar-footer">
        <div className="balance-chip" onClick={onTopUp}>
          <div>
            <div className="lbl">Prepay balance</div>
            <div className="val">${balance.toFixed(2)}</div>
          </div>
          <div className="top">Top up</div>
        </div>
      </div>
    </aside>
  );
}

function UserMenu({ user, onLogout }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef();
  React.useEffect(() => {
    const close = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", close);
    return () => document.removeEventListener("mousedown", close);
  }, []);
  const name = user?.fullName || user?.email || "";
  const initials = name
    ? name.trim().split(/\s+/).slice(0, 2).map((w) => w[0]).join("").toUpperCase() || name.slice(0, 2).toUpperCase()
    : "·";
  return (
    <div ref={ref} style={{position:"relative"}}>
      <div
        onClick={() => setOpen(!open)}
        style={{width:28, height:28, borderRadius:"50%", background:"linear-gradient(135deg,#0A84FF,#9333EA)", color:"white", fontSize:11, fontWeight:600, display:"grid", placeItems:"center", cursor:"pointer"}}
        title={name}
      >{initials}</div>
      {open && (
        <div style={{
          position:"absolute", top:"calc(100% + 6px)", right:0, zIndex:30, minWidth:200,
          background:"var(--panel)", borderRadius:"var(--radius-lg)",
          boxShadow:"var(--shadow-lg)", border:".5px solid var(--line)",
          padding:6, animation:"fadeSlide .16s ease-out"
        }}>
          <div style={{padding:"10px 12px 8px"}}>
            <div style={{fontSize:13, fontWeight:500, color:"var(--ink)"}}>{user?.fullName || "—"}</div>
            <div style={{fontSize:11.5, color:"var(--ink-4)"}}>{user?.email}</div>
          </div>
          <div style={{borderTop:".5px solid var(--line)", margin:"4px 0"}} />
          <div className="nav-item" style={{color:"#DC2626"}} onClick={() => { setOpen(false); onLogout && onLogout(); }}>
            <I.side /> Log out
          </div>
        </div>
      )}
    </div>
  );
}

function Topbar({ crumbs, dark, setDark, sidebar, setSidebar, brandName, user, onLogout }) {
  return (
    <div className="topbar">
      <button className="icon-btn" onClick={() => setSidebar(!sidebar)} title="Toggle sidebar">
        <I.side />
      </button>
      <div className="crumb">
        {crumbs.map((c, i) => (
          <React.Fragment key={i}>
            {i > 0 && <I.chev size={13} />}
            <span className={i === crumbs.length - 1 ? "cur" : ""}>{c}</span>
          </React.Fragment>
        ))}
      </div>
      <div className="spacer" />
      <div className="search">
        <I.search size={14} />
        <span>Search calls, numbers, campaigns</span>
        <kbd>⌘K</kbd>
      </div>
      <button className="icon-btn" onClick={() => setDark(!dark)}>
        {dark ? <I.sparkle /> : <I.moon />}
      </button>
      <button className="icon-btn"><I.help /></button>
      <button className="icon-btn"><I.bell /></button>
      <div style={{width:1, height:20, background:"var(--line)"}} />
      <UserMenu user={user} onLogout={onLogout} />
    </div>
  );
}

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