// Teklens.AI — Settings ▸ Artefact types.
// Defines what an artefact is: name, stage, hierarchy links, source & target binding,
// the forge/skill that creates it, and its output (a markdown template or a widget).
// Reuses globals from dashboard.jsx (DASH_PHASES, dashPhaseIndex, Icon, StagePip).

const ART_SYS = {
  jira:       { label: "Jira",            icon: "jira",       color: "#2563eb" },
  confluence: { label: "Confluence",      icon: "confluence", color: "#1c4f9c" },
  git:        { label: "Code repository", icon: "repo",       color: "#0e0e10" },
  teklens:    { label: "Teklens native",  icon: "sparkles",   color: "#8b5cf6" },
};
const ART_OUTPUT = {
  markdown: { label: "Markdown", icon: "file" },
  html:     { label: "HTML",     icon: "code" },
  widget:   { label: "Widget",   icon: "grid" },
};
const ART_FORGES = ["PRD Forge", "Decision Forge", "Spec Forge", "Brief Forge", "Release Forge"];
const ART_SKILLS = ["Story Drafter", "Story Splitter", "Feedback Synthesizer", "Sprint Pulse", "Release Notes Writer", "Acceptance Criteria Coach"];
const ART_WIDGETS = ["Feedback Summary", "Sprint Pulse", "Risk Analysis", "Component Analysis", "Story Estimation"];

const ART_TYPES_INIT = [
  { id: "prd", name: "PRD", predefined: true, icon: "file", stage: "define",
    desc: "Product Requirements Document — the top of the artefact hierarchy for an initiative.",
    parents: [], children: ["epic", "story"], siblings: ["adr"],
    source: { system: "confluence", loc: "Space · ENG" }, target: { system: "confluence", loc: "Space · ENG / Specs" },
    creator: { kind: "forge", name: "PRD Forge" }, output: "markdown",
    template: "# {Title}\n\n## Problem\n\n## Goals & non-goals\n\n## Requirements\n\n## Success metrics\n\n## Open questions" },
  { id: "epic", name: "Epic", predefined: true, icon: "hierarchy", stage: "define",
    desc: "A large body of work under a PRD that groups related stories.",
    parents: ["prd"], children: ["story"], siblings: [],
    source: { system: "jira", loc: "Project · TEK" }, target: { system: "jira", loc: "Project · TEK" },
    creator: { kind: "skill", name: "Story Splitter" }, output: "markdown",
    template: "## {Epic title}\n\n**Outcome**\n\n**Stories**\n- …\n\n**Exit gate**" },
  { id: "story", name: "Story", predefined: true, icon: "story", stage: "build",
    desc: "The smallest user-observable unit of value under an epic.",
    parents: ["epic", "prd"], children: [], siblings: [],
    source: { system: "jira", loc: "Project · TEK" }, target: { system: "jira", loc: "Project · TEK" },
    creator: { kind: "skill", name: "Story Drafter" }, output: "markdown",
    template: "**As a** {persona}\n**I want** {capability}\n**so that** {value}\n\n### Acceptance criteria\n- [ ] …\n\n### Notes" },
  { id: "adr", name: "ADR", predefined: true, icon: "shield", stage: "define",
    desc: "Architecture Decision Record — captures a decision, its rationale and trade-offs.",
    parents: ["prd"], children: [], siblings: ["prd"],
    source: { system: "git", loc: "/docs/adr" }, target: { system: "git", loc: "/docs/adr" },
    creator: { kind: "forge", name: "Decision Forge" }, output: "markdown",
    template: "# ADR-{n}: {title}\n\n## Status\nProposed\n\n## Context\n\n## Decision\n\n## Consequences" },
  { id: "feedback", name: "Feedback Summary", predefined: false, icon: "search", stage: "discover",
    desc: "A Discover-phase synthesis of user feedback and support signal.",
    parents: [], children: [], siblings: [],
    source: { system: "teklens", loc: "Productboard + Support" }, target: { system: "teklens", loc: "Initiative · Desktop" },
    creator: { kind: "skill", name: "Feedback Synthesizer" }, output: "widget", widget: "Feedback Summary" },
  { id: "sprintreport", name: "Sprint report", predefined: false, icon: "calendar", stage: "build",
    desc: "A Build-phase execution snapshot, usually produced by a schedule.",
    parents: [], children: [], siblings: [],
    source: { system: "jira", loc: "Project · TEK" }, target: { system: "confluence", loc: "Space · ENG / Reports" },
    creator: { kind: "skill", name: "Sprint Pulse" }, output: "widget", widget: "Sprint Pulse" },
  { id: "releasenotes", name: "Release notes", predefined: false, icon: "file", stage: "operate",
    desc: "An Operate-phase customer-facing summary of a release.",
    parents: [], children: [], siblings: [],
    source: { system: "jira", loc: "Project · TEK" }, target: { system: "confluence", loc: "Space · GTM" },
    creator: { kind: "skill", name: "Release Notes Writer" }, output: "markdown",
    template: "# {Release} — what's new\n\n## Highlights\n\n## Improvements\n\n## Fixes" },
];

