// Websites page
const { Card: WsCard, Pill: WsPill, Btn: WsBtn, Avatar: WsAvatar, Topbar: WsTopbar, Modal: WsModal, Field: WsField, Input: WsInput } = window.UI;

const CONCERN_ICONS = ["Shield","Tag","Bolt","Globe","Bell","Chat","Phone","Lock","Image","Note","Zap","Sparkle","Eye","Search","Bookmark","Settings"];
const CONCERN_COLORS = ["#A6F84A","#7AB6FF","#FF9DD2","#FFD37A","#C7B6FF","#FF6B6B","#6366F1","#F97316"];

function Websites() {
  // Live per-site counts from the user's real (scoped) conversations. The old
  // w.activeChats / w.waiting fields only existed on seeded demo sites, so
  // real/created sites showed blank and never updated — compute them here.
  const siteStats = (id) => {
    const cs = (window.Mock.conversations || []).filter((c) => c.site === id);
    return { active: cs.filter((c) => c.status === "active").length, waiting: cs.filter((c) => c.status === "waiting").length };
  };
  const [showAdd, setShowAdd] = React.useState(false);
  const [showEmbed, setShowEmbed] = React.useState(null);
  const [showConfigure, setShowConfigure] = React.useState(null);
  const [view, setView] = React.useState("cards");
  const [color, setColor] = React.useState("#A6F84A");
  const [name, setName] = React.useState("");
  const [domain, setDomain] = React.useState("");
  const [team, setTeam] = React.useState("Tier 1 · Manila");
  const [allowedText, setAllowedText] = React.useState("");
  const [saving, setSaving] = React.useState(false);
  const [err, setErr] = React.useState("");
  const [, setTick] = React.useState(0);
  // Configure modal state
  const [cfgTab, setCfgTab] = React.useState("concerns");
  const [cfgConcerns, setCfgConcerns] = React.useState([]);
  const [cfgKnowledge, setCfgKnowledge] = React.useState("");
  const [cfgWelcome, setCfgWelcome] = React.useState("");
  const [cfgTitle, setCfgTitle] = React.useState("");
  const [cfgTagline, setCfgTagline] = React.useState("");
  const [cfgPhone, setCfgPhone] = React.useState(false);
  const [cfgUsername, setCfgUsername] = React.useState(false);
  const [cfgSaving, setCfgSaving] = React.useState(false);
  const [cfgNewLabel, setCfgNewLabel] = React.useState("");
  const [cfgNewIcon, setCfgNewIcon] = React.useState("Shield");
  const [cfgNewTint, setCfgNewTint] = React.useState("#A6F84A");

  const [cfgSuggesting, setCfgSuggesting] = React.useState(false);
  const openConfigure = (w) => {
    setCfgTab("concerns");
    // Use site concerns if non-empty, else seed with global defaults
    const base = (w.concerns && w.concerns.length > 0) ? [...w.concerns] : [...(window.Mock.concerns || [])];
    setCfgConcerns(base);
    setCfgKnowledge(w.aiKnowledge || "");
    setCfgWelcome(w.prechatWelcome || "");
    setCfgTitle(w.widgetTitle || "");
    setCfgTagline(w.widgetTagline || "");
    setCfgPhone(!!w.collectPhone);
    setCfgUsername(!!w.collectUsername);
    setCfgNewLabel(""); setCfgNewIcon("Shield"); setCfgNewTint("#A6F84A");
    setShowConfigure(w);
  };
  const suggestConcerns = async () => {
    if (!showConfigure) return;
    setCfgSuggesting(true);
    try {
      const r = await fetch(`/api/admin/websites/${showConfigure.id}/suggest-concerns`, {
        method: "POST", headers: { "Content-Type": "application/json", "Authorization": "Bearer " + (localStorage.getItem("loop_token") || "") }
      });
      const d = await r.json();
      if (!r.ok) { alert("Suggest failed: " + (d.error || r.status)); setCfgSuggesting(false); return; }
      if (d.concerns && d.concerns.length) setCfgConcerns(d.concerns);
    } catch(e) { alert("Suggest failed: " + e.message); }
    setCfgSuggesting(false);
  };
  const addConcern = () => {
    if (!cfgNewLabel.trim()) return;
    const id = cfgNewLabel.toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 20);
    setCfgConcerns(prev => [...prev, { id, label: cfgNewLabel.trim(), icon: cfgNewIcon, tint: cfgNewTint }]);
    setCfgNewLabel(""); setCfgNewIcon("Shield"); setCfgNewTint("#A6F84A");
  };
  const removeConcern = (idx) => setCfgConcerns(prev => prev.filter((_, i) => i !== idx));
  // Edit website state
  const [showEdit, setShowEdit] = React.useState(null);
  const [editName, setEditName] = React.useState("");
  const [editDomain, setEditDomain] = React.useState("");
  const [editTeam, setEditTeam] = React.useState("");
  const [editColor, setEditColor] = React.useState("#A6F84A");
  const [editLogoUrl, setEditLogoUrl] = React.useState("");
  const [editAllowed, setEditAllowed] = React.useState("");
  const [editWidgetTheme, setEditWidgetTheme] = React.useState("dark");
  const [editSaving, setEditSaving] = React.useState(false);
  const openEdit = (w) => { setEditName(w.name||""); setEditDomain(w.domain||""); setEditTeam(w.team||""); setEditColor(w.color||"#A6F84A"); setEditLogoUrl(w.logoUrl||""); setEditAllowed((w.allowed||[]).join("\n")); setEditWidgetTheme(w.widgetTheme||"dark"); setShowEdit(w); };
  const saveEdit = async () => {
    if (!showEdit) return;
    setEditSaving(true);
    try {
      const allowed = editAllowed.split(/[\n,]/).map(x=>x.trim()).filter(Boolean);
      await window.LoopData.adminUpdate("websites", showEdit.id, { name: editName.trim(), domain: editDomain.trim(), team: editTeam, color: editColor, logoUrl: editLogoUrl.trim(), allowed: allowed.length ? allowed : ["localhost"], widgetTheme: editWidgetTheme });
      await window.LoopData.bootstrap().catch(()=>{});
      setShowEdit(null); setTick(t=>t+1);
    } catch(e) { alert("Save failed: "+(e.message||e)); }
    setEditSaving(false);
  };

  const saveConfigure = async () => {
    if (!showConfigure) return;
    setCfgSaving(true);
    try {
      const patch = { concerns: cfgConcerns, aiKnowledge: cfgKnowledge, prechatWelcome: cfgWelcome.trim(), widgetTitle: cfgTitle.trim(), widgetTagline: cfgTagline.trim(), collectPhone: cfgPhone, collectUsername: cfgUsername, widgetTheme: editWidgetTheme };
      await window.LoopData.adminUpdate("websites", showConfigure.id, patch);
      // Mutate window.Mock.websites directly so re-open reflects saved state immediately
      const idx = (window.Mock.websites || []).findIndex(x => x.id === showConfigure.id);
      if (idx !== -1) Object.assign(window.Mock.websites[idx], patch);
      setShowConfigure(null);
      setTick(t => t + 1);
    } catch(e) { alert("Save failed: " + (e.message || e)); }
    setCfgSaving(false);
  };

  const resetForm = () => { setName(""); setDomain(""); setTeam("Tier 1 · Manila"); setAllowedText(""); setColor("#A6F84A"); setErr(""); };
  const closeAdd = () => { setShowAdd(false); resetForm(); };

  const createWebsite = async () => {
    if (!name.trim()) { setErr("Website name is required."); return; }
    setSaving(true); setErr("");
    try {
      const allowed = allowedText.split(/[\n,]/).map((x) => x.trim()).filter(Boolean);
      await window.LoopData.adminCreate("websites", {
        name: name.trim(),
        domain: domain.trim(),
        color,
        team,
        allowed: allowed.length ? allowed : [domain.trim() || "localhost"],
      });
      try { await window.LoopData.bootstrap(); } catch (e) {}
      setSaving(false);
      closeAdd();
      setTick((t) => t + 1);
    } catch (e) {
      setSaving(false);
      setErr((e && e.message) || "Could not create website. Make sure you're signed in as an Admin.");
    }
  };

  // The real, working loader: loader.js on THIS deployment, keyed by the site
  // id via data-property. One snippet works on every domain of the brand
  // (including mirror domains) — no per-domain change needed.
  const embedHost = (typeof location !== "undefined" ? location.origin : "https://your-loop-host");
  const embedCode = (site) => `<!-- Loop Live Chat -->
<script src="${embedHost}/loader.js" data-property="${site?.id || 'YOUR_SITE_ID'}" async></script>`;
  const [copied, setCopied] = React.useState(false);
  const copyEmbed = async (site) => {
    try { await navigator.clipboard.writeText(embedCode(site)); setCopied(true); setTimeout(() => setCopied(false), 1500); }
    catch (e) { /* clipboard blocked — the user can still select the snippet manually */ }
  };

  return (
    <div className="flex-1 flex flex-col h-full overflow-hidden">
      <WsTopbar
        title="Websites"
        subtitle={`${window.Mock.websites.length} brands connected to Loop`}
        right={
          <div className="flex items-center gap-2">
            <div className="inline-flex p-1 rounded-xl bg-white/[0.04] border border-white/[0.06]">
              <button onClick={() => setView("cards")} className={`h-7 px-2.5 rounded-lg text-[11.5px] ${view === "cards" ? "bg-white/[0.08] text-white" : "text-white/55"}`}>Cards</button>
              <button onClick={() => setView("table")} className={`h-7 px-2.5 rounded-lg text-[11.5px] ${view === "table" ? "bg-white/[0.08] text-white" : "text-white/55"}`}>Table</button>
            </div>
            <WsBtn variant="primary" onClick={() => setShowAdd(true)}><Icon.Plus size={14}/> Add website</WsBtn>
          </div>
        }
      />

      <div className="flex-1 overflow-y-auto px-7 py-6">
        {view === "cards" ? (
          <div className="grid md:grid-cols-2 xl:grid-cols-3 gap-5">
            {window.Mock.websites.map(w => (
              <WsCard key={w.id} className="overflow-hidden relative">
                <div className="absolute -top-12 -right-12 w-40 h-40 rounded-full opacity-20" style={{ background: `radial-gradient(circle, ${w.color}, transparent 70%)` }}/>
                <div className="relative">
                  <div className="flex items-start justify-between">
                    <div className="flex items-center gap-3">
                      <div className="w-12 h-12 rounded-2xl grid place-items-center font-bold text-ink-950 text-[14px] shadow-lg" style={{ background: `linear-gradient(135deg, ${w.color}, ${w.color}cc)` }}>{w.initials}</div>
                      <div>
                        <div className="text-[15px] font-semibold text-white/95">{w.name}</div>
                        <div className="text-[11.5px] text-white/45 font-mono mt-0.5">{w.domain}</div>
                      </div>
                    </div>
                    <button onClick={() => openEdit(w)} title="Edit website" className="text-white/40 hover:text-white p-1"><Icon.Settings size={16}/></button>
                  </div>

                  <div className="flex items-center gap-2 mt-4">
                    <WsPill tone={w.online ? "lime" : "default"}>
                      <span className={`w-1.5 h-1.5 rounded-full ${w.online ? "bg-lime dot-online" : "bg-zinc-500"}`}/>
                      {w.online ? "Live" : "Offline"}
                    </WsPill>
                    <WsPill>{w.team}</WsPill>
                  </div>

                  <div className="grid grid-cols-3 gap-2 mt-4 pt-4 border-t border-white/[0.05]">
                    <Stat label="Active" value={siteStats(w.id).active} tint="#A6F84A"/>
                    <Stat label="Waiting" value={siteStats(w.id).waiting} tint="#FFD37A"/>
                    <Stat label="Color" value={
                      <span className="flex items-center gap-1.5">
                        <span className="w-3 h-3 rounded-full" style={{ background: w.color }}/>
                        <span className="text-[11px] font-mono">{w.color}</span>
                      </span>
                    }/>
                  </div>

                  <div className="mt-4">
                    <div className="text-[10.5px] uppercase tracking-wider text-white/40 mb-1.5">Allowed domains</div>
                    <div className="flex flex-wrap gap-1">
                      {w.allowed.map(d => <span key={d} className="text-[10.5px] font-mono text-white/65 px-2 py-0.5 rounded-md bg-white/[0.04] border border-white/[0.06]">{d}</span>)}
                    </div>
                  </div>

                  <div className="grid grid-cols-3 gap-2 mt-5">
                    <WsBtn variant="ghost" size="sm" onClick={() => window.open(`/demo-site.html?property=${encodeURIComponent(w.id)}`, "_blank")}><Icon.Eye size={13}/> Preview</WsBtn>
                    <WsBtn variant="ghost" size="sm" onClick={() => setShowEmbed(w)}><Icon.Code size={13}/> Embed</WsBtn>
                    <WsBtn variant="ghost" size="sm" onClick={() => openConfigure(w)}><Icon.Settings size={13}/> Configure</WsBtn>
                  </div>
                </div>
              </WsCard>
            ))}
            {/* Add card */}
            <button onClick={() => setShowAdd(true)} className="rounded-2xl border border-dashed border-white/[0.1] p-6 grid place-items-center min-h-[300px] hover:border-lime/40 hover:bg-lime/[0.02] transition group">
              <div className="text-center">
                <div className="mx-auto grid place-items-center w-12 h-12 rounded-xl bg-white/[0.04] group-hover:bg-lime/15 group-hover:text-lime text-white/60 mb-3"><Icon.Plus size={20}/></div>
                <div className="text-[14px] font-medium text-white/85">Add a new website</div>
                <div className="text-[12px] text-white/40 mt-1">Drop the snippet on any domain</div>
              </div>
            </button>
          </div>
        ) : (
          <WsCard padded={false}>
            <table className="w-full text-[13px]">
              <thead className="text-[11px] uppercase tracking-wider text-white/45 border-b border-white/[0.05]">
                <tr>
                  <th className="text-left px-5 py-3 font-medium">Website</th>
                  <th className="text-left px-3 py-3 font-medium">Status</th>
                  <th className="text-left px-3 py-3 font-medium">Team</th>
                  <th className="text-left px-3 py-3 font-medium">Active</th>
                  <th className="text-left px-3 py-3 font-medium">Color</th>
                  <th className="text-right px-5 py-3 font-medium">Actions</th>
                </tr>
              </thead>
              <tbody>
                {window.Mock.websites.map(w => (
                  <tr key={w.id} className="border-b border-white/[0.04] hover:bg-white/[0.02]">
                    <td className="px-5 py-3.5">
                      <div className="flex items-center gap-3">
                        <div className="w-9 h-9 rounded-xl grid place-items-center font-bold text-ink-950 text-[11px]" style={{ background: w.color }}>{w.initials}</div>
                        <div>
                          <div className="text-white/95 font-medium">{w.name}</div>
                          <div className="text-[11px] text-white/45 font-mono">{w.domain}</div>
                        </div>
                      </div>
                    </td>
                    <td className="px-3"><WsPill tone={w.online ? "lime" : "default"}><span className={`w-1.5 h-1.5 rounded-full ${w.online ? "bg-lime" : "bg-zinc-500"}`}/>{w.online ? "Live" : "Offline"}</WsPill></td>
                    <td className="px-3 text-white/75">{w.team}</td>
                    <td className="px-3 text-white/85 font-mono">{siteStats(w.id).active}</td>
                    <td className="px-3"><span className="flex items-center gap-1.5"><span className="w-3 h-3 rounded-full" style={{background: w.color}}/><span className="text-[11px] font-mono text-white/65">{w.color}</span></span></td>
                    <td className="px-5 text-right">
                      <button onClick={() => window.open(`/demo-site.html?property=${encodeURIComponent(w.id)}`, "_blank")} className="text-lime text-[12px] hover:underline">Preview</button>
                      <span className="text-white/15 mx-2">·</span>
                      <button onClick={() => setShowEmbed(w)} className="text-lime text-[12px] hover:underline">Embed</button>
                      <span className="text-white/15 mx-2">·</span>
                      <button onClick={() => openEdit(w)} className="text-white/55 text-[12px] hover:text-white">Edit</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </WsCard>
        )}
      </div>

      {/* Embed modal */}
      <WsModal open={!!showEmbed} onClose={() => setShowEmbed(null)} title="Embed code" subtitle={showEmbed && `Drop this snippet on every page of ${showEmbed.domain}`} width={620}>
        <div className="rounded-xl overflow-hidden border border-white/[0.08]">
          <div className="flex items-center justify-between px-3 py-2 bg-white/[0.03] border-b border-white/[0.06]">
            <span className="text-[11px] font-mono text-white/55">install.html · place before &lt;/body&gt;</span>
            <button onClick={() => copyEmbed(showEmbed)} className="text-[11px] text-lime flex items-center gap-1 hover:underline"><Icon.Copy size={12}/> {copied ? "Copied!" : "Copy"}</button>
          </div>
          <pre className="p-4 text-[11.5px] leading-relaxed font-mono text-white/85 overflow-x-auto bg-ink-950">
{embedCode(showEmbed)}
          </pre>
        </div>
        <div className="flex items-center gap-2 mt-4 text-[12px] text-white/55">
          <Icon.Help size={14} className="text-white/45"/>
          The widget appears within seconds. CSP-safe and async.
        </div>
      </WsModal>

      {/* Edit website modal */}
      <WsModal open={!!showEdit} onClose={() => setShowEdit(null)} title={`Edit — ${showEdit && showEdit.name}`} subtitle="Update website name, domain, color, and allowed origins." width={540}>
        <div className="space-y-4">
          <WsField label="Website name"><WsInput value={editName} onChange={e=>setEditName(e.target.value)} placeholder="e.g. Vertex Gaming Solutions"/></WsField>
          <div className="grid grid-cols-2 gap-3">
            <WsField label="Primary domain"><WsInput value={editDomain} onChange={e=>setEditDomain(e.target.value)} placeholder="vertex.com"/></WsField>
            <WsField label="Team">
              <select value={editTeam} onChange={e=>setEditTeam(e.target.value)} className="w-full h-10 px-3 rounded-xl bg-white/[0.03] border border-white/[0.07] text-[13px]">
                <option>Tier 1 · Manila</option><option>Partners · Cebu</option><option>Beta crew</option><option>iGaming · Infrastructure</option>
              </select>
            </WsField>
          </div>
          <WsField label="Widget color">
            <div className="flex items-center gap-3">
              <div className="flex gap-2">{["#A6F84A","#7AB6FF","#FF9DD2","#FFD37A","#C7B6FF","#FF6B6B"].map(c=><button key={c} onClick={()=>setEditColor(c)} className={`w-9 h-9 rounded-xl ${editColor===c?"ring-2 ring-white":""}`} style={{background:c}}/>)}</div>
              <input value={editColor} onChange={e=>setEditColor(e.target.value)} className="flex-1 h-10 px-3 rounded-xl bg-white/[0.03] border border-white/[0.07] text-[13px] font-mono"/>
            </div>
          </WsField>
          <WsField label="Logo URL" hint="https URL shown in the widget header (optional).">
            <div className="flex items-center gap-3">
              {editLogoUrl ? <img src={editLogoUrl} alt="" className="w-10 h-10 rounded-xl object-contain bg-white/[0.06]" onError={e=>{e.target.style.visibility="hidden";}}/> : null}
              <WsInput value={editLogoUrl} onChange={e=>setEditLogoUrl(e.target.value)} placeholder="https://vertex.com/logo.png"/>
            </div>
          </WsField>
          <WsField label="Allowed domains" hint="One per line — domains the widget is allowed to load on.">
            <textarea rows={3} value={editAllowed} onChange={e=>setEditAllowed(e.target.value)} className="w-full px-3 py-2.5 rounded-xl bg-white/[0.03] border border-white/[0.07] text-[12.5px] font-mono resize-none" placeholder={"vertex.com\napp.vertex.com\nlocalhost"}/>
          </WsField>
          <div className="flex justify-end gap-2 pt-2">
            <WsBtn variant="quiet" onClick={()=>setShowEdit(null)}>Cancel</WsBtn>
            <WsBtn variant="primary" onClick={saveEdit} disabled={editSaving}>{editSaving?"Saving…":"Save changes"}</WsBtn>
          </div>
        </div>
      </WsModal>

      {/* Configure modal */}
      <WsModal open={!!showConfigure} onClose={() => setShowConfigure(null)} title={`Configure — ${showConfigure && showConfigure.name}`} subtitle="Set per-brand concern categories, pre-chat form and AI knowledge." width={620}>
        {/* Tabs */}
        <div className="flex gap-1 mb-5 bg-white/[0.04] rounded-xl p-1 w-fit">
          {["concerns","prechat","ai-knowledge"].map(t => (
            <button key={t} onClick={() => setCfgTab(t)} className={`px-4 py-1.5 rounded-lg text-[12.5px] font-medium transition ${cfgTab === t ? "bg-white/[0.1] text-white" : "text-white/50 hover:text-white/80"}`}>
              {t === "concerns" ? "Concern Categories" : t === "prechat" ? "Pre-chat Form" : "AI Knowledge"}
            </button>
          ))}
        </div>

        {cfgTab === "concerns" && (
          <div className="space-y-3">
            {cfgConcerns.map((c, i) => (
              <div key={i} className="flex items-center gap-3 px-3 py-2.5 rounded-xl bg-white/[0.03] border border-white/[0.06]">
                <span className="w-3 h-3 rounded-full flex-shrink-0" style={{ background: c.tint }}/>
                <span className="flex-1 text-[13px] text-white/90">{c.label}</span>
                <span className="text-[11px] text-white/40 font-mono">{c.icon}</span>
                <button onClick={() => removeConcern(i)} className="text-white/30 hover:text-rose-400 transition"><Icon.Close size={13}/></button>
              </div>
            ))}
            <div className="flex justify-between items-center">
              {cfgConcerns.length === 0 && <div className="text-[12px] text-white/35 py-2">No concerns yet — add one below or use AI Suggest.</div>}
              <div className="ml-auto">
                <WsBtn variant="ghost" size="sm" onClick={suggestConcerns} disabled={cfgSuggesting}><Icon.Sparkle size={13}/> {cfgSuggesting ? "Suggesting…" : "AI Suggest"}</WsBtn>
              </div>
            </div>

            <div className="mt-4 pt-4 border-t border-white/[0.06] space-y-3">
              <div className="text-[11px] uppercase tracking-wider text-white/40">Add new concern</div>
              <div className="flex gap-2">
                <WsInput value={cfgNewLabel} onChange={e => setCfgNewLabel(e.target.value)} placeholder="Label e.g. Deposit Issue" className="flex-1"/>
                <select value={cfgNewIcon} onChange={e => setCfgNewIcon(e.target.value)} className="h-10 px-2 rounded-xl bg-white/[0.03] border border-white/[0.07] text-[12px] text-white/80">
                  {CONCERN_ICONS.map(ic => <option key={ic} value={ic}>{ic}</option>)}
                </select>
                <div className="flex gap-1 items-center">
                  {CONCERN_COLORS.map(col => (
                    <button key={col} onClick={() => setCfgNewTint(col)} className={`w-6 h-6 rounded-full ${cfgNewTint === col ? "ring-2 ring-white ring-offset-1 ring-offset-ink-950" : ""}`} style={{ background: col }}/>
                  ))}
                </div>
                <WsBtn variant="primary" size="sm" onClick={addConcern} disabled={!cfgNewLabel.trim()}>Add</WsBtn>
              </div>
            </div>
          </div>
        )}

        {cfgTab === "prechat" && (
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-3">
              <div>
                <div className="text-[11px] uppercase tracking-wider text-white/40 mb-1.5">Widget header title</div>
                <WsInput value={cfgTitle} onChange={e => setCfgTitle(e.target.value)} placeholder={`${(showConfigure && showConfigure.name) || "Brand"} Support`} />
                <div className="text-[11px] text-white/35 mt-1">The bold line at the top of the widget. e.g. "JuanRepublic LiveChat". Blank = "{(showConfigure && showConfigure.name) || "Brand"} Support".</div>
              </div>
              <div>
                <div className="text-[11px] uppercase tracking-wider text-white/40 mb-1.5">Header tagline</div>
                <WsInput value={cfgTagline} onChange={e => setCfgTagline(e.target.value)} placeholder="Replies in < 1 min" />
                <div className="text-[11px] text-white/35 mt-1">The small line under the title (when online). Blank = "Replies in &lt; 1 min".</div>
              </div>
            </div>
            <div>
              <div className="text-[11px] uppercase tracking-wider text-white/40 mb-1.5">Welcome message</div>
              <textarea rows={3} value={cfgWelcome} onChange={e => setCfgWelcome(e.target.value)}
                className="w-full px-3 py-2.5 rounded-xl bg-white/[0.03] border border-white/[0.07] text-[12.5px] resize-none text-white/85 focus:border-lime/50 outline-none"
                placeholder="Welcome to Acme LiveChat! Please fill in the form below before starting the chat."/>
              <div className="text-[11px] text-white/35 mt-1">Shown at the top of the widget's pre-chat form. Leave blank for the default.</div>
            </div>
            <div>
              <div className="text-[11px] uppercase tracking-wider text-white/40 mb-2.5">Widget theme</div>
              <div className="flex gap-2">
                {["dark", "light"].map(t => (
                  <button key={t} onClick={() => setEditWidgetTheme(t)} className={`h-9 px-4 rounded-lg text-[13px] flex items-center gap-2 transition ${editWidgetTheme === t ? (t === "dark" ? "bg-white/[0.08] text-white" : "bg-white text-ink-950") : "text-white/55 hover:text-white/80"}`}>
                    {t === "dark" ? <Icon.Moon size={14}/> : <Icon.Sun size={14}/>} {t.charAt(0).toUpperCase() + t.slice(1)}
                  </button>
                ))}
              </div>
              <div className="text-[11px] text-white/35 mt-2">Choose how the widget appears to your visitors.</div>
            </div>
            {[
              { label: "Ask for phone number", hint: "Adds a required Phone number field", val: cfgPhone, set: setCfgPhone },
              { label: "Ask for username / user ID", hint: "Adds an optional Username field (Name becomes name-only)", val: cfgUsername, set: setCfgUsername },
            ].map((o) => (
              <div key={o.label} className="flex items-center justify-between px-3 py-2.5 rounded-xl bg-white/[0.03] border border-white/[0.06]">
                <div><div className="text-[13px] text-white/90">{o.label}</div><div className="text-[11px] text-white/40">{o.hint}</div></div>
                <button onClick={() => o.set(!o.val)} className={`h-6 w-11 rounded-full transition relative ${o.val ? "bg-lime" : "bg-white/[0.12]"}`}>
                  <span className={`absolute top-0.5 ${o.val ? "right-0.5" : "left-0.5"} w-5 h-5 rounded-full bg-white transition-all`} />
                </button>
              </div>
            ))}
            <div className="text-[11px] text-white/35">The Name field and inquiry categories (from the Concern Categories tab) are always shown.</div>
          </div>
        )}

        {cfgTab === "ai-knowledge" && (
          <div className="space-y-2">
            <div className="text-[12px] text-white/50">This text is injected into the AI system prompt. Describe your brand, services, pricing, FAQs, and policies.</div>
            <textarea rows={14} value={cfgKnowledge} onChange={e => setCfgKnowledge(e.target.value)}
              className="w-full px-3 py-2.5 rounded-xl bg-white/[0.03] border border-white/[0.07] text-[12.5px] font-mono resize-none text-white/85 focus:border-lime/50 outline-none"
              placeholder="Company: Vertex Gaming Solutions&#10;Services: Casino API, White Label Platform...&#10;Contact: support@vertex.com"/>
          </div>
        )}

        <div className="flex justify-end gap-2 pt-4 mt-2 border-t border-white/[0.05]">
          <WsBtn variant="quiet" onClick={() => setShowConfigure(null)}>Cancel</WsBtn>
          <WsBtn variant="primary" onClick={saveConfigure} disabled={cfgSaving}>{cfgSaving ? "Saving…" : "Save changes"}</WsBtn>
        </div>
      </WsModal>

      {/* Add website modal */}
      <WsModal open={showAdd} onClose={closeAdd} title="Add a new website" subtitle="Brand and route a new domain in 30 seconds." width={560}>
        <div className="space-y-4">
          <WsField label="Website name"><WsInput value={name} onChange={e => setName(e.target.value)} placeholder="e.g. NorthStar Sportsbook"/></WsField>
          <div className="grid grid-cols-2 gap-3">
            <WsField label="Primary domain"><WsInput value={domain} onChange={e => setDomain(e.target.value)} placeholder="northstar.bet"/></WsField>
            <WsField label="Default team">
              <select value={team} onChange={e => setTeam(e.target.value)} className="w-full h-10 px-3 rounded-xl bg-white/[0.03] border border-white/[0.07] text-[13px]">
                <option>Tier 1 · Manila</option>
                <option>Partners · Cebu</option>
                <option>Beta crew</option>
              </select>
            </WsField>
          </div>
          <WsField label="Widget color">
            <div className="flex items-center gap-3">
              <div className="flex gap-2">
                {["#A6F84A","#7AB6FF","#FF9DD2","#FFD37A","#C7B6FF","#FF6B6B"].map(c => (
                  <button key={c} onClick={() => setColor(c)} className={`w-9 h-9 rounded-xl ${color === c ? "ring-2 ring-white" : ""}`} style={{ background: c }}/>
                ))}
              </div>
              <input value={color} onChange={e => setColor(e.target.value)} className="flex-1 h-10 px-3 rounded-xl bg-white/[0.03] border border-white/[0.07] text-[13px] font-mono"/>
            </div>
          </WsField>
          <WsField label="Allowed domains" hint="One per line. Subdomains supported."><textarea rows={3} value={allowedText} onChange={e => setAllowedText(e.target.value)} className="w-full px-3 py-2.5 rounded-xl bg-white/[0.03] border border-white/[0.07] text-[12.5px] font-mono resize-none" placeholder={"northstar.bet\napp.northstar.bet"} /></WsField>
          {err && <div className="text-[12px] text-rose-300 bg-rose-500/10 border border-rose-500/20 rounded-lg px-3 py-2">{err}</div>}
          <div className="flex justify-end gap-2 pt-2">
            <WsBtn variant="quiet" onClick={closeAdd}>Cancel</WsBtn>
            <WsBtn variant="primary" onClick={createWebsite} disabled={saving}>{saving ? "Creating…" : "Create website"}</WsBtn>
          </div>
        </div>
      </WsModal>
    </div>
  );
}

function Stat({ label, value, tint }) {
  return (
    <div>
      <div className="text-[10.5px] uppercase tracking-wider text-white/40">{label}</div>
      <div className="text-[15px] font-semibold text-white/95 mt-0.5" style={tint ? { color: tint } : null}>{value}</div>
    </div>
  );
}

window.Websites = Websites;
