/* ───────────────────────────────────────────────────────────────
   NutriDMS Staff Portal — Ingredient Verification queue & console.
   Internal team (dietitian / compliance / manager / admin / super-admin)
   works the tickets customers submit: assign, advance the 10-stage
   pipeline, request more info, respond in-thread, approve/reject, and
   publish the verified ingredient to the Master Library.
   Reads/writes the same localStorage store the customer module uses.
   Exports window.IngredientVerifStaff (a React screen component).
   ─────────────────────────────────────────────────────────────── */
(function () {
  const { useState, useEffect } = React;
  const Ic = (n, s, st) => React.createElement(window.Icon, { name: n, size: s || 16, stroke: st || 2 });
  const TICKET_KEY = "nutridms_ing_verify_tickets_v1";
  const STAGES = ["Submitted", "Received", "Assigned", "Research", "Nutrition Analysis", "Ingredient Mapping", "Compliance Review", "QA Review", "Approved", "Published"];

  function load() { try { return JSON.parse(localStorage.getItem(TICKET_KEY) || "[]"); } catch (e) { return []; } }
  function save(list) { try { localStorage.setItem(TICKET_KEY, JSON.stringify(list)); } catch (e) {} try { window.dispatchEvent(new CustomEvent("nutridms-verify-tickets")); } catch (e) {} }
  function upd(id, fn) { const list = load(); const i = list.findIndex(t => t.id === id); if (i < 0) return; list[i] = fn({ ...list[i] }); save(list); }
  function slaRemaining(t) { const ms = (t.slaDueAt || 0) - Date.now(); if (ms <= 0) return { text: "SLA elapsed", over: true }; const h = Math.floor(ms / 3600e3), m = Math.floor((ms % 3600e3) / 60000); return { text: h + "h " + m + "m", over: false }; }
  function statusTone(s) { if (["Approved", "Published", "Completed"].includes(s)) return "ok"; if (["Rejected", "Cancelled"].includes(s)) return "block"; if (["Submitted", "Received"].includes(s)) return "info"; return "warn"; }

  function IngredientVerifStaff() {
    const app = (window.useApp ? window.useApp() : {}) || {};
    const role = app.role || window.__role;
    const toast = app.toast || (() => {});
    const me = (typeof currentUser === "function") ? currentUser(role) : { name: "Staff" };
    const [tick, setTick] = useState(0);
    const [filter, setFilter] = useState("all");
    const [openId, setOpenId] = useState(null);
    const [reply, setReply] = useState("");
    useEffect(() => { const b = () => setTick(t => t + 1); window.addEventListener("nutridms-verify-tickets", b); return () => window.removeEventListener("nutridms-verify-tickets", b); }, []);

    const list = load();
    const open = openId && list.find(t => t.id === openId);
    const isOverdue = (t) => (t.slaDueAt || 0) < Date.now() && !["Published", "Completed", "Rejected", "Cancelled"].includes(t.status);
    const counts = {
      all: list.length,
      new: list.filter(t => ["Submitted", "Received"].includes(t.status)).length,
      urgent: list.filter(t => t.priority !== "Normal" && !["Published", "Completed", "Rejected"].includes(t.status)).length,
      research: list.filter(t => ["Research", "Nutrition Analysis", "Ingredient Mapping"].includes(t.status)).length,
      qa: list.filter(t => ["Compliance Review", "QA Review"].includes(t.status)).length,
      completed: list.filter(t => ["Published", "Completed"].includes(t.status)).length,
      overdue: list.filter(isOverdue).length,
    };
    const pass = (t) => {
      if (filter === "all") return true;
      if (filter === "new") return ["Submitted", "Received"].includes(t.status);
      if (filter === "urgent") return t.priority !== "Normal" && !["Published", "Completed", "Rejected"].includes(t.status);
      if (filter === "research") return ["Research", "Nutrition Analysis", "Ingredient Mapping"].includes(t.status);
      if (filter === "qa") return ["Compliance Review", "QA Review"].includes(t.status);
      if (filter === "completed") return ["Published", "Completed"].includes(t.status);
      if (filter === "overdue") return isOverdue(t);
      return true;
    };
    const rows = list.filter(pass);

    // ── staff actions ──
    const pushEvent = (t, stage, note) => { t.timeline = [...(t.timeline || []), { stage, at: Date.now(), owner: me.name, note }]; return t; };
    const advance = (t) => {
      const idx = Math.min((t.stageIdx || 0) + 1, STAGES.length - 1);
      upd(t.id, (x) => { x.stageIdx = idx; x.status = STAGES[idx]; pushEvent(x, STAGES[idx], "Advanced by " + me.name + "."); return x; });
      audit("Advanced " + t.number + " → " + STAGES[idx]); toast("Moved to " + STAGES[idx]);
    };
    const assign = (t, who) => { upd(t.id, (x) => { x.assignedTo = who; if (x.stageIdx < 2) { x.stageIdx = 2; x.status = "Assigned"; } pushEvent(x, "Assigned", "Assigned to " + who + "."); return x; }); audit("Assigned " + t.number + " to " + who); toast("Assigned to " + who); };
    const requestInfo = (t) => { upd(t.id, (x) => { x.status = "Waiting for Customer"; x.thread = [...(x.thread || []), { from: "nutridms", who: me.name, at: Date.now(), text: "We need more information to proceed. Please add any spec sheets or clarify the intended use." }]; return x; }); audit("Requested info on " + t.number); toast("Requested more information"); };
    const respond = (t) => { if (!reply.trim()) return; upd(t.id, (x) => { x.thread = [...(x.thread || []), { from: "nutridms", who: me.name, at: Date.now(), text: reply.trim() }]; return x; }); setReply(""); toast("Reply sent"); };
    const approve = (t) => { upd(t.id, (x) => { x.stageIdx = 8; x.status = "Approved"; pushEvent(x, "Approved", "Clinically reviewed & compliance-approved by " + me.name + "."); return x; }); audit("Approved " + t.number); toast("Approved"); };
    const reject = (t) => { upd(t.id, (x) => { x.status = "Rejected"; pushEvent(x, "Rejected", "Rejected by " + me.name + "."); return x; }); audit("Rejected " + t.number); toast("Rejected"); };
    const publish = (t) => {
      upd(t.id, (x) => { x.stageIdx = 9; x.status = "Published"; pushEvent(x, "Published", "Added to the Master Ingredient Library by " + me.name + "."); x.thread = [...(x.thread || []), { from: "nutridms", who: me.name, at: Date.now(), text: "Verified and added to your Master Ingredient Library. You can import it with one click." }]; return x; });
      // Add to master library if the API is present
      try { if (window.MasterIngredients && window.MasterIngredients.addVerified) window.MasterIngredients.addVerified({ name: t.ingredientName, category: (t.form && t.form.category) || "Other", source: "NutriDMS Verified" }); } catch (e) {}
      audit("Published " + t.number + " to Master Library"); toast("Published to Master Library");
    };
    function audit(action) { try { if (typeof auditPush === "function") auditPush({ who: me.name, action, target: "Verification", severity: "medium" }); } catch (e) {} }

    const REVIEWERS = (typeof USERS !== "undefined" ? USERS : (window.USERS || [])).filter(u => ["dietitian", "compliance", "manager"].includes(u.role));

    return React.createElement("div", null,
      window.Crumbs && React.createElement(window.Crumbs, { path: [{ label: "Verification Queue" }] }),
      React.createElement("div", { className: "page-head" },
        React.createElement("div", null,
          React.createElement("h1", { className: "page-title" }, "Ingredient Verification Queue"),
          React.createElement("p", { className: "page-sub" }, "Clinical research requests from Enterprise customers, routed to the NutriDMS Dietitian & Compliance team."))),

      // stat filters
      React.createElement("div", { className: "ivs-filters" },
        [["all", "All", "inbox"], ["new", "New", "sparkle"], ["urgent", "Urgent", "flag"], ["research", "Research", "flask-conical"], ["qa", "QA & Compliance", "shield-check"], ["overdue", "Overdue", "alarm-clock"], ["completed", "Completed", "check-circle-2"]].map(([id, label, icon]) =>
          React.createElement("button", { key: id, className: "ivs-filter" + (filter === id ? " on" : "") + (id === "overdue" && counts.overdue ? " danger" : ""), onClick: () => setFilter(id) },
            Ic(icon, 15, 2.2), React.createElement("span", null, label), React.createElement("b", null, counts[id] || 0)))),

      rows.length === 0
        ? React.createElement("div", { className: "ivs-empty" }, Ic("inbox", 28, 1.6), React.createElement("strong", null, "No requests in this view"), React.createElement("span", null, "Enterprise verification requests appear here as customers submit them."))
        : React.createElement("div", { className: "ivs-grid" },
          rows.map(t => {
            const sla = slaRemaining(t); const od = isOverdue(t);
            return React.createElement("button", { key: t.id, className: "ivs-card" + (od ? " overdue" : ""), onClick: () => setOpenId(t.id) },
              React.createElement("div", { className: "ivs-card-top" },
                React.createElement("span", { className: "ivs-num" }, t.number),
                React.createElement("span", { className: "iv-badge " + statusTone(t.status) }, t.status)),
              React.createElement("div", { className: "ivs-name" }, t.ingredientName),
              React.createElement("div", { className: "ivs-meta" },
                React.createElement("span", null, Ic("building-2", 12, 2.2), t.org || "Org"),
                React.createElement("span", { className: t.priority !== "Normal" ? "urg" : "" }, Ic("flag", 12, 2.2), t.priority),
                React.createElement("span", { className: od ? "over" : "" }, Ic("clock", 12, 2.2), sla.text)),
              React.createElement("div", { className: "ivs-assignee" }, t.assignedTo ? ("Assigned: " + t.assignedTo) : "Unassigned"));
          })),

      open && React.createElement(StaffDrawer, {
        t: open, me, reviewers: REVIEWERS, reply, setReply,
        onClose: () => setOpenId(null),
        actions: { advance, assign, requestInfo, respond, approve, reject, publish },
      }));
  }

  function StaffDrawer({ t, me, reviewers, reply, setReply, onClose, actions }) {
    const sla = slaRemaining(t);
    const canApprove = ["compliance", "manager", "admin", "super-admin"].includes(window.__role);
    return React.createElement("div", { className: "iv-scrim", onClick: (e) => e.target === e.currentTarget && onClose() },
      React.createElement("div", { className: "ivs-drawer" },
        React.createElement("div", { className: "iv-head" },
          React.createElement("div", { className: "iv-head-badge" }, Ic("microscope", 18, 2.2)),
          React.createElement("div", { className: "iv-head-t" },
            React.createElement("div", { className: "iv-head-title" }, t.number),
            React.createElement("div", { className: "iv-head-sub" }, t.ingredientName + " · " + (t.org || "Org"))),
          React.createElement("button", { className: "iv-x", onClick: onClose }, Ic("x", 18, 2.4))),

        React.createElement("div", { className: "ivs-drawer-body" },
          // action bar
          React.createElement("div", { className: "ivs-actions" },
            React.createElement("select", { className: "iv-input ivs-assign", value: t.assignedTo || "", onChange: e => e.target.value && actions.assign(t, e.target.value) },
              React.createElement("option", { value: "" }, "Assign to…"),
              reviewers.map(u => React.createElement("option", { key: u.initials, value: u.name }, u.name))),
            !["Published", "Completed", "Rejected"].includes(t.status) && React.createElement("button", { className: "iv-btn ghost sm", onClick: () => actions.advance(t) }, Ic("chevrons-right", 13, 2.4), "Advance stage"),
            !["Published", "Completed", "Rejected"].includes(t.status) && React.createElement("button", { className: "iv-btn ghost sm", onClick: () => actions.requestInfo(t) }, Ic("message-circle-question", 13, 2.2), "Request info"),
            canApprove && t.status !== "Approved" && t.status !== "Published" && React.createElement("button", { className: "iv-btn ghost sm", onClick: () => actions.approve(t) }, Ic("check", 13, 2.6), "Approve"),
            canApprove && t.status === "Approved" && React.createElement("button", { className: "iv-btn primary sm", onClick: () => actions.publish(t) }, Ic("globe", 13, 2.2), "Publish to library"),
            canApprove && !["Rejected", "Published"].includes(t.status) && React.createElement("button", { className: "iv-btn danger sm", onClick: () => actions.reject(t) }, Ic("x-circle", 13, 2.2), "Reject")),

          React.createElement("div", { className: "ivs-cols" },
            // left: timeline + request
            React.createElement("div", { className: "ivs-col-main" },
              React.createElement("div", { className: "iv-sec-h" }, Ic("git-commit", 15, 2.2), "Pipeline"),
              React.createElement("div", { className: "iv-timeline" },
                STAGES.map((s, i) => {
                  const done = i <= (t.stageIdx || 0); const cur = i === (t.stageIdx || 0);
                  const ev = (t.timeline || []).slice().reverse().find(x => x.stage === s);
                  return React.createElement("div", { key: s, className: "iv-tl" + (done ? " done" : "") + (cur ? " cur" : "") },
                    React.createElement("span", { className: "iv-tl-dot" }, done && Ic("check", 11, 3)),
                    React.createElement("div", { className: "iv-tl-body" },
                      React.createElement("div", { className: "iv-tl-stage" }, s),
                      ev && React.createElement("div", { className: "iv-tl-note" }, ev.note),
                      ev && React.createElement("div", { className: "iv-tl-when" }, new Date(ev.at).toLocaleString() + " · " + ev.owner)));
                })),
              t.form && React.createElement("div", { className: "ivs-req" },
                React.createElement("div", { className: "iv-sec-h" }, Ic("file-text", 15, 2.2), "Request detail"),
                reqRow("Scientific name", t.form.scientificName),
                reqRow("Manufacturer", t.form.manufacturer),
                reqRow("Origin", t.form.origin),
                reqRow("Category", t.form.category),
                reqRow("Processing", t.form.processing),
                t.form.research && t.form.research.length > 0 && React.createElement("div", { className: "ivs-tags" }, React.createElement("em", null, "Research"), t.form.research.map(r => React.createElement("span", { key: r, className: "iv-side-tag" }, r))),
                t.form.compliance && t.form.compliance.length > 0 && React.createElement("div", { className: "ivs-tags" }, React.createElement("em", null, "Compliance"), t.form.compliance.map(r => React.createElement("span", { key: r, className: "iv-side-tag" }, r))),
                t.form.justification && React.createElement("p", { className: "ivs-just" }, t.form.justification))),

            // right: side + thread
            React.createElement("div", { className: "ivs-col-side" },
              React.createElement("div", { className: "iv-side-card" },
                sideRow("Status", React.createElement("span", { className: "iv-badge " + statusTone(t.status) }, t.status)),
                sideRow("Priority", t.priority),
                sideRow("SLA", React.createElement("b", { className: sla.over ? "over" : "" }, sla.text)),
                sideRow("Requested by", t.requestedBy),
                sideRow("Assigned", t.assignedTo || "Unassigned")),
              React.createElement("div", { className: "iv-thread" },
                React.createElement("div", { className: "iv-side-h" }, "Conversation"),
                (t.thread || []).map((m, i) => React.createElement("div", { key: i, className: "iv-msg " + m.from },
                  React.createElement("div", { className: "iv-msg-who" }, m.who),
                  React.createElement("div", { className: "iv-msg-tx" }, m.text))),
                React.createElement("div", { className: "ivs-reply" },
                  React.createElement("textarea", { className: "iv-input iv-textarea", value: reply, placeholder: "Reply to the customer…", onChange: e => setReply(e.target.value) }),
                  React.createElement("button", { className: "iv-btn primary sm", onClick: () => actions.respond(t) }, Ic("send", 13, 2.4), "Send reply"))))))));
  }
  function reqRow(k, v) { return v ? React.createElement("div", { className: "ivs-reqrow" }, React.createElement("em", null, k), React.createElement("b", null, v)) : null; }
  function sideRow(k, v) { return React.createElement("div", { className: "iv-side-row" }, React.createElement("em", null, k), typeof v === "string" ? React.createElement("b", null, v) : v); }

  window.IngredientVerifStaff = IngredientVerifStaff;
})();