// ============================================================
function ArtefactSettings() {
  const [types, setTypes] = useState(ART_TYPES_INIT);
  const [selId, setSelId] = useState("story");
  const sel = types.find((t) => t.id === selId) || types[0];
  const nameOf = (id) => (types.find((t) => t.id === id) || {}).name || id;

  const update = (patch) => setTypes((ts) => ts.map((t) => (t.id === sel.id ? { ...t, ...patch } : t)));
  const addType = () => {
    const id = "custom-" + Date.now().toString(36);
    const nt = { id, name: "New artefact", predefined: false, icon: "file", stage: "discover", desc: "", parents: [], children: [], siblings: [], source: { system: "teklens", loc: "" }, target: { system: "teklens", loc: "" }, creator: { kind: "skill", name: ART_SKILLS[0] }, output: "markdown", template: "" };
    setTypes((ts) => [...ts, nt]); setSelId(id);
  };

  const predefined = types.filter((t) => t.predefined);
  const custom = types.filter((t) => !t.predefined);

  return (
    <div className="flex-1 min-w-0 flex flex-col bg-[#f4f1ea]">
      {/* header */}
      <div className="shrink-0 bg-white border-b border-[#e8e3d8] px-6 py-3.5 flex items-center gap-2.5">
        <Icon name="settings" size={18} className="text-[#9b8866]" />
        <h1 className="text-[18px] font-semibold text-[#0e0e10]">Settings</h1>
        <Icon name="chevron-right" size={15} className="text-[#cbcbcb]" />
        <span className="text-[14px] font-medium text-[#5a5a5a]">Artefact types</span>
        <span className="ml-2 text-[12px] text-[#9aa0a6] hidden md:block">Define what artefacts exist, how they nest, where they live, and what creates them.</span>
      </div>

      {/* two-pane */}
      <div className="flex-1 min-h-0 flex">
        {/* LEFT — type list */}
        <div className="w-[280px] shrink-0 border-r border-[#e8e3d8] bg-[#faf8f3] flex flex-col">
          <div className="flex-1 overflow-y-auto px-2.5 py-3">
            <ArtGroup label="Predefined" hint="ship with Teklens">
              {predefined.map((t) => <ArtListRow key={t.id} t={t} active={t.id === selId} onClick={() => setSelId(t.id)} />)}
            </ArtGroup>
            <div className="h-3" />
            <ArtGroup label="Custom" hint="defined per project">
              {custom.map((t) => <ArtListRow key={t.id} t={t} active={t.id === selId} onClick={() => setSelId(t.id)} />)}
            </ArtGroup>
          </div>
          <div className="shrink-0 p-2.5 border-t border-[#e8e3d8]">
            <button onClick={addType} className="w-full flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg border border-[#ddd6c6] bg-white text-[13px] font-medium text-[#3a3a3a] hover:border-[var(--accent)]/50 hover:text-[var(--accent)]"><Icon name="plus" size={15} /> New artefact type</button>
          </div>
        </div>

        {/* RIGHT — editor */}
        <div className="flex-1 min-w-0 overflow-y-auto">
          <div className="max-w-[820px] mx-auto px-7 py-7 flex flex-col gap-7">
            <ArtEditor sel={sel} update={update} nameOf={nameOf} types={types} />
          </div>
        </div>
      </div>
    </div>
  );
}

