// screens-agent-edit.jsx — full edit screen for an AI agent.
// Tabs: Profile · Knowledge & links · Training (corrections the agent learns from).
const { useState: useStateAE } = React;

const EDIT_TABS = [
  { key: "profile", label: "Profile", icon: "bot" },
  { key: "knowledge", label: "Knowledge & links", icon: "fileText" },
  { key: "training", label: "Training", icon: "sparkles" },
];

const STYLE_OPTS = ["Consultative", "Technical", "Premium", "Educational", "Growth", "Friendly"];
const LANG_OPTS = [{ v: "ar", label: "Arabic" }, { v: "en", label: "English" }, { v: "ar_en", label: "Arabic + English" }];
const SERVICE_OPTS = [{ v: "shopify", label: "Shopify design & migration" }, { v: "web", label: "Website design" }, { v: "automation", label: "Automation & SEO" }, { v: "app_sub", label: "Maxab Hub app subscription" }, { v: "salla", label: "Salla store services" }, { v: "zid", label: "Zid store services" }];
const REPLY_MODE_OPTS = [{ v: "", label: "Inherit global setting" }, { v: "manual", label: "Manual approval" }, { v: "auto_safe", label: "Auto-safe" }, { v: "auto", label: "Full auto" }];
const AGENT_COLORS = ["#00654B", "#2563EB", "#7E22CE", "#EA580C", "#0891B2", "#BE185D", "#4A6400", "#B45309"];
const BLANK_AGENT = { id: null, name: "", role: "", specialty: "", style: "Consultative", lang: "ar_en", color: "#00654B", trust: 2, blurb: "", service: "shopify" };

function LinkRow({ link, onChange, onRemove }) {
  const meta = DATA.LINK_TYPES[link.type] || DATA.LINK_TYPES.other;
  return (
    <div className="row" style={{ gap: 10, padding: 12, background: "var(--bg-2)", borderRadius: 12, alignItems: "flex-start" }}>
      <span className="optcard__icon" style={{ width: 36, height: 36, background: "#fff", color: meta.c, flexShrink: 0 }}><Icon name={meta.icon} size={18} /></span>
      <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 8 }}>
        <div className="row" style={{ gap: 8 }}>
          <select className="select" value={link.type} onChange={(e) => onChange({ ...link, type: e.target.value })} style={{ background: "#fff", height: 38, width: 150, flexShrink: 0 }}>
            {Object.entries(DATA.LINK_TYPES).map(([k, m]) => <option key={k} value={k}>{m.label}</option>)}
          </select>
          <input className="input" style={{ height: 38 }} placeholder="Label (e.g. Shopify build)" value={link.label} onChange={(e) => onChange({ ...link, label: e.target.value })} />
        </div>
        <input className="input" style={{ height: 38, fontFamily: "monospace", fontSize: 12.5 }} placeholder="https://…" value={link.url} onChange={(e) => onChange({ ...link, url: e.target.value })} />
      </div>
      <button className="iconbtn" style={{ width: 36, height: 36, color: "var(--color-danger)" }} onClick={onRemove} title="Remove link"><Icon name="trash" size={16} /></button>
    </div>
  );
}

