/* ============================================================
   WCW Product Hub — Intake form (field guidance + AI draft)
   and Marketing review (approve AI-drafted fields)
   ============================================================ */
const { useState: useStateIntake, useRef: useRefIntake } = React;

const PACK_RE = /^\d+\/\d+(\.\d+)?\s(OZ|LB|G|KG|ML|L|CT|EA)\s(CS|EA|PK)$/i;

/* ---------- multi-select chips (warehouses, companies, sell-as) ---------- */
function MultiChips({ value, onChange, source, options }) {
  const list = source ? (window.HUB_DATA.SOURCES[source] || []).map(o => ({ v: o.code, label: o.name, sub: o.desc })) : options;
  const val = Array.isArray(value) ? value : [];
  const toggle = (v) => onChange(val.includes(v) ? val.filter(x => x !== v) : [...val, v]);
  return (
    <div className="mchips">
      {list.map(o => {
        const sel = val.includes(o.v);
        return (
          <button type="button" key={o.v} className={`mchip ${sel ? "sel" : ""}`} onClick={() => toggle(o.v)}>
            <span className="mchk">{sel && <Icon name="check" size={11} />}</span>
            <span>
              {source ? <span className="mc-code">{o.v}</span> : null} {o.label}
              {o.sub && <span className="mc-sub" style={{ display: "block" }}>{o.sub}</span>}
            </span>
          </button>
        );
      })}
    </div>
  );
}

/* ---------- purchase sources (vendor + item# + GTIN + cost, repeatable) ---------- */
function PurchaseSources({ value, onChange }) {
  const rows = Array.isArray(value) ? value : [];
  const update = (i, k, v) => onChange(rows.map((r, idx) => idx === i ? { ...r, [k]: v } : r));
  const setPrimary = (i) => onChange(rows.map((r, idx) => ({ ...r, primary: idx === i })));
  const remove = (i) => onChange(rows.filter((_, idx) => idx !== i));
  const add = () => onChange([...rows, { vendor: "", item: "", gtin: "", cost: "", primary: rows.length === 0 }]);
  return (
    <div className="src-list">
      {rows.map((r, i) => (
        <div className={`src-row ${r.primary ? "primary" : ""}`} key={i}>
          <div className="src-grid">
            <div><span className="micro">Vendor / distributor</span><input className="inp" value={r.vendor} placeholder="e.g. Fever-Tree (UNFI)" onChange={e => update(i, "vendor", e.target.value)} /></div>
            <div><span className="micro">Vendor item #</span><input className="inp" value={r.item} placeholder="SKU" onChange={e => update(i, "item", e.target.value)} /></div>
            <div><span className="micro">Case GTIN-14</span><input className="inp mono" style={{ fontSize: 12 }} value={r.gtin} placeholder="1 00000 00000 0" onChange={e => update(i, "gtin", e.target.value)} /></div>
            <div><span className="micro">Case cost</span><div className="src-cost"><input className="inp" value={r.cost} placeholder="0.00" onChange={e => update(i, "cost", e.target.value)} /></div></div>
          </div>
          <div className="src-foot">
            <button type="button" className="prim-toggle" onClick={() => setPrimary(i)}><span className="dot"></span> {r.primary ? "Primary source" : "Make primary"}</button>
            {rows.length > 1 && <button type="button" className="src-rm" onClick={() => remove(i)}>Remove</button>}
          </div>
        </div>
      ))}
      <button type="button" className="src-add" onClick={add}><Icon name="plus" size={14} /> Add another source</button>
    </div>
  );
}