function ArtGroup({ label, hint, children }) {
  return (
    <div>
      <div className="flex items-baseline gap-1.5 px-1.5 mb-1.5"><span className="text-[11px] font-semibold tracking-[0.06em] text-[#6b6b6b] uppercase">{label}</span><span className="text-[10.5px] text-[#9aa0a6]">{hint}</span></div>
      <div className="flex flex-col gap-0.5">{children}</div>
    </div>
  );
}
function ArtListRow({ t, active, onClick }) {
  const out = ART_OUTPUT[t.output];
  return (
    <button onClick={onClick} className={`group flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-left ${active ? "bg-white border border-[#e6dfcd] shadow-[0_1px_2px_rgba(0,0,0,0.04)]" : "border border-transparent hover:bg-white/60"}`}>
      <span className="w-7 h-7 rounded-md flex items-center justify-center shrink-0 bg-[#f1ede3] text-[#6b6b6b]"><Icon name={t.icon} size={14} /></span>
      <div className="min-w-0 flex-1">
        <div className="text-[13px] font-medium text-[#0e0e10] truncate">{t.name}</div>
        <div className="text-[10.5px] text-[#9aa0a6] flex items-center gap-1"><Icon name={out.icon} size={10} /> {out.label}</div>
      </div>
      <StagePip phase={t.stage} />
    </button>
  );
}