function AgentEditOverlay({ agent, onClose }) {
  const isNew = !agent;
  const a = agent || BLANK_AGENT;
  const base = isNew ? { knowledge: [], links: [], corrections: [] } : trainingFor(a.id);
  const [tab, setTab] = useStateAE("profile");
  const [name, setName] = useStateAE(a.nameEn || a.name);
  const [nameAr, setNameAr] = useStateAE(a.nameAr || "");
  const [role, setRole] = useStateAE(a.role);
  const [specialty, setSpecialty] = useStateAE(a.specialty);
  const [salesSkill, setSalesSkill] = useStateAE(a.salesSkill || "");
  const [style, setStyle] = useStateAE(a.style);
  const [lang, setLang] = useStateAE(a.lang);
  const [blurb, setBlurb] = useStateAE(a.blurb);
  const [trustCap, setTrustCap] = useStateAE(a.trust);
  const [color, setColor] = useStateAE(a.color);
  const [service, setService] = useStateAE(a.service || "shopify");
  const [targetAudience, setTargetAudience] = useStateAE(a.targetAudience || "");
  const [instructions, setInstructions] = useStateAE(a.instructions || "");
  const [allowedStr, setAllowedStr] = useStateAE((a.allowedPhrases || []).join(", "));
  const [forbiddenStr, setForbiddenStr] = useStateAE((a.forbiddenPhrases || []).join(", "));
  const [replyMode, setReplyMode] = useStateAE(a.replyMode || "");

  const [knowledge, setKnowledge] = useStateAE(base.knowledge);
  const [newKnow, setNewKnow] = useStateAE("");
  const [links, setLinks] = useStateAE(base.links);
  const [corrections, setCorrections] = useStateAE(base.corrections);
  const [adding, setAdding] = useStateAE(false);
  const [draftCorr, setDraftCorr] = useStateAE({ topic: "", before: "", after: "", note: "" });
  const [saved, setSaved] = useStateAE(false);

  const addKnowledge = () => { if (newKnow.trim()) { setKnowledge([...knowledge, newKnow.trim()]); setNewKnow(""); } };
  const addLink = () => setLinks([...links, { id: "lk" + Date.now(), type: "service", label: "", url: "" }]);
  const updateLink = (i, v) => setLinks(links.map((l, idx) => idx === i ? v : l));
  const removeLink = (i) => setLinks(links.filter((_, idx) => idx !== i));
  const saveCorr = () => {
    if (draftCorr.before.trim() && draftCorr.after.trim()) {
      setCorrections([{ id: "cr" + Date.now(), date: "Just now", ...draftCorr }, ...corrections]);
      setDraftCorr({ topic: "", before: "", after: "", note: "" }); setAdding(false);
    }
  };
  const [busy, setBusy] = useStateAE(false);
  const save = async () => {
    if (busy) return;
    setBusy(true);
    const training = { knowledge, links, corrections };
    const toList = (s) => String(s || "").split(",").map((x) => x.trim()).filter(Boolean);
    // Keep `name` = English name for back-compat; nameEn/nameAr drive bilingual output.
    const body = { name: name.trim(), nameEn: name.trim(), nameAr: nameAr.trim(), displayName: name.trim(), role, specialty, salesSkill: salesSkill.trim(), speakingStyle: style, style, lang, color, trust: trustCap, service, blurb,
      targetAudience: targetAudience.trim(), instructions: instructions.trim(), allowedPhrases: toList(allowedStr), forbiddenPhrases: toList(forbiddenStr), replyMode: replyMode || null, training };
    try {
      if (isNew) await Actions.createAgent(body);
      else await Actions.updateAgent(a.id, body);
      setSaved(true);
      setTimeout(onClose, 750);
    } catch (e) { console.error("save agent failed", e); setBusy(false); }
  };
  const removeAgent = async () => {
    if (busy || isNew) return;
    if (!window.confirm(`Delete ${name || "this agent"}? This can't be undone.`)) return;
    setBusy(true);
    try { await Actions.deleteAgent(a.id); onClose(); }
    catch (e) { console.error("delete agent failed", e); setBusy(false); }
  };

  return (
    <Scrim onClose={onClose}>
      <div className="modal" style={{ width: 920, maxWidth: "94vw", height: "88vh", maxHeight: 760, display: "flex", flexDirection: "column", padding: 0 }} onClick={(e) => e.stopPropagation()}>
        {/* header */}
        <div className="between" style={{ padding: "16px 24px", borderBottom: "1px solid var(--border-1)" }}>
          <div className="row" style={{ gap: 12 }}>
            <Avatar name={name || "New"} color={color} size="lg" />
            <div><div style={{ fontWeight: 800, fontSize: 16 }}>{isNew ? "New agent" : "Edit agent"}</div><div style={{ fontSize: 12, color: "var(--fg-4)" }}>{isNew ? "Build an AI specialist for your team" : `${name} · ${role}`}</div></div>
          </div>
          <button className="iconbtn" onClick={onClose}><Icon name="x" size={20} /></button>
        </div>

        {/* tabs */}
        <div className="row" style={{ gap: 4, padding: "0 24px", borderBottom: "1px solid var(--border-1)", background: "var(--bg-2)" }}>
          {EDIT_TABS.map((t) => (
            <button key={t.key} onClick={() => setTab(t.key)} className="row" style={{ gap: 8, padding: "14px 14px", fontSize: 14, fontWeight: 600,
              color: tab === t.key ? "var(--color-secondary)" : "var(--fg-3)", borderBottom: "2px solid " + (tab === t.key ? "var(--color-secondary)" : "transparent"), marginBottom: -1 }}>
              <Icon name={t.icon} size={16} />{t.label}
            </button>
          ))}
        </div>

        {/* body */}
        <div style={{ flex: 1, overflowY: "auto", padding: 28 }}>
          {tab === "profile" && (
            <div className="fade-up" style={{ maxWidth: 620 }}>
              <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                <Field label="English name" hint="Shown in the app + English messages."><input className="input" placeholder="e.g. Noura" value={name} onChange={(e) => setName(e.target.value)} /></Field>
                <Field label="Arabic name" hint="Used when the agent writes in Arabic."><input className="input" dir="rtl" placeholder="مثال: نورة" value={nameAr} onChange={(e) => setNameAr(e.target.value)} /></Field>
              </div>
              <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                <Field label="Role"><input className="input" placeholder="e.g. Sales Consultant" value={role} onChange={(e) => setRole(e.target.value)} /></Field>
                <Field label="Specialty"><input className="input" placeholder="What this agent is best at" value={specialty} onChange={(e) => setSpecialty(e.target.value)} /></Field>
              </div>
              <Field label="Service it sells" hint="Picks which Maxab Hub offer and knowledge the agent leads with.">
                <select className="select" value={service} onChange={(e) => setService(e.target.value)}>{SERVICE_OPTS.map((s) => <option key={s.v} value={s.v}>{s.label}</option>)}</select>
              </Field>
              <Field label="Target audience" hint="Who this agent sells to — shapes how it speaks (e.g. 'Shopify merchants in the GCC').">
                <input className="input" dir="auto" placeholder="e.g. Salla merchants who answer WhatsApp by hand" value={targetAudience} onChange={(e) => setTargetAudience(e.target.value)} />
              </Field>
              <Field label="Avatar color">
                <div className="row wrap" style={{ gap: 8 }}>
                  {AGENT_COLORS.map((c) => (
                    <button key={c} onClick={() => setColor(c)} title={c} style={{ width: 30, height: 30, borderRadius: 999, background: c, border: "2px solid " + (color === c ? "var(--fg-1)" : "transparent"), boxShadow: color === c ? "0 0 0 2px #fff inset" : "none", cursor: "pointer" }} />
                  ))}
                </div>
              </Field>
              <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                <Field label="Speaking style">
                  <select className="select" value={style} onChange={(e) => setStyle(e.target.value)}>{STYLE_OPTS.map((s) => <option key={s}>{s}</option>)}</select>
                </Field>
                <Field label="Language">
                  <select className="select" value={lang} onChange={(e) => setLang(e.target.value)}>{LANG_OPTS.map((l) => <option key={l.v} value={l.v}>{l.label}</option>)}</select>
                </Field>
              </div>
              <Field label="Sales skill" hint="How this agent sells — shapes generated drafts (discovery, objection handling, closing).">
                <textarea className="textarea" rows={2} dir="auto" placeholder="e.g. Consultative seller — qualifies before pitching, books calls." value={salesSkill} onChange={(e) => setSalesSkill(e.target.value)} />
              </Field>
              <Field label="Standing instructions" hint="Permanent rules this agent always follows — used in campaigns, replies, auto-replies, regenerate & follow-ups.">
                <textarea className="textarea" rows={3} dir="auto" placeholder="e.g. Sell the Maxab Hub app subscription. Never suggest a phone call — offer a Google Meet. Never invent pricing." value={instructions} onChange={(e) => setInstructions(e.target.value)} />
              </Field>
              <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                <Field label="Allowed phrases" hint="Comma-separated — lean toward these.">
                  <input className="input" dir="auto" placeholder="happy to help, no pressure" value={allowedStr} onChange={(e) => setAllowedStr(e.target.value)} />
                </Field>
                <Field label="Forbidden phrases" hint="Comma-separated — never use these.">
                  <input className="input" dir="auto" placeholder="phone call, act now, cheapest" value={forbiddenStr} onChange={(e) => setForbiddenStr(e.target.value)} />
                </Field>
              </div>
              <Field label="Reply mode" hint="Auto-send behavior for this agent (overrides the global Settings → Auto-reply default).">
                <select className="select" value={replyMode} onChange={(e) => setReplyMode(e.target.value)}>{REPLY_MODE_OPTS.map((m) => <option key={m.v} value={m.v}>{m.label}</option>)}</select>
              </Field>
              <Field label="Short description" hint="Shown on the agent card.">
                <textarea className="textarea" rows={3} value={blurb} onChange={(e) => setBlurb(e.target.value)} />
              </Field>
              <Field label="Maximum trust level" hint="Cap how much the agent can do on its own, no matter how well it performs.">
                <div className="col" style={{ gap: 8 }}>
                  <input type="range" min={1} max={5} value={trustCap} onChange={(e) => setTrustCap(+e.target.value)} style={{ accentColor: "var(--color-secondary)", width: 240 }} />
                  <Badge tone="lime">Level {trustCap} · {["Observe", "Drafts only", "Send with approval", "Auto-send (low risk)", "Director"][trustCap - 1]}</Badge>
                </div>
              </Field>
            </div>
          )}

          {tab === "knowledge" && (
            <div className="fade-up">
              {/* knowledge */}
              <h5 style={{ marginBottom: 4 }}>What the agent talks about</h5>
              <p className="muted" style={{ fontSize: 14, marginBottom: 16 }}>Facts, talking points and rules the agent should use in every conversation.</p>
              <div className="col" style={{ gap: 8, marginBottom: 12 }}>
                {knowledge.map((k, i) => (
                  <div key={i} className="row" style={{ gap: 10, padding: "12px 14px", background: "var(--bg-2)", borderRadius: 12, alignItems: "flex-start" }}>
                    <Icon name="check2" size={16} style={{ color: "var(--color-secondary)", marginTop: 2, flexShrink: 0 }} />
                    <input className="input" value={k} onChange={(e) => setKnowledge(knowledge.map((x, idx) => idx === i ? e.target.value : x))} style={{ border: "none", background: "transparent", height: "auto", padding: 0, flex: 1 }} dir="auto" />
                    <button className="iconbtn" style={{ width: 28, height: 28, color: "var(--fg-4)" }} onClick={() => setKnowledge(knowledge.filter((_, idx) => idx !== i))}><Icon name="x" size={15} /></button>
                  </div>
                ))}
              </div>
              <div className="row" style={{ gap: 8, marginBottom: 28 }}>
                <input className="input" placeholder="Add a fact or talking point…" value={newKnow} dir="auto"
                  onChange={(e) => setNewKnow(e.target.value)} onKeyDown={(e) => e.key === "Enter" && addKnowledge()} />
                <Button variant="dark" icon="plus" onClick={addKnowledge}>Add</Button>
              </div>

              {/* links */}
              <h5 style={{ marginBottom: 4 }}>Links the agent can send</h5>
              <p className="muted" style={{ fontSize: 14, marginBottom: 16 }}>Service pages, payment links, affiliate links — the agent only shares from this list.</p>
              <div className="col" style={{ gap: 10, marginBottom: 12 }}>
                {links.map((l, i) => <LinkRow key={l.id} link={l} onChange={(v) => updateLink(i, v)} onRemove={() => removeLink(i)} />)}
              </div>
              <Button variant="ghost" icon="plus" onClick={addLink}>Add a link</Button>
            </div>
          )}

          {tab === "training" && (
            <div className="fade-up">
              <h5 style={{ marginBottom: 4 }}>Teach the agent from past replies</h5>
              <p className="muted" style={{ fontSize: 14, marginBottom: 16 }}>Fix a reply the agent got wrong. It learns the correction and applies it next time.</p>

              {!adding && <Button variant="dark" icon="plus" onClick={() => setAdding(true)} style={{ marginBottom: 16 }}>Add a correction</Button>}

              {adding && (
                <Card style={{ marginBottom: 16, border: "1.5px solid var(--color-secondary)" }}>
                  <Field label="What was this about?"><input className="input" placeholder="e.g. Pricing question" value={draftCorr.topic} onChange={(e) => setDraftCorr({ ...draftCorr, topic: e.target.value })} /></Field>
                  <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                    <Field label="What it said (wrong)"><textarea className="textarea" rows={3} dir="auto" value={draftCorr.before} onChange={(e) => setDraftCorr({ ...draftCorr, before: e.target.value })} /></Field>
                    <Field label="What it should say"><textarea className="textarea" rows={3} dir="auto" value={draftCorr.after} onChange={(e) => setDraftCorr({ ...draftCorr, after: e.target.value })} /></Field>
                  </div>
                  <Field label="Rule to remember" hint="Optional — a short instruction for the future."><input className="input" dir="auto" value={draftCorr.note} onChange={(e) => setDraftCorr({ ...draftCorr, note: e.target.value })} /></Field>
                  <div className="row" style={{ gap: 8, justifyContent: "flex-end" }}>
                    <Button variant="ghost" size="sm" onClick={() => setAdding(false)}>Cancel</Button>
                    <Button variant="primary" size="sm" icon="sparkles" onClick={saveCorr}>Teach agent</Button>
                  </div>
                </Card>
              )}

              <div className="col" style={{ gap: 12 }}>
                {corrections.length === 0 && !adding && <EmptyState icon="sparkles" title="No corrections yet" body="When the agent makes a mistake, fix it here so it improves over time." />}
                {corrections.map((c) => (
                  <Card key={c.id}>
                    <div className="between" style={{ marginBottom: 12 }}>
                      <div className="row" style={{ gap: 8 }}><Badge tone="lime"><Icon name="sparkles" size={12} />Learned</Badge>{c.topic && <b style={{ fontSize: 13 }}>{c.topic}</b>}</div>
                      <span style={{ fontSize: 11, color: "var(--fg-4)" }}>{c.date}</span>
                    </div>
                    <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                      <div style={{ background: "var(--color-danger-soft)", borderRadius: 10, padding: 12 }}>
                        <div className="row" style={{ gap: 5, marginBottom: 5, color: "var(--color-danger)", fontSize: 11, fontWeight: 700 }}><Icon name="x" size={12} />Before</div>
                        <p dir="auto" style={{ fontSize: 13, lineHeight: 1.5, color: "var(--fg-2)" }}>{c.before}</p>
                      </div>
                      <div style={{ background: "var(--color-success-soft)", borderRadius: 10, padding: 12 }}>
                        <div className="row" style={{ gap: 5, marginBottom: 5, color: "#15803D", fontSize: 11, fontWeight: 700 }}><Icon name="check" size={12} />After</div>
                        <p dir="auto" style={{ fontSize: 13, lineHeight: 1.5, color: "var(--fg-2)" }}>{c.after}</p>
                      </div>
                    </div>
                    {c.note && <div className="row" style={{ gap: 6, marginTop: 10, fontSize: 12.5, color: "var(--fg-3)" }}><Icon name="pin" size={13} style={{ flexShrink: 0, marginTop: 1 }} /><span dir="auto">{c.note}</span></div>}
                  </Card>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* footer */}
        <div className="between" style={{ padding: "16px 24px", borderTop: "1px solid var(--border-1)" }}>
          <div className="row" style={{ gap: 12 }}>
            {!isNew && <button className="btn btn--subtle btn--sm" style={{ color: "var(--color-danger)" }} onClick={removeAgent} disabled={busy}><Icon name="trash" size={14} />Delete</button>}
            <span className="subtle" style={{ fontSize: 12 }}>{knowledge.length} facts · {links.length} links · {corrections.length} corrections</span>
          </div>
          <div className="row" style={{ gap: 10 }}>
            {saved && <span className="row" style={{ gap: 6, color: "var(--color-success)", fontWeight: 600, fontSize: 13 }}><Icon name="checkcircle" size={16} />{isNew ? "Created" : "Saved"}</span>}
            <Button variant="ghost" onClick={onClose}>Cancel</Button>
            <Button variant="primary" icon={isNew ? "plus" : "check"} onClick={save} disabled={busy || (isNew && !name.trim())}>{busy && !saved ? "Saving…" : isNew ? "Create agent" : "Save changes"}</Button>
          </div>
        </div>
      </div>
    </Scrim>
  );
}

window.AgentEditOverlay = AgentEditOverlay;