/* ---------- a single guided field ---------- */
function GuidedField({ f, value, onChange, openWhy, setOpenWhy, alwaysGuide }) {
  const isOpen = alwaysGuide || openWhy === f.key;
  let validity = null;
  if (f.validate === "pack" && value) validity = PACK_RE.test(value.trim()) ? "ok" : "bad";
  const len = typeof value === "string" ? value.length : 0;

  return (
    <div className={`field ${f.full ? "full" : ""}`}>
      <div className="field-top">
        <label>{f.label}{f.req && <span className="req">*</span>}</label>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          {f.maxLen && <span className={`char-count ${len > f.maxLen ? "over" : len > f.maxLen - 8 ? "near" : ""}`}>{len}/{f.maxLen}</span>}
          {f.owner && <span className="owner-tag">{f.owner}</span>}
          {f.guidance && (
            <button type="button" className={`why-btn ${isOpen ? "active" : ""}`} onClick={() => setOpenWhy(isOpen ? null : f.key)}>
              <span className="qd">i</span> Why?
            </button>
          )}
        </div>
      </div>

      {f.type === "text" && (
        <input className={`inp ${validity || ""}`} value={value} placeholder={f.placeholder} maxLength={f.maxLen}
          onChange={e => onChange(f.key, e.target.value)} />
      )}
      {f.type === "date" && (
        <input type="date" className="inp" value={value} onChange={e => onChange(f.key, e.target.value)} />
      )}
      {f.type === "rselect" && (
        <RichSelect value={value} source={f.source} onChange={v => onChange(f.key, v)} />
      )}
      {f.type === "multi" && (
        <MultiChips value={value} source={f.source} options={f.options} onChange={v => onChange(f.key, v)} />
      )}
      {f.type === "checks" && (
        <MultiChips value={value} options={f.options.map(o => ({ v: o.v, label: o.v, sub: o.desc }))} onChange={v => onChange(f.key, v)} />
      )}
      {f.type === "sources" && (
        <PurchaseSources value={value} onChange={v => onChange(f.key, v)} />
      )}
      {f.type === "upload" && (
        <div className="dropzone">
          <div className="dz-ico"><Icon name="upload" size={24} /></div>
          <b>{f.label}</b>
          <p>{f.desc}</p>
        </div>
      )}
      {f.type === "cards" && (
        <div className="opt-cards">
          {f.options.map(o => (
            <button type="button" key={o.v} className={`opt-card ${value === o.v ? "sel" : ""}`} onClick={() => onChange(f.key, o.v)}>
              <div className="oc-label"><span className="radio"></span>{o.v}</div>
              <div className="oc-desc">{o.desc}</div>
            </button>
          ))}
        </div>
      )}

      {validity === "ok" && <div className="validate ok"><Icon name="check" size={13} /> Valid PPRO pack format</div>}
      {validity === "bad" && <div className="validate bad"><Icon name="alert" size={13} /> Use count/size unit CS — e.g. 12/14 OZ CS</div>}

      {/* derived chips */}
      {f.key === "pack" && validity === "ok" && (() => {
        const [c, rest] = value.trim().split("/"); const [sz, unit] = rest.split(" ");
        return <div style={{ display: "flex", gap: 6, marginTop: 8, flexWrap: "wrap" }}>
          <span className="derived"><Icon name="settings" size={11} /> Pack Qty <span className="mono">{c}</span></span>
          <span className="derived"><Icon name="settings" size={11} /> Size <span className="mono">{sz}</span></span>
          <span className="derived"><Icon name="settings" size={11} /> UoM <span className="mono">{unit}</span></span>
        </div>;
      })()}
      {f.key === "catch" && value === "Yes" && (
        <div className="nudge warn"><span className="n-ico"><Icon name="alert" size={14} /></span><div><b>Catch weight set.</b> The New Item Team will set Pound Type and Entry codes — you don't need to.</div></div>
      )}
      {f.key === "dept" && value && (
        <div className="nudge info"><span className="n-ico"><Icon name="sparkle" size={14} /></span><div>Naming rules and Class options for <b>{(window.HUB_DATA.DEPARTMENTS.find(d => d.code === value) || {}).name}</b> will be applied automatically.</div></div>
      )}

      {isOpen && f.guidance && (
        <div className="guidance">
          <div className="g-what">{f.guidance.what}</div>
          <div className="g-why">{f.guidance.why}</div>
          {f.guidance.examples && (
            <div className="g-ex">
              <div className="g-ex-h">Good examples</div>
              {f.guidance.examples.map((e, i) => <span className="ex" key={i}>{e}</span>)}
            </div>
          )}
          {f.guidance.ask && <div className="g-ask"><b>If stuck</b> — {f.guidance.ask}</div>}
        </div>
      )}
    </div>
  );
}