// ---------- editor ----------
function ArtEditor({ sel, update, nameOf, types }) {
  return (
    <>
      {/* identity */}
      <div className="flex items-start gap-3.5">
        <span className="w-12 h-12 rounded-xl flex items-center justify-center shrink-0 bg-white border border-[#e8e3d8] text-[#5a5a5a]"><Icon name={sel.icon} size={22} /></span>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <input value={sel.name} onChange={(e) => update({ name: e.target.value })} disabled={sel.predefined}
              className="text-[20px] font-semibold text-[#0e0e10] bg-transparent outline-none border-b border-transparent focus:border-[var(--accent)] disabled:cursor-default min-w-0" />
            <span className={`shrink-0 text-[10px] font-semibold uppercase tracking-[0.05em] px-1.5 py-0.5 rounded ${sel.predefined ? "bg-[#eef3fe] text-[#2657c4]" : "bg-[#f3eefe] text-[#7c5cf6]"}`}>{sel.predefined ? "Predefined" : "Custom"}</span>
          </div>
          <textarea value={sel.desc} onChange={(e) => update({ desc: e.target.value })} rows={2} placeholder="What is this artefact?"
            className="mt-1.5 w-full resize-none text-[13px] text-[#5a5a5a] bg-transparent outline-none leading-snug placeholder:text-[#bcb6a6]" />
        </div>
      </div>

      {/* stage */}
      <Field label="Stage" hint="which phase of an initiative this artefact belongs to">
        <div className="inline-flex items-center bg-white rounded-lg border border-[#e8e3d8] p-0.5">
          {DASH_PHASES.map((p) => (
            <button key={p.id} onClick={() => update({ stage: p.id })}
              className="px-3 py-1.5 rounded-md text-[12.5px] font-medium transition-colors"
              style={sel.stage === p.id ? { background: p.color, color: "#fff" } : { color: "#6b6b6b" }}>{p.name}</button>
          ))}
          <button onClick={() => update({ stage: "any" })} className={`px-3 py-1.5 rounded-md text-[12.5px] font-medium ${sel.stage === "any" ? "bg-[#0e0e10] text-white" : "text-[#6b6b6b]"}`}>Any</button>
        </div>
      </Field>

      {/* hierarchy */}
      <Field label="Hierarchy" hint="how this artefact links to others (parents · children · siblings)">
        <div className="flex flex-col gap-2.5">
          <HierRow icon="chevron-up" label="Parent of none — child of" rel="parents" sel={sel} update={update} nameOf={nameOf} types={types} />
          <HierRow icon="chevron-down" label="Parent of" rel="children" sel={sel} update={update} nameOf={nameOf} types={types} />
          <HierRow icon="link" label="Sibling of" rel="siblings" sel={sel} update={update} nameOf={nameOf} types={types} />
        </div>
      </Field>

      {/* source + target */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
        <Field label="Source" hint="where these usually already reside">
          <BindingEditor binding={sel.source} onChange={(b) => update({ source: b })} />
        </Field>
        <Field label="Target" hint="where promoted artefacts are written">
          <BindingEditor binding={sel.target} onChange={(b) => update({ target: b })} />
        </Field>
      </div>

      {/* created by */}
      <Field label="Created by" hint="a forge (plugin) or a skill produces this artefact">
        <div className="rounded-xl border border-[#e8e3d8] bg-white p-3.5 flex flex-col gap-3">
          <div className="flex items-center gap-2">
            <div className="inline-flex items-center bg-[#f4f1ea] rounded-lg p-0.5">
              {["forge", "skill"].map((k) => (
                <button key={k} onClick={() => update({ creator: { kind: k, name: (k === "forge" ? ART_FORGES : ART_SKILLS)[0] } })}
                  className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-[12.5px] font-medium capitalize ${sel.creator.kind === k ? "bg-white shadow-sm text-[#0e0e10]" : "text-[#6b6b6b]"}`}>
                  <Icon name={k === "forge" ? "wand" : "lab"} size={13} /> {k}
                </button>
              ))}
            </div>
            <Picker value={sel.creator.name} options={sel.creator.kind === "forge" ? ART_FORGES : ART_SKILLS} onChange={(v) => update({ creator: { ...sel.creator, name: v } })} icon={sel.creator.kind === "forge" ? "wand" : "lab"} />
          </div>
          {/* output */}
          <div className="flex items-center gap-2 pt-3 border-t border-[#f0ebdd]">
            <span className="text-[12px] text-[#6b6b6b] shrink-0">Produces</span>
            <div className="inline-flex items-center bg-[#f4f1ea] rounded-lg p-0.5">
              {Object.entries(ART_OUTPUT).map(([k, o]) => (
                <button key={k} onClick={() => update({ output: k })} className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-[12.5px] font-medium ${sel.output === k ? "bg-white shadow-sm text-[#0e0e10]" : "text-[#6b6b6b]"}`}><Icon name={o.icon} size={13} /> {o.label}</button>
              ))}
            </div>
            {sel.output === "widget" && (
              <div className="ml-auto"><Picker value={sel.widget || ART_WIDGETS[0]} options={ART_WIDGETS} onChange={(v) => update({ widget: v })} icon="grid" /></div>
            )}
          </div>
        </div>
      </Field>

      {/* template / widget output */}
      {sel.output === "widget" ? (
        <Field label="Output widget" hint="the forge/skill renders this widget instead of a document">
          <div className="rounded-xl border border-[#e8e3d8] bg-white p-4 flex items-center gap-3">
            <span className="w-10 h-10 rounded-lg flex items-center justify-center shrink-0 bg-[var(--accent)]/[0.08] text-[var(--accent)]"><Icon name="grid" size={18} /></span>
            <div className="min-w-0">
              <div className="text-[13.5px] font-medium text-[#0e0e10]">{sel.widget || ART_WIDGETS[0]} widget</div>
              <div className="text-[11.5px] text-[#9aa0a6]">Interactive surface shipped by the {sel.creator.name}. No markdown template needed.</div>
            </div>
          </div>
        </Field>
      ) : (
        <Field label="Template" hint={`structural ${ART_OUTPUT[sel.output].label.toLowerCase()} the ${sel.creator.kind} fills in`}>
          <div className="rounded-xl border border-[#e8e3d8] bg-white overflow-hidden">
            <div className="px-3 py-2 border-b border-[#f0ebdd] bg-[#faf8f3] flex items-center gap-2 text-[11.5px] text-[#9aa0a6]"><Icon name={ART_OUTPUT[sel.output].icon} size={12} /> {sel.name.toLowerCase()}.{sel.output === "html" ? "html" : "md"}</div>
            <textarea value={sel.template || ""} onChange={(e) => update({ template: e.target.value })} rows={8} placeholder="Add a structural template or example…"
              className="w-full resize-none px-3.5 py-3 text-[12.5px] font-mono text-[#1a1a1a] bg-transparent outline-none leading-relaxed placeholder:text-[#bcb6a6]" />
          </div>
        </Field>
      )}

      <div className="flex items-center gap-2 pt-1">
        <button className="flex items-center gap-1.5 px-3.5 py-2 rounded-lg bg-[var(--accent)] text-white text-[13px] font-medium hover:brightness-110 shadow-[0_1px_0_rgba(0,0,0,0.08)]"><Icon name="check" size={15} /> Save artefact type</button>
        {!sel.predefined && <button className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-[13px] text-[#c2410c] hover:bg-[#c2410c]/[0.07]"><Icon name="trash" size={14} /> Delete</button>}
      </div>
      <div className="h-2" />
    </>
  );
}

function Field({ label, hint, children }) {
  return (
    <div>
      <div className="flex items-baseline gap-2 mb-2">
        <span className="text-[13px] font-semibold text-[#0e0e10]">{label}</span>
        {hint && <span className="text-[11.5px] text-[#9aa0a6]">{hint}</span>}
      </div>
      {children}
    </div>
  );
}

// hierarchy relation row — chips + add menu
function HierRow({ icon, label, rel, sel, update, nameOf, types }) {
  const [open, setOpen] = useState(false);
  const current = sel[rel] || [];
  const candidates = types.filter((t) => t.id !== sel.id && !current.includes(t.id));
  const remove = (id) => update({ [rel]: current.filter((x) => x !== id) });
  const add = (id) => { update({ [rel]: [...current, id] }); setOpen(false); };
  return (
    <div className="flex items-center gap-2.5">
      <span className="w-[120px] shrink-0 flex items-center gap-1.5 text-[12px] text-[#6b6b6b]"><Icon name={icon} size={13} className="text-[#9aa0a6]" /> {label}</span>
      <div className="flex-1 flex flex-wrap items-center gap-1.5">
        {current.length === 0 && <span className="text-[12px] text-[#bcb6a6]">none</span>}
        {current.map((id) => (
          <span key={id} className="inline-flex items-center gap-1 pl-2 pr-1 py-1 rounded-md border border-[#e6dfcd] bg-white text-[12px] text-[#0e0e10]">
            {nameOf(id)}
            <button onClick={() => remove(id)} className="p-0.5 rounded hover:bg-black/[0.06] text-[#9aa0a6]"><Icon name="x" size={11} /></button>
          </span>
        ))}
        <div className="relative">
          <button onClick={() => setOpen((o) => !o)} disabled={candidates.length === 0} className="inline-flex items-center gap-1 px-2 py-1 rounded-md border border-dashed border-[#d6cfbc] text-[12px] text-[#6b6b6b] hover:border-[var(--accent)]/50 hover:text-[var(--accent)] disabled:opacity-40"><Icon name="plus" size={12} /> Add</button>
          {open && (
            <>
              <div className="fixed inset-0 z-30" onClick={() => setOpen(false)} />
              <div className="absolute left-0 top-full mt-1 w-[200px] bg-white rounded-lg border border-[#ece7da] shadow-xl z-40 py-1">
                {candidates.map((t) => (
                  <button key={t.id} onClick={() => add(t.id)} className="w-full flex items-center gap-2 px-3 py-1.5 text-[12.5px] text-[#1f1f1f] hover:bg-black/[0.04] text-left"><Icon name={t.icon} size={13} className="text-[#9aa0a6]" /> {t.name}</button>
                ))}
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// source / target binding editor
function BindingEditor({ binding, onChange }) {
  const [open, setOpen] = useState(false);
  const s = ART_SYS[binding.system];
  return (
    <div className="rounded-xl border border-[#e8e3d8] bg-white p-3 flex flex-col gap-2.5">
      <div className="relative">
        <button onClick={() => setOpen((o) => !o)} className="w-full flex items-center gap-2 px-2.5 py-2 rounded-lg border border-[#ece7da] hover:border-[var(--accent)]/40 text-left">
          <span className="shrink-0" style={{ color: s.color }}><Icon name={s.icon} size={16} /></span>
          <span className="text-[13px] font-medium text-[#0e0e10] flex-1">{s.label}</span>
          <Icon name="chevron-down" size={14} className="text-[#9aa0a6]" />
        </button>
        {open && (
          <>
            <div className="fixed inset-0 z-30" onClick={() => setOpen(false)} />
            <div className="absolute left-0 right-0 top-full mt-1 bg-white rounded-lg border border-[#ece7da] shadow-xl z-40 py-1">
              {Object.entries(ART_SYS).map(([k, v]) => (
                <button key={k} onClick={() => { onChange({ ...binding, system: k }); setOpen(false); }} className="w-full flex items-center gap-2 px-3 py-1.5 text-[12.5px] text-[#1f1f1f] hover:bg-black/[0.04] text-left"><span style={{ color: v.color }}><Icon name={v.icon} size={14} /></span> {v.label}</button>
              ))}
            </div>
          </>
        )}
      </div>
      <div className="flex items-center gap-2 px-2.5 py-2 rounded-lg border border-[#ece7da] focus-within:border-[var(--accent)]/50">
        <Icon name="pin" size={13} className="text-[#9aa0a6] shrink-0" />
        <input value={binding.loc} onChange={(e) => onChange({ ...binding, loc: e.target.value })} placeholder="location…" className="flex-1 bg-transparent outline-none text-[12.5px] text-[#0e0e10] placeholder:text-[#bcb6a6]" />
      </div>
    </div>
  );
}

function Picker({ value, options, onChange, icon }) {
  const [open, setOpen] = useState(false);
  return (
    <div className="relative flex-1 min-w-0">
      <button onClick={() => setOpen((o) => !o)} className="w-full flex items-center gap-2 px-2.5 py-1.5 rounded-md border border-[#ece7da] bg-white hover:border-[var(--accent)]/40 text-left">
        {icon && <Icon name={icon} size={13} className="text-[var(--accent)] shrink-0" />}
        <span className="text-[12.5px] text-[#0e0e10] flex-1 truncate">{value}</span>
        <Icon name="chevron-down" size={13} className="text-[#9aa0a6]" />
      </button>
      {open && (
        <>
          <div className="fixed inset-0 z-30" onClick={() => setOpen(false)} />
          <div className="absolute left-0 right-0 top-full mt-1 bg-white rounded-lg border border-[#ece7da] shadow-xl z-40 py-1 max-h-[240px] overflow-y-auto">
            {options.map((o) => (
              <button key={o} onClick={() => { onChange(o); setOpen(false); }} className="w-full flex items-center gap-2 px-3 py-1.5 text-[12.5px] text-[#1f1f1f] hover:bg-black/[0.04] text-left">{o}{o === value && <Icon name="check" size={13} className="ml-auto text-[var(--accent)]" />}</button>
            ))}
          </div>
        </>
      )}
    </div>
  );
}
