// Settings page
const { Card: StCard, Pill: StPill, Btn: StBtn, Topbar: StTopbar, Field: StField, Input: StInput, Textarea: StArea, ConcernIcon: StCon, Modal: StModal } = window.UI;

function Settings() {
  const [section, setSection] = React.useState("brand");

  // Brand fields — loaded from backend on mount
  const [workspaceName, setWorkspaceName] = React.useState("Loop · Live chat OS");
  const [displayName, setDisplayName] = React.useState("Support Team");
  const [welcome, setWelcome] = React.useState("Hello there! 👋\nHow can we help you today?");
  const [color, setColor] = React.useState("#A6F84A");
  // Logo stored in localStorage — keeps it out of the DB request entirely
  const [logo, setLogo] = React.useState(() => {
    try { return localStorage.getItem("loop_brand_logo") || null; } catch { return null; }
  });
  const [saveBusy, setSaveBusy] = React.useState(false);
  const [saveOk, setSaveOk] = React.useState(false);
  const logoRef = React.useRef(null);

  // Routing (local toggles only — no routing backend)
  const [routing, setRouting] = React.useState({ roundRobin: true, skill: true, overflow: false, language: true });

  // Domains (local state — not persisted yet)
  const [domains, setDomains] = React.useState("winforlife88.com\nplay.winforlife88.com\npromo.winforlife88.com");

  // Theme preview
  const [theme, setTheme] = React.useState("dark");

  // Concerns
  const [concerns, setConcerns] = React.useState(window.Mock.concerns || []);
  const [showAddConcern, setShowAddConcern] = React.useState(false);
  const [concernForm, setConcernForm] = React.useState({ label: "", icon: "Tag", tint: "#A6F84A" });
  const [concernBusy, setConcernBusy] = React.useState(false);

  // Load settings from backend on mount
  React.useEffect(() => {
    window.LoopData.getSettings().then(s => {
      if (!s) return;
      if (s.brand) setWorkspaceName(s.brand);
      if (s.displayName) setDisplayName(s.displayName);
      if (s.welcome) setWelcome(s.welcome);
      if (s.color) setColor(s.color);
      // logo lives in localStorage — don't load from backend
    });
    setConcerns(window.Mock.concerns || []);
  }, []);

  const saveLogo = (dataUrl) => {
    setLogo(dataUrl);
    try {
      if (dataUrl) localStorage.setItem("loop_brand_logo", dataUrl);
      else localStorage.removeItem("loop_brand_logo");
    } catch (e) { console.warn("Could not save logo:", e); }
  };

  const handleLogoPick = (e) => {
    const f = (e.target && e.target.files && e.target.files[0]) || (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0]);
    if (!f) return;
    if (f.type && !f.type.startsWith("image/")) { alert("Please pick an image file (PNG, JPG, SVG, WebP)"); return; }
    if (f.size > 15 * 1024 * 1024) { alert("File too large — max 15 MB"); return; }
    const reader = new FileReader();
    reader.onerror = () => alert("Could not read file. Please try another.");
    reader.onload = (ev) => {
      try {
        const img = new Image();
        img.onerror = () => alert("Could not load image. Please try a different file.");
        img.onload = () => {
          try {
            const MAX = 160;
            const scale = Math.min(1, MAX / Math.max(img.width || 1, img.height || 1));
            const w = Math.max(1, Math.round(img.width * scale));
            const h = Math.max(1, Math.round(img.height * scale));
            const canvas = document.createElement("canvas");
            canvas.width = w; canvas.height = h;
            const ctx = canvas.getContext("2d");
            if (!ctx) throw new Error("Canvas context unavailable");
            ctx.fillStyle = "#ffffff";
            ctx.fillRect(0, 0, w, h);
            ctx.drawImage(img, 0, 0, w, h);
            saveLogo(canvas.toDataURL("image/jpeg", 0.80));
          } catch (err) { console.error("Canvas error:", err); alert("Could not process image. Please try a PNG or JPG."); }
        };
        img.src = ev.target.result;
      } catch (err) { console.error("Image load error:", err); }
    };
    reader.readAsDataURL(f);
    if (logoRef && logoRef.current) logoRef.current.value = "";
  };

  const handleSave = async () => {
    setSaveBusy(true);
    try {
      await window.LoopData.saveSettings({ brand: workspaceName, displayName, welcome, color }); // logo is in localStorage
      setSaveOk(true);
      setTimeout(() => setSaveOk(false), 2000);
    } finally { setSaveBusy(false); }
  };

  const reloadConcerns = async () => {
    await window.LoopData.bootstrap();
    setConcerns(window.Mock.concerns || []);
  };

  const handleDeleteConcern = async (id) => {
    if (!window.confirm("Remove this concern type?")) return;
    setConcernBusy(true);
    try {
      await window.LoopData.adminDelete("concerns", id);
      await reloadConcerns();
    } finally { setConcernBusy(false); }
  };

  const handleAddConcern = async () => {
    if (!concernForm.label) return;
    setConcernBusy(true);
    try {
      await window.LoopData.adminCreate("concerns", concernForm);
      await reloadConcerns();
      setShowAddConcern(false);
      setConcernForm({ label: "", icon: "Tag", tint: "#A6F84A" });
    } finally { setConcernBusy(false); }
  };

  const CONCERN_ICONS = ["Tag", "Wallet", "User", "Shield", "Gamepad", "Mail", "Phone", "Star", "AlertCircle"];
  const CONCERN_TINTS = ["#A6F84A", "#7AB6FF", "#FF9DD2", "#FFD37A", "#C7B6FF", "#FF6B6B", "#5EE9D6", "#FFA07A"];

  const sections = [
    { id: "brand", label: "Brand & widget", icon: "Sparkle" },
    { id: "concerns", label: "Concerns dropdown", icon: "Tag" },
    { id: "routing", label: "Routing rules", icon: "Layers" },
    { id: "domains", label: "Domain restrictions", icon: "Shield" },
    { id: "theme", label: "Theme preview", icon: "Sun" },
  ];

  return (
    <div className="flex-1 flex flex-col h-full overflow-hidden">
      <StTopbar
        title="Settings"
        subtitle="Configure how Loop looks, routes, and behaves across your sites"
        right={
          <StBtn variant="primary" onClick={handleSave} disabled={saveBusy}>
            {saveOk ? <><Icon.Check size={14}/> Saved!</> : saveBusy ? "Saving…" : <><Icon.Check size={14}/> Save changes</>}
          </StBtn>
        }
      />
      <div className="flex-1 grid grid-cols-[260px_1fr] min-h-0">
        <aside className="border-r border-white/[0.05] p-3 bg-ink-950/30">
          {sections.map(s => {
            const I = Icon[s.icon];
            const isActive = section === s.id;
            return (
              <button key={s.id} onClick={() => setSection(s.id)} className={`w-full flex items-center gap-3 px-3 h-10 rounded-xl text-[13px] mb-1 ${isActive ? "bg-white/[0.06] text-white" : "text-white/65 hover:text-white hover:bg-white/[0.03]"}`}>
                <I size={15} className={isActive ? "text-lime" : ""}/>
                <span className="font-medium">{s.label}</span>
              </button>
            );
          })}
        </aside>

        <main className="overflow-y-auto p-7 max-w-[860px]">

          {/* ---- Brand & widget ---- */}
          {section === "brand" && (
            <div className="space-y-5">
              <StCard>
                <SectionHead title="Brand identity" sub="The face your visitors see in every widget."/>
                <div className="grid grid-cols-[160px_1fr] gap-6 mt-5 items-start">
                  <div>
                    <div className="text-[10.5px] uppercase tracking-wider text-white/40 mb-2">Logo</div>
                    <input ref={logoRef} type="file" accept="image/*" style={{ display: "none" }} onChange={handleLogoPick}/>
                    <div
                      onClick={() => logoRef.current && logoRef.current.click()}
                      onDragOver={e => e.preventDefault()}
                      onDrop={e => { e.preventDefault(); handleLogoPick(e); }}
                      className="aspect-square rounded-2xl border border-dashed border-white/[0.12] grid place-items-center bg-white/[0.02] hover:bg-white/[0.06] cursor-pointer transition overflow-hidden relative group"
                    >
                      {logo ? (
                        <>
                          <img src={logo} alt="Logo" className="w-full h-full object-contain p-2"/>
                          <button
                            onClick={e => { e.stopPropagation(); saveLogo(null); }}
                            className="absolute top-1.5 right-1.5 w-6 h-6 rounded-full bg-rose-500/80 text-white text-[11px] grid place-items-center opacity-0 group-hover:opacity-100 transition"
                          >✕</button>
                        </>
                      ) : (
                        <div className="text-center px-2">
                          <Icon.Image size={22} className="text-white/40 mx-auto mb-1.5"/>
                          <div className="text-[11px] text-white/55">Drop or browse</div>
                          <div className="text-[10px] text-white/35">PNG · JPG · WebP · max 15MB</div>
                        </div>
                      )}
                    </div>
                  </div>
                  <div className="space-y-4">
                    <StField label="Workspace name">
                      <StInput value={workspaceName} onChange={e => setWorkspaceName(e.target.value)}/>
                    </StField>
                    <StField label="Display name (in widget header)">
                      <StInput value={displayName} onChange={e => setDisplayName(e.target.value)}/>
                    </StField>
                    <StField label="Welcome message">
                      <StArea rows={3} value={welcome} onChange={e => setWelcome(e.target.value)}/>
                    </StField>
                  </div>
                </div>
              </StCard>

              <StCard>
                <SectionHead title="Widget color" sub="Used for primary buttons, accents, and the launcher bubble."/>
                <div className="flex items-center gap-3 mt-5">
                  <div className="flex gap-2">
                    {["#A6F84A","#7AB6FF","#FF9DD2","#FFD37A","#C7B6FF","#FF6B6B","#5EE9D6"].map(c => (
                      <button key={c} onClick={() => setColor(c)} className={`relative w-10 h-10 rounded-xl transition ${color === c ? "ring-2 ring-white scale-105" : "hover:scale-105"}`} style={{ background: c }}>
                        {color === c && <Icon.Check size={14} className="text-ink-950 absolute inset-0 m-auto"/>}
                      </button>
                    ))}
                  </div>
                  <div className="ml-2 flex items-center gap-2 h-10 px-3 rounded-xl bg-white/[0.03] border border-white/[0.07]">
                    <span className="w-4 h-4 rounded-md" style={{ background: color }}/>
                    <input value={color} onChange={e => setColor(e.target.value)} className="bg-transparent outline-none w-20 text-[12.5px] font-mono text-white/90"/>
                  </div>
                </div>
                <div className="mt-6 grid grid-cols-2 gap-4">
                  <div className="rounded-2xl bg-ink-900 border border-white/[0.05] p-4">
                    <div className="text-[10.5px] uppercase tracking-wider text-white/40 mb-3">Live preview</div>
                    <div className="rounded-xl overflow-hidden border border-white/[0.06]">
                      <div className="p-3 flex items-center gap-2.5" style={{ background: `linear-gradient(135deg, ${color}33, transparent)` }}>
                        {logo ? (
                          <img src={logo} alt="Logo" className="w-8 h-8 rounded-lg object-contain" style={{ background: color }}/>
                        ) : (
                          <div className="w-8 h-8 rounded-lg grid place-items-center font-bold text-ink-950 text-[10px]" style={{ background: color }}>WFL</div>
                        )}
                        <div>
                          <div className="text-[12px] text-white/95 font-medium leading-tight">{displayName}</div>
                          <div className="text-[10px] text-white/55 flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-lime"/>Replies in &lt; 1 min</div>
                        </div>
                      </div>
                      <div className="p-3 space-y-2 bg-white/[0.02]">
                        <div className="text-[11px] text-white/85 whitespace-pre-line">{welcome}</div>
                        <button className="w-full mt-1 h-9 rounded-lg text-[12px] font-semibold text-ink-950" style={{ background: color }}>Start a conversation</button>
                      </div>
                    </div>
                  </div>
                  <div className="rounded-2xl bg-white/[0.02] border border-white/[0.06] p-4">
                    <div className="text-[10.5px] uppercase tracking-wider text-white/40 mb-3">Bubble</div>
                    <div className="grid place-items-center h-32">
                      <button className="relative grid place-items-center w-14 h-14 rounded-full" style={{ background: color, boxShadow: `0 12px 36px -8px ${color}aa` }}>
                        <Icon.Chat size={22} className="text-ink-950"/>
                        <span className="absolute top-1 right-1 w-2 h-2 rounded-full bg-lime ring-2 ring-ink-950"/>
                      </button>
                    </div>
                  </div>
                </div>
              </StCard>
            </div>
          )}

          {/* ---- Concerns dropdown ---- */}
          {section === "concerns" && (
            <StCard>
              <SectionHead title="Pre-chat concern dropdown" sub="What visitors choose from when starting a chat."/>
              <div className="space-y-2 mt-5">
                {concerns.map((c) => {
                  const I = Icon[c.icon] || Icon.Tag;
                  return (
                    <div key={c.id} className="flex items-center gap-3 p-3 rounded-xl bg-white/[0.02] border border-white/[0.06] hover:bg-white/[0.04] group">
                      <span className="grid place-items-center w-9 h-9 rounded-lg shrink-0" style={{ background: `${c.tint}22`, color: c.tint }}>
                        <I size={14}/>
                      </span>
                      <div className="flex-1">
                        <div className="text-[13px] text-white/90 font-medium">{c.label}</div>
                        <div className="text-[11px] text-white/45 font-mono">{c.id}</div>
                      </div>
                      <span className="w-3 h-3 rounded-full shrink-0" style={{ background: c.tint }}/>
                      <button
                        onClick={() => handleDeleteConcern(c.id)}
                        disabled={concernBusy}
                        className="opacity-0 group-hover:opacity-100 text-white/45 hover:text-rose-300 transition disabled:opacity-40">
                        <Icon.Trash size={14}/>
                      </button>
                    </div>
                  );
                })}
              </div>
              <button
                onClick={() => setShowAddConcern(true)}
                className="mt-3 w-full text-[12.5px] text-white/55 hover:text-white border border-dashed border-white/15 hover:border-white/30 rounded-xl py-3 flex items-center justify-center gap-1.5 transition">
                <Icon.Plus size={14}/> Add concern type
              </button>
            </StCard>
          )}

          {/* ---- Routing rules ---- */}
          {section === "routing" && (
            <StCard>
              <SectionHead title="Routing rules" sub="How incoming conversations get assigned."/>
              <div className="space-y-3 mt-5">
                {[
                  { id: "roundRobin", t: "Round-robin among available agents", b: "Distribute conversations evenly across online CSRs." },
                  { id: "skill", t: "Skill-based routing by concern", b: "KYC → KYC desk, Cash-out → Tier 1 Manila, etc." },
                  { id: "language", t: "Auto-detect visitor language", b: "Route Tagalog visitors to bilingual agents first." },
                  { id: "overflow", t: "Overflow to email after hours", b: "When no agent is online, queue up an email reply." },
                ].map(r => (
                  <div key={r.id} className="flex items-start gap-3 p-4 rounded-xl bg-white/[0.02] border border-white/[0.06]">
                    <button onClick={() => setRouting(s => ({ ...s, [r.id]: !s[r.id] }))} className={`relative shrink-0 w-10 h-6 rounded-full transition ${routing[r.id] ? "bg-lime" : "bg-white/[0.1]"}`}>
                      <span className={`absolute top-0.5 w-5 h-5 rounded-full bg-white transition-all ${routing[r.id] ? "left-[18px]" : "left-0.5"}`}/>
                    </button>
                    <div className="flex-1">
                      <div className="text-[13px] font-medium text-white/95">{r.t}</div>
                      <div className="text-[11.5px] text-white/55 mt-0.5">{r.b}</div>
                    </div>
                  </div>
                ))}
              </div>
            </StCard>
          )}

          {/* ---- Domain restrictions ---- */}
          {section === "domains" && (
            <StCard>
              <SectionHead title="Domain restrictions" sub="Only widgets loaded on these domains will work. CORS-safe."/>
              <div className="mt-5 grid grid-cols-2 gap-4">
                <StField label="Allowed domains" hint="One per line · subdomains supported with wildcards (*.example.com)">
                  <StArea rows={6} value={domains} onChange={e => setDomains(e.target.value)} className="font-mono text-[12px]"/>
                </StField>
                <div>
                  <div className="text-[10.5px] uppercase tracking-wider text-white/40 mb-1.5">Detected</div>
                  <div className="space-y-1.5">
                    {domains.split("\n").filter(Boolean).map((d, i) => (
                      <div key={i} className="flex items-center justify-between p-2.5 rounded-lg bg-white/[0.02] border border-white/[0.06]">
                        <span className="text-[12px] font-mono text-white/85">{d}</span>
                        <span className="text-[10.5px] text-lime flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-lime"/>Verified</span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </StCard>
          )}

          {/* ---- Theme preview ---- */}
          {section === "theme" && (
            <StCard>
              <SectionHead title="Theme preview" sub="Switch between dark and light to see how the widget renders."/>
              <div className="mt-5 inline-flex p-1 rounded-xl bg-white/[0.04] border border-white/[0.06]">
                <button onClick={() => setTheme("dark")} className={`h-9 px-4 rounded-lg text-[13px] flex items-center gap-2 ${theme === "dark" ? "bg-white/[0.08] text-white" : "text-white/55"}`}><Icon.Moon size={14}/> Dark</button>
                <button onClick={() => setTheme("light")} className={`h-9 px-4 rounded-lg text-[13px] flex items-center gap-2 ${theme === "light" ? "bg-white text-ink-950" : "text-white/55"}`}><Icon.Sun size={14}/> Light</button>
              </div>
              <div className="grid grid-cols-2 gap-4 mt-6">
                <ThemePreview mode="dark" active={theme === "dark"}/>
                <ThemePreview mode="light" active={theme === "light"}/>
              </div>
            </StCard>
          )}
        </main>
      </div>

      {/* Add concern modal */}
      {StModal && (
        <StModal open={showAddConcern} onClose={() => setShowAddConcern(false)} title="Add concern type" width={420}>
          <div className="space-y-4">
            <StField label="Label">
              <StInput value={concernForm.label} onChange={e => setConcernForm(f => ({ ...f, label: e.target.value }))} placeholder="e.g. Bonus inquiry"/>
            </StField>
            <StField label="Icon">
              <div className="flex flex-wrap gap-2">
                {CONCERN_ICONS.map(ic => {
                  const Ic = Icon[ic];
                  if (!Ic) return null;
                  return (
                    <button key={ic} onClick={() => setConcernForm(f => ({ ...f, icon: ic }))}
                      className={`w-9 h-9 rounded-lg grid place-items-center border transition ${concernForm.icon === ic ? "border-lime/50 bg-lime/10 text-lime" : "border-white/[0.08] text-white/55 hover:text-white"}`}>
                      <Ic size={14}/>
                    </button>
                  );
                })}
              </div>
            </StField>
            <StField label="Color">
              <div className="flex gap-2">
                {CONCERN_TINTS.map(t => (
                  <button key={t} onClick={() => setConcernForm(f => ({ ...f, tint: t }))}
                    className={`w-8 h-8 rounded-lg transition ${concernForm.tint === t ? "ring-2 ring-white scale-105" : "hover:scale-105"}`}
                    style={{ background: t }}>
                    {concernForm.tint === t && <Icon.Check size={12} className="text-ink-950 mx-auto"/>}
                  </button>
                ))}
              </div>
            </StField>
            {/* Preview */}
            <div className="flex items-center gap-3 p-3 rounded-xl bg-white/[0.03] border border-white/[0.06]">
              {(() => { const Ic = Icon[concernForm.icon] || Icon.Tag; return <span className="grid place-items-center w-9 h-9 rounded-lg shrink-0" style={{ background: `${concernForm.tint}22`, color: concernForm.tint }}><Ic size={14}/></span>; })()}
              <span className="text-[13px] text-white/90">{concernForm.label || "Concern label"}</span>
            </div>
            <div className="flex justify-end gap-2 pt-1">
              <StBtn variant="quiet" onClick={() => setShowAddConcern(false)}>Cancel</StBtn>
              <StBtn variant="primary" onClick={handleAddConcern} disabled={concernBusy || !concernForm.label}>
                {concernBusy ? "Adding…" : "Add concern"}
              </StBtn>
            </div>
          </div>
        </StModal>
      )}
    </div>
  );
}

function SectionHead({ title, sub }) {
  return (
    <div className="pb-4 border-b border-white/[0.05]">
      <h3 className="text-[15px] font-medium text-white/95">{title}</h3>
      <p className="text-[12.5px] text-white/50 mt-1">{sub}</p>
    </div>
  );
}

function ThemePreview({ mode, active }) {
  const dark = mode === "dark";
  return (
    <div className={`rounded-2xl p-4 border transition ${active ? "border-lime/40 ring-1 ring-lime/20" : "border-white/[0.06]"} ${dark ? "bg-ink-950" : "bg-zinc-100"}`}>
      <div className={`rounded-xl overflow-hidden border ${dark ? "border-white/[0.06]" : "border-zinc-300"}`}>
        <div className={`p-3 flex items-center gap-2.5 ${dark ? "bg-lime/10" : "bg-lime/30"}`}>
          <div className="w-8 h-8 rounded-lg grid place-items-center font-bold text-ink-950 bg-lime text-[10px]">WFL</div>
          <div>
            <div className={`text-[12px] font-medium leading-tight ${dark ? "text-white/95" : "text-ink-950"}`}>WINFORLIFE88</div>
            <div className={`text-[10px] flex items-center gap-1 ${dark ? "text-white/55" : "text-zinc-600"}`}><span className="w-1.5 h-1.5 rounded-full bg-lime"/>Replies in &lt; 1 min</div>
          </div>
        </div>
        <div className={`p-3 space-y-2 ${dark ? "bg-white/[0.02]" : "bg-white"}`}>
          <div className={`max-w-[80%] px-3 py-1.5 rounded-xl rounded-bl-sm text-[11px] ${dark ? "bg-white/[0.06] text-white/85" : "bg-zinc-100 text-zinc-800"}`}>Hi! How can we help?</div>
          <div className="ml-auto max-w-[80%] px-3 py-1.5 rounded-xl rounded-br-sm text-[11px] bg-lime text-ink-950 font-medium">Withdrawal status</div>
        </div>
      </div>
      <div className={`text-[11px] mt-3 text-center ${dark ? "text-white/55" : "text-zinc-700"} font-medium uppercase tracking-wider`}>{mode}</div>
    </div>
  );
}

window.Settings = Settings;