/* ---------- AI draft panel (shown in intake) ---------- */
function AIDraftPanel({ draft, loading, onRun, onAccept }) {
  return (
    <div className="card" style={{ marginBottom: 22, overflow: "hidden", borderColor: "var(--red-line)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 13, padding: "16px 22px", background: "linear-gradient(100deg, var(--red-soft), var(--surface) 92%)", borderBottom: "1px solid var(--line)" }}>
        <div style={{ width: 38, height: 38, borderRadius: 10, background: "var(--surface)", border: "1px solid var(--red-line)", color: "var(--red)", display: "grid", placeItems: "center", flexShrink: 0 }}>
          <Icon name="sparkle" size={19} />
        </div>
        <div style={{ flex: 1 }}>
          <b style={{ fontSize: 14.5 }}>AI draft — classification & copy</b>
          <p style={{ fontSize: 12, color: "var(--ink-2)", marginTop: 1 }}>
            Department, Class, Commodity, the PPRO name and romantic copy — drafted from standard rules, then reviewed by Marketing.
          </p>
        </div>
        <button className="btn btn-primary btn-sm" onClick={onRun} disabled={loading}>
          {loading ? <><span className="spin" /> Drafting…</> : <><Icon name="sparkle" size={14} /> {draft ? "Regenerate" : "Draft with AI"}</>}
        </button>
      </div>

      {draft && (
        <div style={{ padding: "18px 22px" }}>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 12, marginBottom: 16 }}>
            {[["Department", draft.department, true], ["Class", draft.klass], ["Commodity", draft.commodity, false, true]].map(([l, v, code, mono], i) => (
              <div key={i} style={{ background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 9, padding: "10px 12px" }}>
                <div className="eyebrow" style={{ fontSize: 9.5, marginBottom: 4 }}>{l} <span className="derived" style={{ padding: "0 5px", fontSize: 9 }}>AI</span></div>
                <div style={{ fontWeight: 700, fontSize: 13.5 }}>{code ? <span className="tag code">{v}</span> : mono ? <span className="mono" style={{ fontSize: 12 }}>{v}</span> : v}</div>
              </div>
            ))}
          </div>
          <div style={{ marginBottom: 14 }}>
            <div className="eyebrow" style={{ fontSize: 9.5, marginBottom: 5, display: "flex", alignItems: "center", gap: 7 }}>PPRO name <span className="derived" style={{ padding: "0 5px", fontSize: 9 }}>AI</span>
              {(() => { const l = (draft.ppro_name || "").length; return <span className={`char-count ${l > 50 ? "over" : l > 42 ? "near" : ""}`} style={{ marginLeft: "auto" }}>{l}/50</span>; })()}
            </div>
            <div className="mono" style={{ fontSize: 14, fontWeight: 700, color: "var(--ink)", background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 9, padding: "10px 13px" }}>{draft.ppro_name}</div>
            {draft.naming_note && <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 5, fontStyle: "italic" }}>{draft.naming_note}</div>}
          </div>
          <div style={{ marginBottom: 14 }}>
            <div className="eyebrow" style={{ fontSize: 9.5, marginBottom: 5 }}>Product description <span className="derived" style={{ padding: "0 5px", fontSize: 9 }}>AI</span></div>
            <div style={{ fontSize: 13, lineHeight: 1.55, color: "var(--ink-2)", background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 9, padding: "11px 13px" }}>{draft.romantic_copy}</div>
          </div>
          {draft.features_benefits && draft.features_benefits.length > 0 && (
            <div style={{ marginBottom: 14 }}>
              <div className="eyebrow" style={{ fontSize: 9.5, marginBottom: 5 }}>Features &amp; benefits <span className="derived" style={{ padding: "0 5px", fontSize: 9 }}>AI</span></div>
              <div style={{ fontSize: 13, lineHeight: 1.5, color: "var(--ink-2)", background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 9, padding: "11px 13px", display: "flex", flexDirection: "column", gap: 4 }}>{draft.features_benefits.map((b, i) => <div key={i}>{b}</div>)}</div>
            </div>
          )}
          {draft.handling_instructions && draft.handling_instructions.length > 0 && (
            <div style={{ marginBottom: 14 }}>
              <div className="eyebrow" style={{ fontSize: 9.5, marginBottom: 5 }}>Handling instructions <span className="derived" style={{ padding: "0 5px", fontSize: 9 }}>AI</span></div>
              <div style={{ fontSize: 13, lineHeight: 1.5, color: "var(--ink-2)", background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 9, padding: "11px 13px", display: "flex", flexDirection: "column", gap: 4 }}>{draft.handling_instructions.map((b, i) => <div key={i}>{b}</div>)}</div>
            </div>
          )}
          {draft.keywords && draft.keywords.length > 0 && (
            <div style={{ marginBottom: 14 }}>
              <div className="eyebrow" style={{ fontSize: 9.5, marginBottom: 6 }}>Keywords <span className="derived" style={{ padding: "0 5px", fontSize: 9 }}>AI · from materials</span></div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 7 }}>{draft.keywords.map((k, i) => <span className="kw" key={i}><Icon name="tag" size={11} style={{ color: "var(--ink-3)" }} /> {k}</span>)}</div>
            </div>
          )}
          {draft.attributes && draft.attributes.length > 0 && (
            <div>
              <div className="eyebrow" style={{ fontSize: 9.5, marginBottom: 6 }}>Attributes <span className="derived" style={{ padding: "0 5px", fontSize: 9 }}>AI · from materials</span></div>
              <div style={{ background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 9, padding: "4px 13px" }}>
                {draft.attributes.map((a, i) => <div className="attr-row" key={i}><span className="ak">{a.label}</span><span className="av">{a.value}</span></div>)}
              </div>
            </div>
          )}
          <div className="nudge info" style={{ marginTop: 14 }}>
            <span className="n-ico"><Icon name="user" size={14} /></span>
            <div>These are <b>drafts</b>. They travel with the product to Marketing, who reviews and approves — no need to get the wording perfect here.{draft._fallback && <em style={{ color: "var(--ink-3)" }}> (offline sample shown)</em>}</div>
          </div>
        </div>
      )}
    </div>
  );
}

