// App shell: sidebar (brand, role switch, nav), topbar, copilot.

const NAV = [
  { section: "Workspace" },
  { id: "home",      label: "Home",          icon: "home" },
  { id: "leads",     label: "Leads",         icon: "leads",    badge: 14 },
  { id: "pipeline",  label: "Pipeline",      icon: "pipeline" },
  { id: "tasks",     label: "Tasks",         icon: "tasks",    badge: 5 },
  { section: "Sales" },
  { id: "inventory", label: "Inventory",     icon: "building" },
  { id: "reservations", label: "Reservations", icon: "payments", badge: 2 },
  { section: "Manage", roles: ["manager", "admin"] },
  { id: "insights",  label: "Insights",      icon: "chart",    roles: ["manager", "admin"] },
  { id: "team",      label: "Team",          icon: "team",     roles: ["manager", "admin"] },
];

const ROLES = {
  agent:   { label: "Sales agent",   agent: "sofia" },
  manager: { label: "Sales manager", agent: "diana" },
  admin:   { label: "Owner / Admin", agent: "diana" },
};

function RoleProfile(role) {
  const def = ROLES[role] || ROLES.agent;
  const a = agentById(def.agent);
  return { ...a, roleLabel: def.label };
}

function navForRole(role) {
  return NAV.filter((n) => !n.roles || n.roles.includes(role));
}

function Shell({ children, screen, setScreen, role, setRole, dark, onCopilot }) {
  const me = RoleProfile(role);
  const [menu, setMenu] = React.useState(false);
  const items = navForRole(role);
  return (
    <>
      <aside className="rc-side">
        <div className="rc-brand">
          <div className="rc-mark">
            <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round">
              <path d="M4 20V9l8-5 8 5v11" /><path d="M9 20v-6h6v6" />
            </svg>
          </div>
          <div className="rc-brand-text">
            <div className="rc-brand-name">Meridian</div>
            <div className="rc-brand-tier">Sales CRM · Lite</div>
          </div>
        </div>

        <div className="rc-roleswitch">
          <button className="rc-roleswitch-btn" onClick={() => setMenu((v) => !v)}>
            <Avatar initials={me.initials} size={28} color={me.color} />
            <div style={{ flex: 1, textAlign: "left", lineHeight: 1.2, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{me.name}</div>
              <div style={{ fontSize: 11, color: "var(--text-muted)" }}>{me.roleLabel}</div>
            </div>
            <Icon name="chevronDown" size={14} />
          </button>
          {menu && (
            <>
              <div style={{ position: "fixed", inset: 0, zIndex: 40 }} onClick={() => setMenu(false)} />
              <div className="rc-roleswitch-menu">
                <div style={{ fontSize: 10.5, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: 0.6, padding: "4px 10px 6px", fontWeight: 600 }}>View as</div>
                {Object.entries(ROLES).map(([key, r]) => {
                  const a = agentById(r.agent);
                  return (
                    <button key={key} className={`rc-rolerow ${role === key ? "is-active" : ""}`} onClick={() => { setRole(key); setMenu(false); setScreen("home"); }}>
                      <Avatar initials={a.initials} size={22} color={a.color} />
                      <div style={{ flex: 1, textAlign: "left" }}>
                        <div style={{ fontSize: 12.5, fontWeight: 550 }}>{a.name}</div>
                        <div style={{ fontSize: 11, color: "var(--text-muted)" }}>{r.label}</div>
                      </div>
                      {role === key && <Icon name="check" size={14} />}
                    </button>
                  );
                })}
              </div>
            </>
          )}
        </div>

        <nav className="rc-nav">
          {items.map((n, i) =>
            n.section ? (
              <div key={"s" + i} className="rc-navlabel">{n.section}</div>
            ) : (
              <button key={n.id} className={`rc-navbtn ${screen === n.id ? "is-active" : ""}`} onClick={() => setScreen(n.id)}>
                <Icon name={n.icon} size={18} />
                <span>{n.label}</span>
                {n.badge ? <span className="rc-navbadge">{n.badge}</span> : null}
              </button>
            )
          )}
        </nav>

        <div className="rc-side-foot">
          {role === "admin" && (
            <button className={`rc-navbtn ${screen === "settings" ? "is-active" : ""}`} onClick={() => setScreen("settings")}>
              <Icon name="settings" size={18} /><span>Settings</span>
            </button>
          )}
          <div style={{ padding: "10px 12px", border: "1px solid var(--border)", borderRadius: 11, background: "var(--surface)", marginTop: 4 }}>
            <div style={{ fontSize: 12, fontWeight: 600 }}>3 developments live</div>
            <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 2 }}>98 units · 35 available</div>
          </div>
        </div>
      </aside>

      <main className="rc-main">
        <header className="rc-top">
          <div className="rc-search">
            <Icon name="search" size={16} />
            <input placeholder="Search leads, units, reservations…" />
            <kbd>⌘K</kbd>
          </div>
          <div className="rc-top-right">
            <a className="rc-iconbtn" href="mobile.html" title="Open mobile app" style={{ textDecoration: "none" }}><Icon name="device" size={18} /></a>
            <button className="rc-iconbtn"><Icon name="bell" size={18} /><span className="rc-dot-red" /></button>
            <button className="rc-iconbtn" onClick={() => window.dispatchEvent(new CustomEvent("rc-toggle-theme"))}>
              <Icon name={dark ? "sun" : "moon"} size={18} />
            </button>
            <button className="rc-userchip">
              <Avatar initials={me.initials} size={30} color={me.color} />
              <div style={{ lineHeight: 1.15, textAlign: "left" }}>
                <div style={{ fontSize: 13, fontWeight: 550 }}>{me.name}</div>
                <div style={{ fontSize: 11, color: "var(--text-muted)" }}>{me.roleLabel}</div>
              </div>
            </button>
          </div>
        </header>
        <div className="rc-content">{children}</div>
      </main>

      <button className="rc-copilot-fab" onClick={onCopilot}>
        <Icon name="sparkles" size={18} />Ask Copilot
      </button>
    </>
  );
}

