/* Calibrated Ascension HQ — escalation inbox + settings (brief, trust, team). */
const { useState: useStateSet } = React;

const DEFAULT_SETTINGS = {
  brief: { inApp: true, email: true, address: "you@calibratedascension.com", time: "4:00pm" },
  trust: [
    { id: "client", label: "Anything client-facing (emails, posts, forms)", level: "ask" },
    { id: "publish", label: "Publish blogs & community posts", level: "ask" },
    { id: "dm", label: "Low-risk DM replies — Max", level: "auto" },
    { id: "automations", label: "Run healthy automations — Alma", level: "auto" },
    { id: "broken", label: "Touch anything that's broken — Soham", level: "ask" },
    { id: "spend", label: "Shift ad spend under $500/day — Noah", level: "ask" },
    { id: "pricing", label: "Change offers or pricing — Odin", level: "off" },
  ],
  team: [
    { id: "owner", name: "You", email: "you@calibratedascension.com", role: "Owner", scope: "All accounts" },
  ],
};

/* ---------- Global escalation inbox ---------- */
function EscalationInbox({ items, clients, onApprove, onJump, onInspect, onClose }) {
  const clientName = (id) => (clients.find((c) => c.id === id) || {}).name || id;
  const clientBadge = (id) => clients.find((c) => c.id === id) || {};
  const byClient = {};
  items.forEach((it) => { (byClient[it.clientId] = byClient[it.clientId] || []).push(it); });

  return (
    <div className="ov" onClick={onClose}>
      <div className="sheet" onClick={(e) => e.stopPropagation()}>
        <div className="sheet-h">
          <div className="deliv-ico" style={{ width: 38, height: 38, background: "var(--amber-soft)", color: "var(--amber-ink)", borderColor: "var(--amber)" }}>{I.bell}</div>
          <div style={{ flex: 1 }}>
            <div className="sheet-title">Needs you</div>
            <div className="sheet-sub">{items.length === 0 ? "Nothing is waiting — the team has it." : `${items.length} item${items.length === 1 ? "" : "s"} across your accounts`}</div>
          </div>
          <button className="x-btn" onClick={onClose}>{I.x}</button>
        </div>
        <div className="sheet-b">
          {items.length === 0 && <div className="empty" style={{ padding: "30px 10px" }}>Inbox zero. Anubis only escalates what truly needs your call.</div>}
          {Object.keys(byClient).map((cid) => {
            const c = clientBadge(cid);
            return (
              <div key={cid} style={{ marginBottom: 16 }}>
                <div className="esc-group">
                  <span className="client-badge" style={{ background: c.color, width: 22, height: 22, fontSize: 9 }}>{c.initials}</span>
                  {clientName(cid)}
                </div>
                {byClient[cid].map((it) => (
                  <div key={it.id} className="esc-row clickable" data-kind={it.kind} onClick={() => onInspect && onInspect(it)}>
                    <span className={`esc-tag ${it.kind}`}>{it.kind === "risk" ? "risk" : it.kind === "deliverable" ? "to send" : it.tag || "decision"}</span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div className="esc-title">{it.title}</div>
                      {it.detail && <div className="esc-detail">{it.detail}</div>}
                    </div>
                    {it.kind === "decision"
                      ? <button className="btn btn-primary btn-sm" onClick={(e) => { e.stopPropagation(); onApprove(it.clientId, it.id); }}>{I.check} Approve</button>
                      : <button className="btn btn-ghost btn-sm" onClick={(e) => { e.stopPropagation(); onJump(it.clientId); }}>Open</button>}
                  </div>
                ))}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

/* ---------- Settings: brief delivery · trust dial · team ---------- */
function Seg({ value, options, onChange }) {
  return (
    <div className="seg">
      {options.map((o) => (
        <button key={o.v} className="seg-opt" data-active={value === o.v} data-tone={o.v} onClick={() => onChange(o.v)}>{o.l}</button>
      ))}
    </div>
  );
}

function SettingsModal({ settings, setSettings, onClose }) {
  const [tab, setTab] = useStateSet("brief");
  const [invite, setInvite] = useStateSet({ email: "", role: "VA", scope: "Selected clients" });

  const setBrief = (k, v) => setSettings((s) => ({ ...s, brief: { ...s.brief, [k]: v } }));
  const setTrust = (id, level) => setSettings((s) => ({ ...s, trust: s.trust.map((t) => (t.id === id ? { ...t, level } : t)) }));
  function addMember() {
    if (!invite.email.trim()) return;
    setSettings((s) => ({ ...s, team: [...s.team, { id: "m" + Date.now(), name: invite.email.split("@")[0], email: invite.email.trim(), role: invite.role, scope: invite.scope }] }));
    setInvite({ email: "", role: "VA", scope: "Selected clients" });
  }

  const tabs = [
    { id: "brief", label: "Brief delivery", ico: I.today },
    { id: "trust", label: "Trust & autonomy", ico: I.shield },
    { id: "team", label: "Team & access", ico: I.seat },
  ];

  return (
    <div className="ov" onClick={onClose}>
      <div className="sheet" style={{ width: 600 }} onClick={(e) => e.stopPropagation()}>
        <div className="sheet-h">
          <div className="deliv-ico" style={{ width: 38, height: 38, background: "var(--surface-2)", color: "var(--ink-2)" }}>{I.gear}</div>
          <div style={{ flex: 1 }}>
            <div className="sheet-title">Settings</div>
            <div className="sheet-sub">How HQ briefs you, what the agents can do alone, and who else gets in.</div>
          </div>
          <button className="x-btn" onClick={onClose}>{I.x}</button>
        </div>
        <div className="set-tabs">
          {tabs.map((t) => (
            <button key={t.id} className="set-tab" data-active={tab === t.id} onClick={() => setTab(t.id)}>{t.ico}{t.label}</button>
          ))}
        </div>
        <div className="sheet-b">
          {tab === "brief" && (
            <React.Fragment>
              <div className="set-row">
                <div><div className="set-name">In-app brief</div><div className="set-sub">Your end-of-day brief lives on the command center.</div></div>
                <Seg value={settings.brief.inApp ? "on" : "off"} options={[{ v: "on", l: "On" }, { v: "off", l: "Off" }]} onChange={(v) => setBrief("inApp", v === "on")} />
              </div>
              <div className="set-row">
                <div><div className="set-name">Email me the brief</div><div className="set-sub">A formatted recap sent every day at <b>{settings.brief.time}</b>.</div></div>
                <Seg value={settings.brief.email ? "on" : "off"} options={[{ v: "on", l: "On" }, { v: "off", l: "Off" }]} onChange={(v) => setBrief("email", v === "on")} />
              </div>
              {settings.brief.email && (
                <div className="field" style={{ marginTop: 14 }}>
                  <label>Send to</label>
                  <input value={settings.brief.address} onChange={(e) => setBrief("address", e.target.value)} />
                </div>
              )}
              <div className="email-preview">
                <div className="ep-bar"><span>{I.mail}</span> EOD Brief · {settings.brief.time} · today</div>
                <div className="ep-body">
                  <div className="ep-h">Your day, in one place</div>
                  <div className="ep-line"><b>3</b> decisions need you · <b>2</b> risks · tomorrow's plan across Offers, Automation &amp; Traffic.</div>
                  <div className="ep-cta">Open the command center →</div>
                </div>
              </div>
            </React.Fragment>
          )}
          {tab === "trust" && (
            <React.Fragment>
              <div className="set-intro">Set how far the team runs without you. <b>Auto</b> = they just do it. <b>Ask</b> = it lands in “Needs you.” <b>Off</b> = they won't touch it.</div>
              {settings.trust.map((t) => (
                <div key={t.id} className="set-row">
                  <div className="set-name">{t.label}</div>
                  <Seg value={t.level} options={[{ v: "auto", l: "Auto" }, { v: "ask", l: "Ask" }, { v: "off", l: "Off" }]} onChange={(v) => setTrust(t.id, v)} />
                </div>
              ))}
            </React.Fragment>
          )}
          {tab === "team" && (
            <React.Fragment>
              <div className="set-intro">It's just you today. Invite VAs and team members when you're ready — they'll only see the accounts you scope them to.</div>
              {settings.team.map((m) => (
                <div key={m.id} className="member-row">
                  <span className="avatar md" style={{ background: m.role === "Owner" ? "linear-gradient(150deg, var(--accent), var(--accent-strong))" : "var(--ink-3)" }}>{m.name[0].toUpperCase()}</span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="set-name">{m.name} {m.role === "Owner" && <span className="role-chip owner">Owner</span>}</div>
                    <div className="set-sub">{m.email} · {m.scope}</div>
                  </div>
                  {m.role !== "Owner" && <span className="role-chip">{m.role}</span>}
                </div>
              ))}
              <div className="invite-box">
                <div className="post-flabel" style={{ margin: "0 0 10px" }}>Invite a teammate</div>
                <div className="field"><input value={invite.email} placeholder="email@address.com" onChange={(e) => setInvite({ ...invite, email: e.target.value })} /></div>
                <div className="field-row">
                  <div className="field"><label>Role</label>
                    <select value={invite.role} onChange={(e) => setInvite({ ...invite, role: e.target.value })}>
                      <option>VA</option><option>Manager</option><option>Contractor</option>
                    </select>
                  </div>
                  <div className="field"><label>Access</label>
                    <select value={invite.scope} onChange={(e) => setInvite({ ...invite, scope: e.target.value })}>
                      <option>Selected clients</option><option>All clients</option><option>All accounts</option>
                    </select>
                  </div>
                </div>
                <button className="btn btn-primary btn-sm" disabled={!invite.email.trim()} onClick={addMember}>{I.plus} Send invite</button>
              </div>
            </React.Fragment>
          )}
        </div>
      </div>
    </div>
  );
}

/* ---------- Workflow context (from a 'needs you' item) ---------- */
function WorkflowDetail({ item, data, clients, onApprove, onDecline, onChat, onClose }) {
  const client = clients.find((c) => c.id === item.clientId) || {};
  const isDecision = item.kind !== "risk";
  const owner = item.agent ? data.AGENTS.find((a) => a.id === item.agent) : null;
  const steps = (item.workflow && item.workflow.length)
    ? item.workflow
    : [{ agentId: item.agent || "atlas", label: item.detail || "Anubis is gathering context on this." }];
  return (
    <div className="ov" onClick={onClose}>
      <div className="sheet" onClick={(e) => e.stopPropagation()}>
        <div className="sheet-h">
          <div className="deliv-ico" style={{ width: 38, height: 38, background: "var(--accent-soft)", color: "var(--accent-ink)", borderColor: "var(--accent-line)" }}>{I.flow}</div>
          <div style={{ flex: 1 }}>
            <div className="sheet-title">{item.title}</div>
            <div className="sheet-sub">
              <span className="client-badge" style={{ background: client.color, width: 16, height: 16, fontSize: 7, display: "inline-grid", verticalAlign: "middle", marginRight: 6 }}>{client.initials}</span>
              {client.name} · {item.kind === "risk" ? "Risk" : item.tag || "Decision"}
            </div>
          </div>
          <button className="x-btn" onClick={onClose}>{I.x}</button>
        </div>
        <div className="sheet-b">
          <div className="wf-context">{item.detail}</div>
          <div className="post-flabel" style={{ margin: "18px 0 12px" }}>How this resolves</div>
          <div className="wf-steps">
            {steps.map((s, i) => {
              const a = data.AGENTS.find((x) => x.id === s.agentId);
              return (
                <div key={i} className="wf-step">
                  <div className="wf-line"></div>
                  {a ? <Avatar agent={a} size="sm" /> : <span className="wf-dot"></span>}
                  <div>
                    <div className="wf-step-label">{s.label}</div>
                    {a && <div className="wf-step-agent">{a.name} · {a.role}</div>}
                  </div>
                </div>
              );
            })}
          </div>
          <div className="actions" style={{ marginTop: 20 }}>
            {isDecision && <button className="btn btn-primary" onClick={() => onApprove(item.clientId, item.id)}>{I.check} Approve &amp; ship</button>}
            {isDecision && <button className="btn btn-ghost" onClick={() => onDecline(item.clientId, item.id)}>Send back</button>}
            {owner && <button className="btn btn-ghost" onClick={() => onChat(owner)}>{I.send} Chat with {owner.name}</button>}
            {!isDecision && <button className="btn btn-ghost" onClick={onClose}>Close</button>}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DEFAULT_SETTINGS, EscalationInbox, SettingsModal, WorkflowDetail });