// Admin (owner) console — manage team, websites, templates, auto-reply, settings + analytics.
const { Card: ACard, Pill: APill, Btn: ABtn, Avatar: AAvatar, Topbar: ATopbar, Input: AInput, Textarea: ATextarea, Tabs: ATabs, Modal: AModal, Field: AField } = window.UI;

function Admin({ authAgent }) {
  // Owner Admin = global console. Manager = client admin scoped to their own
  // websites (the server enforces this; the UI hides what they can't touch).
  const isOwner = !authAgent || authAgent.role === "Admin";
  const myScope = (authAgent && authAgent.websites) || [];
  const [tab, setTab] = React.useState("analytics");
  const [tick, setTick] = React.useState(0);
  const [settings, setSettings] = React.useState(null);
  const [analytics, setAnalytics] = React.useState(null);
  const [add, setAdd] = React.useState(null);     // { kind, form }
  const [rulesDraft, setRulesDraft] = React.useState([]);

  React.useEffect(() => {
    if (isOwner) window.LoopData.getSettings().then((s) => { setSettings(s); setRulesDraft((s && s.rules) ? s.rules.map((r) => ({ ...r })) : []); });
    window.LoopData.getAnalytics().then(setAnalytics);
  }, [tick]);

  const agents = window.Mock.agents || [];
  const websites = window.Mock.websites || [];
  const canned = window.Mock.cannedResponses || [];
  const concerns = window.Mock.concerns || [];

  const reload = async () => { try { await window.LoopData.bootstrap(); } catch (e) {} setTick((t) => t + 1); };
  const create = async (kind, obj) => { await window.LoopData.adminCreate(kind, obj); setAdd(null); await reload(); };
  const remove = async (kind, id) => { await window.LoopData.adminDelete(kind, id); await reload(); };
  const saveSettings = async (patch) => { const s = await window.LoopData.saveSettings(patch); setSettings(s); };

  const host = (typeof location !== "undefined" ? location.origin : "https://your-loop-host");

  // ---- Add modal ----
  const F = (add && add.form) || {};
  const setF = (k, v) => setAdd((a) => ({ ...a, form: { ...a.form, [k]: v } }));
  const addModal = (
    <AModal open={!!add} onClose={() => setAdd(null)} title={add ? add.title : ""} width={460}>
      {add && add.kind === "agents" && (
        <div className="space-y-3">
          <AField label="Name"><AInput value={F.name || ""} onChange={(e) => setF("name", e.target.value)} placeholder="CS Bea" /></AField>
          <AField label="Email"><AInput value={F.email || ""} onChange={(e) => setF("email", e.target.value)} placeholder="bea@loop.cs" /></AField>
          <AField label="Password" hint="The agent signs in with this. Required."><AInput type="password" value={F.password || ""} onChange={(e) => setF("password", e.target.value)} placeholder="Set a password" /></AField>
          <AField label="Role" hint={isOwner ? "Manager = client admin, sees only their own websites" : undefined}>
            <div className="flex gap-2">
              {(isOwner ? ["CSR", "Manager", "Admin"] : ["CSR"]).map((r) => (
                <button key={r} onClick={() => setF("role", r)} className={`flex-1 h-9 rounded-xl border text-[13px] ${(F.role || "CSR") === r ? "border-lime/50 bg-lime/10 text-lime" : "border-white/[0.08] text-white/70"}`}>{r}</button>
              ))}
            </div>
          </AField>
          <AField label="Assign to websites">
            <div className="flex flex-wrap gap-1.5">
              {websites.map((w) => {
                const sel = (F.websites || []).includes(w.id);
                return <button key={w.id} onClick={() => setF("websites", sel ? (F.websites || []).filter((x) => x !== w.id) : [...(F.websites || []), w.id])} className={`text-[11.5px] px-2.5 py-1 rounded-full border ${sel ? "border-lime/50 bg-lime/10 text-lime" : "border-white/[0.1] text-white/60"}`}>{w.name}</button>;
              })}
            </div>
          </AField>
          <ABtn variant="primary" className="w-full" disabled={!F.password} onClick={() => create("agents", { name: F.name, email: F.email, password: F.password, role: F.role || "CSR", websites: F.websites || [] })}>Add agent</ABtn>
        </div>
      )}
      {add && add.kind === "websites" && (
        <div className="space-y-3">
          <AField label="Website name"><AInput value={F.name || ""} onChange={(e) => setF("name", e.target.value)} placeholder="Acme Store" /></AField>
          <AField label="Primary domain"><AInput value={F.domain || ""} onChange={(e) => setF("domain", e.target.value)} placeholder="acme.com" /></AField>
          <AField label="Brand color">
            <div className="flex items-center gap-2">
              <input type="color" value={F.color || "#A6F84A"} onChange={(e) => setF("color", e.target.value)} className="h-9 w-12 rounded-lg bg-transparent border border-white/[0.1] cursor-pointer" />
              <AInput value={F.color || ""} onChange={(e) => setF("color", e.target.value)} placeholder="#A6F84A" />
            </div>
          </AField>
          <AField label="Logo URL" hint="https URL to the brand logo (optional)"><AInput value={F.logoUrl || ""} onChange={(e) => setF("logoUrl", e.target.value)} placeholder="https://acme.com/logo.png" /></AField>
          <AField label="Allowed domains (comma-separated)" hint="Domains that may embed the widget"><AInput value={F.allowed || ""} onChange={(e) => setF("allowed", e.target.value)} placeholder="acme.com, www.acme.com, localhost" /></AField>
          <ABtn variant="primary" className="w-full" onClick={() => create("websites", { name: F.name, domain: F.domain, color: F.color || undefined, logoUrl: F.logoUrl || undefined, allowed: (F.allowed || "localhost").split(",").map((x) => x.trim()).filter(Boolean) })}>Create website</ABtn>
        </div>
      )}
      {add && add.kind === "canned" && (
        <div className="space-y-3">
          <AField label="Title"><AInput value={F.title || ""} onChange={(e) => setF("title", e.target.value)} placeholder="Promo announcement" /></AField>
          <AField label="Shortcut"><AInput value={F.shortcut || ""} onChange={(e) => setF("shortcut", e.target.value)} placeholder="/promo" /></AField>
          <AField label="Body"><ATextarea rows={3} value={F.body || ""} onChange={(e) => setF("body", e.target.value)} placeholder="Message text…" /></AField>
          <ABtn variant="primary" className="w-full" onClick={() => create("canned", { title: F.title, shortcut: F.shortcut, body: F.body })}>Add template</ABtn>
        </div>
      )}
    </AModal>
  );

  return (
    <div className="flex-1 flex flex-col h-full overflow-hidden">
      <ATopbar title="Admin" subtitle={isOwner ? "Manage your team, websites, templates and auto-reply" : "Manage your own team and websites"} />
      <div className="px-7 pt-4">
        <ATabs value={tab} onChange={setTab} tabs={[
          { value: "analytics", label: "Analytics" }, { value: "team", label: "Team", count: agents.length },
          { value: "websites", label: "Websites", count: websites.length },
          ...(isOwner ? [
            { value: "templates", label: "Templates", count: canned.length },
            { value: "autoreply", label: "Auto-reply" }, { value: "settings", label: "Settings" },
          ] : []),
        ]} />
      </div>
      <div className="flex-1 overflow-y-auto px-7 py-5 space-y-4">

        {tab === "analytics" && analytics && (
          <>
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
              {[["Conversations", analytics.total], ["Agents online", analytics.agents.online + " / " + analytics.agents.total], ["Websites", analytics.websites], ["Avg rating", (analytics.avgRating || 0) + " ★ (" + analytics.ratedCount + ")"]].map(([l, v]) => (
                <ACard key={l}><div className="text-[11px] uppercase tracking-wider text-white/45">{l}</div><div className="text-[26px] font-semibold text-white mt-2 leading-none">{v}</div></ACard>
              ))}
            </div>
            {[["By channel", analytics.byChannel], ["By status", analytics.byStatus], ["By concern", analytics.byConcern]].map(([title, obj]) => (
              <ACard key={title}><div className="text-[13px] font-medium text-white/90 mb-2">{title}</div>
                <div className="flex flex-wrap gap-2">{Object.keys(obj).map((k) => <APill key={k}>{k}: {obj[k]}</APill>)}</div>
              </ACard>
            ))}
            <ACard>
              <div className="text-[13px] font-medium text-white/90 mb-2">CSAT by agent <span className="text-white/40 font-normal">· positive ratings / total</span></div>
              {(analytics.perAgentCsat && analytics.perAgentCsat.length) ? (
                <div className="space-y-1.5">
                  {analytics.perAgentCsat.map((a) => (
                    <div key={a.agentId} className="flex items-center gap-3">
                      <div className="text-[12.5px] text-white/85 w-40 truncate">{a.name}</div>
                      <div className="flex-1 h-1.5 rounded-full bg-white/[0.07] overflow-hidden"><div className="h-full bg-lime" style={{ width: a.csat + "%" }} /></div>
                      <div className="text-[12px] text-white/70 w-24 text-right">{a.csat}% <span className="text-white/40">· n={a.ratings}</span></div>
                    </div>
                  ))}
                </div>
              ) : <div className="text-[12px] text-white/45">No ratings yet. CSAT appears once customers rate their chats.</div>}
            </ACard>
          </>
        )}

        {tab === "team" && (
          <ACard padded={false}>
            <div className="flex items-center justify-between p-4 border-b border-white/[0.05]"><div className="text-[14px] font-medium text-white/95">Agents & CSRs</div><ABtn variant="primary" size="sm" onClick={() => setAdd({ kind: "agents", title: "Add agent", form: {} })}><Icon.Plus size={13} /> Add agent</ABtn></div>
            <div className="divide-y divide-white/[0.04]">
              {agents.map((a) => {
                const canRemove = isOwner || (a.role === "CSR" && (a.websites || []).every((w) => myScope.includes(w)));
                return (
                <div key={a.id} className="flex items-center gap-3 px-4 py-3">
                  <AAvatar name={a.name} color={a.color} size={34} status={a.status} />
                  <div className="flex-1 min-w-0"><div className="text-[13px] text-white/95 font-medium">{a.name}</div><div className="text-[11.5px] text-white/45">{a.email} · {(a.websites || []).length} site(s)</div></div>
                  <APill tone={a.role === "Admin" ? "lime" : a.role === "Manager" ? "blue" : "default"}>{a.role}</APill>
                  {canRemove && <button onClick={() => remove("agents", a.id)} className="h-8 w-8 grid place-items-center rounded-lg hover:bg-rose-500/15 text-white/40 hover:text-rose-300"><Icon.Trash size={15} /></button>}
                </div>
                );
              })}
            </div>
          </ACard>
        )}

        {tab === "websites" && (
          <ACard padded={false}>
            <div className="flex items-center justify-between p-4 border-b border-white/[0.05]"><div className="text-[14px] font-medium text-white/95">Websites & widget keys</div><ABtn variant="primary" size="sm" onClick={() => setAdd({ kind: "websites", title: "Create website", form: {} })}><Icon.Plus size={13} /> Add website</ABtn></div>
            <div className="divide-y divide-white/[0.04]">
              {websites.map((w) => (
                <div key={w.id} className="px-4 py-3.5 space-y-2">
                  <div className="flex items-center gap-2.5">
                    <span className="w-2.5 h-2.5 rounded-full" style={{ background: w.color }} />
                    <div className="flex-1"><div className="text-[13px] text-white/95 font-medium">{w.name}</div><div className="text-[11.5px] text-white/45">{w.domain} · widget key <span className="font-mono text-lime">{w.id}</span></div></div>
                    <button onClick={() => remove("websites", w.id)} className="h-8 w-8 grid place-items-center rounded-lg hover:bg-rose-500/15 text-white/40 hover:text-rose-300"><Icon.Trash size={15} /></button>
                  </div>
                  <div className="text-[10.5px] text-white/40">Embed snippet</div>
                  <input readOnly onFocus={(e) => e.target.select()} value={`<script src="${host}/loader.js" data-property="${w.id}" async></script>`} className="w-full h-9 px-3 rounded-lg bg-white/[0.03] border border-white/[0.07] text-[11px] font-mono text-white/70" />
                </div>
              ))}
            </div>
          </ACard>
        )}

        {tab === "templates" && (
          <ACard padded={false}>
            <div className="flex items-center justify-between p-4 border-b border-white/[0.05]"><div className="text-[14px] font-medium text-white/95">Canned templates</div><ABtn variant="primary" size="sm" onClick={() => setAdd({ kind: "canned", title: "Add template", form: {} })}><Icon.Plus size={13} /> Add template</ABtn></div>
            <div className="divide-y divide-white/[0.04]">
              {canned.map((c) => (
                <div key={c.id} className="flex items-start gap-3 px-4 py-3">
                  <span className="text-[10.5px] font-mono text-lime mt-0.5 shrink-0">{c.shortcut}</span>
                  <div className="flex-1 min-w-0"><div className="text-[12.5px] text-white/95 font-medium">{c.title}</div><div className="text-[11.5px] text-white/55 line-clamp-2">{c.body}</div></div>
                  <button onClick={() => remove("canned", c.id)} className="h-8 w-8 grid place-items-center rounded-lg hover:bg-rose-500/15 text-white/40 hover:text-rose-300"><Icon.Trash size={15} /></button>
                </div>
              ))}
            </div>
          </ACard>
        )}

        {tab === "autoreply" && settings && (
          <ACard className="space-y-4">
            <div className="flex items-center justify-between">
              <div><div className="text-[14px] font-medium text-white/95">Auto-reply</div><div className="text-[12px] text-white/50 mt-0.5">Greets the visitor and routes the concern on first message.</div></div>
              <button onClick={() => saveSettings({ autoReply: !settings.autoReply })} className={`h-7 w-12 rounded-full transition relative ${settings.autoReply ? "bg-lime" : "bg-white/[0.12]"}`}><span className={`absolute top-0.5 ${settings.autoReply ? "right-0.5" : "left-0.5"} w-6 h-6 rounded-full bg-white transition-all`} /></button>
            </div>
            <div className="space-y-2.5">
              {rulesDraft.map((r, i) => (
                <div key={i} className="rounded-xl border border-white/[0.07] p-3 space-y-2">
                  <div className="text-[12px] font-medium text-lime">{(concerns.find((c) => c.id === r.concern) || {}).label || r.concern}</div>
                  <AInput value={r.keywords} onChange={(e) => setRulesDraft((d) => d.map((x, j) => j === i ? { ...x, keywords: e.target.value } : x))} placeholder="keywords (regex) — leave blank for default" />
                  <ATextarea rows={2} value={r.ask} onChange={(e) => setRulesDraft((d) => d.map((x, j) => j === i ? { ...x, ask: e.target.value } : x))} />
                </div>
              ))}
            </div>
            <ABtn variant="primary" onClick={() => saveSettings({ rules: rulesDraft })}>Save rules</ABtn>
          </ACard>
        )}

        {tab === "settings" && settings && (
          <ACard className="space-y-3 max-w-lg">
            <AField label="Workspace / brand name"><AInput value={settings.brand || ""} onChange={(e) => setSettings({ ...settings, brand: e.target.value })} /></AField>
            <AField label="Availability message"><AInput value={settings.hours || ""} onChange={(e) => setSettings({ ...settings, hours: e.target.value })} /></AField>
            <ABtn variant="primary" onClick={() => saveSettings({ brand: settings.brand, hours: settings.hours })}>Save settings</ABtn>
          </ACard>
        )}
      </div>
      {addModal}
    </div>
  );
}

window.Admin = Admin;