/* COPILOT */
function Copilot({ open, onClose }) {
  const [messages, setMessages] = React.useState([
    { role: "assistant", text: "Hi Sofia — I can summarize a lead, match a buyer to available units, or draft a follow-up. What do you need?" },
  ]);
  const [input, setInput] = React.useState("");
  const bodyRef = React.useRef(null);
  React.useEffect(() => { if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight; }, [messages]);
  const send = (t) => {
    const text = t || input;
    if (!text.trim()) return;
    setMessages((m) => [...m, { role: "user", text }]);
    setInput("");
    setTimeout(() => setMessages((m) => [...m, { role: "assistant", text: "Here's a draft for you. (Lite Copilot is read-only — it answers questions and drafts, but won't take actions on your behalf.)" }]), 450);
  };
  if (!open) return null;
  return (
    <div className="rc-copilot-panel">
      <div className="rc-copilot-head">
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div className="rc-copilot-mark"><Icon name="sparkles" size={16} /></div>
          <div>
            <div style={{ fontWeight: 650, fontSize: 14 }}>Meridian Copilot</div>
            <div style={{ fontSize: 11, color: "var(--text-muted)" }}>Lite · read-only</div>
          </div>
        </div>
        <button className="rc-iconbtn" onClick={onClose}><Icon name="x" size={16} /></button>
      </div>
      <div className="rc-copilot-body" ref={bodyRef}>
        {messages.map((m, i) => <div key={i} className={`rc-msg rc-msg-${m.role}`}>{m.text}</div>)}
      </div>
      <div className="rc-copilot-suggest">
        <button onClick={() => send("Which available units fit Beatriz's €400k budget?")}>Match a buyer to units</button>
        <button onClick={() => send("Summarize Ana Ferreira")}>Summarize a lead</button>
        <button onClick={() => send("Draft a follow-up for the Marina Verde viewing")}>Draft a follow-up</button>
      </div>
      <div className="rc-copilot-input">
        <input value={input} onChange={(e) => setInput(e.target.value)} onKeyDown={(e) => e.key === "Enter" && send()} placeholder="Ask Copilot…" />
        <button onClick={() => send()}><Icon name="send" size={14} /></button>
      </div>
    </div>
  );
}

Object.assign(window, { Shell, Copilot, RoleProfile, navForRole, ROLES });