/* ---------- Intake form view ---------- */
function IntakeView({ onBack, onSubmit, pushToast, alwaysGuide }) {
  const D = window.HUB_DATA;
  const sections = D.FIELD_SECTIONS;
  const [activeSec, setActiveSec] = useStateIntake(sections[0].id);
  const [openWhy, setOpenWhy] = useStateIntake(null);
  const [draft, setDraft] = useStateIntake(null);
  const [loadingAI, setLoadingAI] = useStateIntake(false);

  // seed values from spec
  const [vals, setVals] = useStateIntake(() => {
    const v = {};
    sections.forEach(s => s.fields.forEach(f => { v[f.key] = f.value || ""; }));
    return v;
  });
  const onChange = (k, val) => setVals(s => ({ ...s, [k]: val }));

  // visibility + filled helpers (handle new field types & conditionals)
  const isVisible = (f) => !f.showIf || f.showIf(vals);
  const isFilled = (f) => {
    const v = vals[f.key];
    if (f.type === "sources") return Array.isArray(v) && v.some(r => r.vendor && r.vendor.trim());
    if (Array.isArray(v)) return v.length > 0;
    return v != null && String(v).trim() !== "";
  };

  // progress = required + visible filled
  const allFields = sections.flatMap(s => s.fields);
  const reqFields = allFields.filter(f => f.req && isVisible(f));
  const filled = reqFields.filter(isFilled).length;
  const pct = reqFields.length ? Math.round((filled / reqFields.length) * 100) : 0;

  const secProgress = (s) => {
    const req = s.fields.filter(f => f.req && isVisible(f));
    const done = req.filter(isFilled).length;
    return { done, total: req.length, complete: done === req.length, partial: done > 0 && done < req.length };
  };

  const runAI = async () => {
    setLoadingAI(true);
    const primary = (Array.isArray(vals.sources) ? vals.sources.find(r => r.primary) || vals.sources[0] : null) || {};
    const product = {
      name: vals.desc || "NEW PRODUCT", dept: vals.dept, cls: "",
      vendor: primary.vendor || "", pack: vals.pack, brand: vals.brand, origin: vals.origin,
    };
    const res = await window.HubAI.draftProduct(product);
    setDraft(res);
    setLoadingAI(false);
    pushToast("AI draft ready — Marketing will review it", "sparkle");
  };

  return (
    <div className="page viewfade">
      <button className="btn btn-quiet btn-sm" onClick={onBack} style={{ marginBottom: 16 }}><Icon name="chevRight" size={14} style={{ transform: "rotate(180deg)" }} /> Cancel</button>
      <div className="page-head" style={{ marginBottom: 22 }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 6 }}>New product request</div>
          <h1>Tell us about the product</h1>
          <div className="sub">Fill the fields you own — Marketing & the New Item Team pick it up after. Stuck? Hit <b>Why?</b> on any field.</div>
        </div>
        <button className="btn btn-ghost" onClick={() => pushToast("Draft saved", "check")}>Save draft</button>
      </div>

      <div className="intake">
        {/* rail */}
        <aside className="intake-rail">
          <div className="intake-progress">
            <div className="ip-ring">
              <Ring pct={pct} />
              <div className="ip-label"><b>{filled}/{reqFields.length}</b><span>required fields</span></div>
            </div>
            <ul className="step-nav">
              {sections.map(s => {
                const sp = secProgress(s);
                return (
                  <li key={s.id} className={`${activeSec === s.id ? "active" : ""} ${sp.complete ? "complete" : sp.partial ? "partial" : ""}`}
                    onClick={() => { setActiveSec(s.id); document.getElementById("sec-" + s.id)?.scrollIntoView({ block: "start" }); }}>
                    <span className="sn-check">{sp.complete ? <Icon name="check" size={11} /> : sp.done}</span>
                    {s.title}
                  </li>
                );
              })}
            </ul>
          </div>
          <div className="help-card">
            <b>Coming next</b>
            <p>Marketing review (AI drafts pre-filled), then New Item Team setup in PPRO.</p>
          </div>
        </aside>

        {/* form */}
        <div>
          <AIDraftPanel draft={draft} loading={loadingAI} onRun={runAI} />

          <div className="intake-main">
            <div className="intake-banner">
              <div className="ib-ico"><Icon name="book" size={17} /></div>
              <div><b>First time setting up a product?</b> Click <b>Why?</b> next to any field for what it means, why it matters, and who to ask. Your progress is saved as you go.</div>
            </div>
            <div className="intake-body">
              {sections.map(s => (
                <div key={s.id} id={"sec-" + s.id} style={{ marginBottom: 30 }}>
                  <div className="intake-sec-head">
                    <h2>{s.title}</h2>
                    <span className="ish-count">{secProgress(s).done} of {secProgress(s).total} required</span>
                  </div>
                  <div className="fgrid">
                    {s.fields.filter(isVisible).map(f => (
                      <GuidedField key={f.key} f={f} value={vals[f.key]} onChange={onChange} openWhy={openWhy} setOpenWhy={setOpenWhy} alwaysGuide={alwaysGuide} />
                    ))}
                  </div>
                </div>
              ))}
            </div>
            <div className="intake-foot">
              <span style={{ fontSize: 12.5, color: "var(--ink-3)" }}>{pct}% of required fields complete</span>
              <div style={{ display: "flex", gap: 10 }}>
                <button className="btn btn-ghost" onClick={() => pushToast("Saved & exited", "check")}>Save & exit</button>
                <button className="btn btn-primary" onClick={() => onSubmit(vals, draft)}>Submit to Marketing <Icon name="arrowRight" size={14} /></button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- Marketing review (approve AI drafts) ---------- */
function ReviewView({ product, me, onBack, onApprove, pushToast }) {
  const D = window.HUB_DATA;
  const p = product;
  const [draft, setDraft] = useStateIntake(null);
  const [loading, setLoading] = useStateIntake(false);
  const [approved, setApproved] = useStateIntake({});
  const [editing, setEditing] = useStateIntake(null);
  const [vals, setVals] = useStateIntake({});

  const run = async () => {
    setLoading(true);
    const res = await window.HubAI.draftProduct(p);
    setDraft(res);
    setVals({ ppro_name: res.ppro_name, romantic_copy: res.romantic_copy, klass: res.klass, commodity: res.commodity, department: res.department, features_benefits: res.features_benefits || [], handling_instructions: res.handling_instructions || [], keywords: res.keywords || [], attributes: res.attributes || [] });
    setLoading(false);
  };
  React.useEffect(() => { run(); }, [p.id]);

  const items = [
    { key: "department", label: "Department", code: true },
    { key: "klass", label: "Class" },
    { key: "commodity", label: "Commodity", mono: true },
    { key: "ppro_name", label: "PPRO name", mono: true, big: true, maxLen: 50 },
    { key: "romantic_copy", label: "Product description", area: true },
    { key: "features_benefits", label: "Features & benefits", kind: "lines" },
    { key: "handling_instructions", label: "Handling instructions", kind: "lines" },
    { key: "keywords", label: "Keywords", kind: "kw" },
    { key: "attributes", label: "Attributes", kind: "attr" },
  ];
  const allApproved = draft && items.every(it => approved[it.key]);

  return (
    <div className="page viewfade">
      <button className="btn btn-quiet btn-sm" onClick={onBack} style={{ marginBottom: 16 }}><Icon name="chevRight" size={14} style={{ transform: "rotate(180deg)" }} /> Back</button>

      <div className="detail-head" style={{ marginBottom: 22 }}>
        <div className="dh-crumb"><b>{p.deptName}</b> · {p.cls} · Marketing review</div>
        <h1>{p.name}</h1>
        <div className="dh-meta">
          <span className="tag code">{p.dept}</span><span>{p.vendor}</span><span>·</span>
          <span>Submitted by <span className="who">{p.buyer}</span></span>
        </div>
      </div>

      <div className="detail-grid">
        <div>
          <div className="alert-banner" style={{ marginBottom: 20, background: "linear-gradient(100deg, var(--red-soft), var(--surface) 90%)", borderColor: "var(--red-line)" }}>
            <div className="ab-ico" style={{ background: "var(--surface)", borderColor: "var(--red-line)", color: "var(--red)" }}><Icon name="sparkle" size={19} /></div>
            <div className="ab-body">
              <b>AI drafted these from the buyer's entry + vendor materials</b>
              <p>Naming, classification, copy, keywords and attributes — read from the spec sheet & sell sheet. Review and approve, edit, or regenerate.</p>
            </div>
            <button className="btn btn-ghost btn-sm" onClick={run} disabled={loading}>{loading ? "Drafting…" : <><Icon name="sparkle" size={13} /> Regenerate all</>}</button>
          </div>

          {loading && !draft && (
            <div className="card card-pad empty"><div className="e-ico"><span className="spin" style={{ width: 26, height: 26, borderWidth: 3 }} /></div><b>AI is drafting…</b>Applying the {p.deptName} naming convention and writing copy.</div>
          )}

          {draft && items.map(it => (
            <div className="card" key={it.key} style={{ marginBottom: 12, borderColor: approved[it.key] ? "color-mix(in oklch, var(--live) 35%, white)" : "var(--line)" }}>
              <div style={{ padding: "13px 18px", display: "flex", alignItems: "center", justifyContent: "space-between", borderBottom: "1px solid var(--line)" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
                  <span className="eyebrow" style={{ fontSize: 10 }}>{it.label}</span>
                  <span className="derived" style={{ fontSize: 9.5, padding: "1px 6px" }}><Icon name="sparkle" size={10} /> AI</span>
                  {it.maxLen && (() => { const l = (vals[it.key] || "").length; return <span className={`char-count ${l > it.maxLen ? "over" : l > it.maxLen - 8 ? "near" : ""}`}>{l}/{it.maxLen}</span>; })()}
                </div>
                {approved[it.key]
                  ? <span className="tag live"><Icon name="check" size={11} /> Approved</span>
                  : <div style={{ display: "flex", gap: 6 }}>
                      <button className="btn btn-quiet btn-sm" onClick={() => setEditing(editing === it.key ? null : it.key)}>Edit</button>
                      <button className="btn btn-dark btn-sm" onClick={() => { setApproved(a => ({ ...a, [it.key]: true })); setEditing(null); pushToast(it.label + " approved", "check"); }}><Icon name="check" size={12} /> Approve</button>
                    </div>}
              </div>
              <div style={{ padding: "13px 18px" }}>
                {it.kind === "kw" ? (
                  editing === it.key
                    ? <input className="inp" value={(vals.keywords || []).join(", ")} autoFocus
                        onChange={e => setVals(v => ({ ...v, keywords: e.target.value.split(",").map(s => s.trim()).filter(Boolean) }))} />
                    : <div style={{ display: "flex", flexWrap: "wrap", gap: 7 }}>{(vals.keywords || []).map((k, i) => <span className="kw" key={i}><Icon name="tag" size={11} style={{ color: "var(--ink-3)" }} /> {k}</span>)}</div>
                ) : it.kind === "attr" ? (
                  editing === it.key
                    ? <textarea className="inp" style={{ minHeight: 100 }} autoFocus
                        value={(vals.attributes || []).map(a => `${a.label}: ${a.value}`).join("\n")}
                        onChange={e => setVals(v => ({ ...v, attributes: e.target.value.split("\n").filter(Boolean).map(line => { const [label, ...rest] = line.split(":"); return { label: label.trim(), value: rest.join(":").trim() }; }) }))} />
                    : <div>{(vals.attributes || []).map((a, i) => <div className="attr-row" key={i}><span className="ak">{a.label}</span><span className="av">{a.value}</span></div>)}</div>
                ) : it.kind === "lines" ? (
                  editing === it.key
                    ? <textarea className="inp" style={{ minHeight: 90 }} autoFocus
                        value={(vals[it.key] || []).join("\n")}
                        onChange={e => setVals(v => ({ ...v, [it.key]: e.target.value.split("\n").map(s => s.trim()).filter(Boolean) }))} />
                    : <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>{(vals[it.key] || []).map((line, i) => <div key={i} style={{ fontSize: 13.5, lineHeight: 1.45, color: "var(--ink-2)" }}>{line}</div>)}</div>
                ) : editing === it.key ? (
                  it.area
                    ? <textarea className="inp" value={vals[it.key]} onChange={e => setVals(v => ({ ...v, [it.key]: e.target.value }))} style={{ minHeight: 80 }} autoFocus />
                    : <input className="inp" value={vals[it.key]} maxLength={it.maxLen} onChange={e => setVals(v => ({ ...v, [it.key]: e.target.value }))} autoFocus />
                ) : (
                  it.code ? <span className="tag code" style={{ fontSize: 12 }}>{vals[it.key]}</span>
                  : it.mono ? <span className="mono" style={{ fontSize: it.big ? 15 : 13, fontWeight: 700 }}>{vals[it.key]}</span>
                  : <span style={{ fontSize: it.area ? 13 : 14, lineHeight: 1.55, color: it.area ? "var(--ink-2)" : "var(--ink)", fontWeight: it.area ? 400 : 600, whiteSpace: it.area ? "pre-line" : "normal" }}>{vals[it.key]}</span>
                )}
              </div>
            </div>
          ))}
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          <div className="card card-pad" style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <div className="eyebrow">Review progress</div>
            <Ring pct={draft ? Math.round(Object.values(approved).filter(Boolean).length / items.length * 100) : 0} size={64} />
            <div style={{ fontSize: 12.5, color: "var(--ink-3)" }}>{Object.values(approved).filter(Boolean).length} of {items.length} fields approved</div>
            <button className="btn btn-primary btn-lg" style={{ justifyContent: "center" }} disabled={!allApproved}
              onClick={() => onApprove(p.id)}>
              <Icon name="arrowRight" size={16} /> Send to New Item Team
            </button>
            {!allApproved && <div style={{ fontSize: 11.5, color: "var(--ink-3)", textAlign: "center" }}>Approve all fields to continue</div>}
          </div>

          <div className="card card-pad">
            <div className="eyebrow" style={{ marginBottom: 10 }}>From the purchaser</div>
            <div className="sales-strip">
              {[["Vendor", p.vendor], ["Pack", p.pack], ["Origin", p.origin], ["Cost", p.cost]].map(([l, v]) => (
                <div key={l} style={{ display: "flex", justifyContent: "space-between", padding: "7px 0", borderBottom: "1px solid var(--line)", fontSize: 13 }}>
                  <span style={{ color: "var(--ink-3)" }}>{l}</span><b>{v}</b>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- Reactivation: pick a dormant item to bring back ---------- */
function ReactivatePicker({ onBack, onPick }) {
  const D = window.HUB_DATA;
  const items = D.DISCONTINUED;
  return (
    <div className="page viewfade">
      <button className="btn btn-quiet btn-sm" onClick={onBack} style={{ marginBottom: 16 }}><Icon name="chevRight" size={14} style={{ transform: "rotate(180deg)" }} /> Back</button>
      <div className="page-head" style={{ marginBottom: 22 }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 6 }}>Reactivate a product</div>
          <h1>Bring a dormant item back</h1>
          <div className="sub">These were live before. Their PPRO record is preserved — pick one and you'll only re-verify the fields likely to have changed, not re-enter everything.</div>
        </div>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {items.map(p => {
          const flags = D.reactivationFlagCount(p);
          return (
            <button className="card card-pad" key={p.id} onClick={() => onPick(p)}
              style={{ textAlign: "left", cursor: "pointer", display: "block", width: "100%" }}>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 14 }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4, flexWrap: "wrap" }}>
                    <span className="tag code">{p.dept}</span>
                    <b style={{ fontSize: 14.5 }}>{p.name}</b>
                  </div>
                  <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginBottom: 7 }}>{p.vendor} · PPRO #{p.ppro}</div>
                  <div style={{ fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.5 }}>{p.discReason}</div>
                  <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 9, flexWrap: "wrap" }}>
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11.5, color: "var(--ink-3)" }}><Icon name="clock" size={12} /> Last active {p.lastActive}</span>
                    <span className="tag warn"><Icon name="flag" size={11} /> {flags} field{flags === 1 ? "" : "s"} to re-verify</span>
                    {p.accounts && p.accounts.length > 0 && <span className="pill sales" style={{ fontSize: 10.5 }}><Icon name="store" size={11} /> {p.accounts.length} waiting</span>}
                  </div>
                </div>
                <span className="btn btn-ghost btn-sm" style={{ pointerEvents: "none", whiteSpace: "nowrap" }}>Review to reactivate <Icon name="arrowRight" size={13} /></span>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

/* ---------- Reactivation review: confirm carried-over record, clear flagged fields ---------- */
function ReactivationView({ item, me, onBack, onReactivate, pushToast }) {
  const D = window.HUB_DATA;
  const p = item;
  const groups = D.reactivationFields(p);
  const flagged = groups.flatMap(g => g.fields).filter(f => f.flag);
  const totalFlags = flagged.length;

  const [resolved, setResolved] = useStateIntake({});   // key -> "confirmed" | "updated"
  const [editing, setEditing] = useStateIntake(null);
  const [vals, setVals] = useStateIntake(() => {
    const v = {}; groups.forEach(g => g.fields.forEach(f => { v[f.key] = f.value; })); return v;
  });

  const clearedCount = Object.keys(resolved).length;
  const pct = totalFlags ? Math.round((clearedCount / totalFlags) * 100) : 100;
  const allCleared = clearedCount >= totalFlags;

  const confirm = (f) => { setResolved(r => ({ ...r, [f.key]: "confirmed" })); setEditing(null); pushToast(f.label + " confirmed", "check"); };
  const saveEdit = (f) => { setResolved(r => ({ ...r, [f.key]: "updated" })); setEditing(null); pushToast(f.label + " updated", "check"); };

  const submit = () => {
    const updates = {};
    Object.keys(resolved).forEach(k => { if (resolved[k] === "updated") updates[k] = vals[k]; });
    onReactivate(p, updates);
  };

  const renderValue = (f) => f.code
    ? <span className="tag code" style={{ fontSize: 12 }}>{vals[f.key]}</span>
    : f.mono ? <span className="mono" style={{ fontSize: 13, fontWeight: 700 }}>{vals[f.key]}</span>
    : <span style={{ fontSize: 13.5, color: "var(--ink)", lineHeight: 1.5 }}>{vals[f.key]}</span>;

  return (
    <div className="page viewfade">
      <button className="btn btn-quiet btn-sm" onClick={onBack} style={{ marginBottom: 16 }}><Icon name="chevRight" size={14} style={{ transform: "rotate(180deg)" }} /> Back to dormant items</button>

      <div className="detail-head" style={{ marginBottom: 22 }}>
        <div className="dh-crumb"><b>{p.deptName}</b> · {p.cls} · Reactivation review</div>
        <h1>{p.name}</h1>
        <div className="dh-meta">
          <span className="tag code">{p.dept}</span><span>{p.vendor}</span><span>·</span>
          <span>PPRO #{p.ppro}</span><span>·</span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="clock" size={13} /> Last active {p.lastActive}</span>
        </div>
      </div>

      <div className="detail-grid">
        <div>
          <div className="alert-banner" style={{ marginBottom: 20 }}>
            <div className="ab-ico"><Icon name="flag" size={19} /></div>
            <div className="ab-body">
              <b>{totalFlags} field{totalFlags === 1 ? "" : "s"} flagged for re-verification</b>
              <p>{p.discReason} The full PPRO record is carried over below — confirm or update each flagged field, then send it to the New Item Team to go live again.</p>
            </div>
          </div>

          {groups.map(g => (
            <div className="card" key={g.group} style={{ marginBottom: 14 }}>
              <div className="fgroup-head" style={{ cursor: "default" }}>
                <div className="fg-title" style={{ paddingLeft: 2 }}>{g.group}</div>
                <span style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{g.note}</span>
              </div>
              <div style={{ padding: "6px 18px 14px" }}>
                {g.fields.map(f => {
                  const state = resolved[f.key];
                  const isFlag = !!f.flag && !state;
                  return (
                    <div key={f.key} style={{
                      borderTop: "1px solid var(--line)", padding: "12px 0",
                      borderLeft: isFlag ? "3px solid var(--mkt)" : "3px solid transparent",
                      paddingLeft: 12, marginLeft: -12,
                      background: isFlag ? "color-mix(in oklch, var(--mkt) 5%, transparent)" : "transparent",
                    }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 10, justifyContent: "space-between" }}>
                        <div style={{ minWidth: 0 }}>
                          <div className="micro" style={{ marginBottom: 3 }}>{f.label}</div>
                          {editing === f.key
                            ? <input className="inp" autoFocus value={vals[f.key]} onChange={e => setVals(v => ({ ...v, [f.key]: e.target.value }))} style={{ maxWidth: 320 }} />
                            : renderValue(f)}
                        </div>
                        <div style={{ flexShrink: 0 }}>
                          {state === "confirmed" && <span className="tag live"><Icon name="check" size={11} /> Confirmed</span>}
                          {state === "updated" && <span className="tag live"><Icon name="check" size={11} /> Updated</span>}
                          {!state && f.flag && (
                            editing === f.key
                              ? <button className="btn btn-dark btn-sm" onClick={() => saveEdit(f)}><Icon name="check" size={12} /> Save</button>
                              : <div style={{ display: "flex", gap: 6 }}>
                                  <button className="btn btn-quiet btn-sm" onClick={() => setEditing(f.key)}>Update</button>
                                  <button className="btn btn-dark btn-sm" onClick={() => confirm(f)}><Icon name="check" size={12} /> Confirm</button>
                                </div>
                          )}
                          {!state && !f.flag && <span style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 11.5, color: "var(--ink-4)" }}><Icon name="check" size={13} style={{ color: "var(--live)" }} /> carried over</span>}
                        </div>
                      </div>
                      {isFlag && <div style={{ fontSize: 12, color: "var(--mkt)", marginTop: 6, display: "flex", gap: 6, alignItems: "flex-start" }}><Icon name="flag" size={12} style={{ marginTop: 2, flexShrink: 0 }} /> {f.flag}</div>}
                    </div>
                  );
                })}
              </div>
            </div>
          ))}
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          <div className="card card-pad" style={{ display: "flex", flexDirection: "column", gap: 12, alignItems: "stretch" }}>
            <div className="eyebrow">Re-verification</div>
            <div style={{ alignSelf: "center" }}><Ring pct={pct} size={64} /></div>
            <div style={{ fontSize: 12.5, color: "var(--ink-3)", textAlign: "center" }}>{clearedCount} of {totalFlags} flagged fields cleared</div>
            <button className="btn btn-primary btn-lg" style={{ justifyContent: "center" }} disabled={!allCleared} onClick={submit}>
              <Icon name="arrowRight" size={16} /> Reactivate & send to New Item Team
            </button>
            {!allCleared && <div style={{ fontSize: 11.5, color: "var(--ink-3)", textAlign: "center" }}>Confirm or update every flagged field to continue</div>}
          </div>

          <div className="card card-pad">
            <div className="sec-head" style={{ margin: "0 0 6px" }}>
              <h2 style={{ fontSize: 15 }}>Why it's coming back</h2>
              <span className="pill sales" style={{ fontSize: 10.5 }}><Icon name="store" size={11} /> Demand</span>
            </div>
            {p.accounts && p.accounts.length > 0 ? (
              <div className="sales-strip">
                {p.accounts.map((a, i) => (
                  <div className="acct-row" key={i}>
                    <div className="ar-logo">{a.logo}</div>
                    <div className="ar-main"><div className="ar-name">{a.name}</div><div className="ar-meta">{a.meta}</div></div>
                    <div className="ar-vol"><b className="tnum">{a.vol}</b><span>{a.unit}</span></div>
                  </div>
                ))}
              </div>
            ) : <div style={{ fontSize: 12.5, color: "var(--ink-3)" }}>No account demand attached yet.</div>}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { IntakeView, ReviewView, GuidedField, AIDraftPanel, ReactivatePicker, ReactivationView });
