/* Task 3 & 4 — Orders table + detail drawer */
const { useState: useStateOrd, useMemo: useMemoOrd } = React;

/* generic filter dropdown */
function FilterDropdown({ icon, label, value, options, onChange, allLabel }) {
  const [open, setOpen] = useStateOrd(false);
  const cur = options.find((o) => o.v === value);
  const isSet = value && value !== "all";
  return React.createElement("div", { className: "co-filter" },
    React.createElement("button", { className: "co-filter-btn" + (isSet ? " set" : ""), onClick: () => setOpen(!open) },
      icon && React.createElement(window.Icon, { name: icon }),
      isSet ? (cur ? cur.label : value) : label,
      React.createElement(window.Icon, { name: "chevdown", size: 14 })),
    React.createElement(window.Popover, { open, onClose: () => setOpen(false), style: { top: 46, left: 0, minWidth: 190, maxHeight: 320, overflowY: "auto" } },
      React.createElement("button", { className: "co-pop-item", onClick: () => { onChange("all"); setOpen(false); } }, allLabel || "All",
        !isSet && React.createElement("span", { className: "co-pop-check" }, React.createElement(window.Icon, { name: "check", size: 16 }))),
      options.map((o) => React.createElement("button", { key: o.v, className: "co-pop-item", onClick: () => { onChange(o.v); setOpen(false); } },
        o.label, value === o.v && React.createElement("span", { className: "co-pop-check" }, React.createElement(window.Icon, { name: "check", size: 16 }))))));
}

function daysClass(d) { return d >= 6 ? "bad" : (d >= 4 ? "warn" : ""); }

function etherscanChip(tx) {
  if (!tx) return null;
  return React.createElement("a", { href: tx.url, target: "_blank", rel: "noreferrer", className: "co-etherscan", title: "View USDC payment on Etherscan · " + tx.hash },
    React.createElement(window.Icon, { name: "etherscan" }), "USDC", React.createElement(window.Icon, { name: "external", size: 11 }));
}
function feeCell(state, amount, tx) {
  return React.createElement("span", { style: { display: "inline-flex", alignItems: "center", gap: 8, justifyContent: "flex-end" } },
    React.createElement(window.Fee, { state, amount }), etherscanChip(tx));
}

function chMaskName(n) { const p = n.trim().split(/\s+/); return p.length < 2 ? n : p[0][0] + ". " + p[p.length - 1]; }
function chMaskEmail(e) { const a = e.split("@"); return (a[0] || "")[0] + "•••@" + (a[1] || ""); }
function chMaskPhone(p) { const head = p.split(" ")[0] || ""; return head + " ••• ••• " + p.replace(/\s/g, "").slice(-2); }
function chMaskLine(line) { const m = line.match(/\d+/); return "•••• " + (m ? m[0] : "") + " ··········"; }

function OrdersTable({ rows, sort, setSort, selectedId, onRowClick }) {
  const cols = [
    { k: "ref", label: "Order ref" },
    { k: "holder", label: "Cardholder" },
    { k: "product", label: "Product" },
    { k: "deliver", label: "Delivery" },
    { k: "status", label: "Status" },
    { k: "country", label: "Country" },
    { k: "yearly", label: "Yearly fee" },
    { k: "shipping", label: "Shipping" },
    { k: "created", label: "Created", noSort: true },
    { k: "days", label: "Days in state" },
  ];
  const th = (c) => React.createElement("th", {
    key: c.k, className: (c.noSort ? "no-sort" : "") + (sort.k === c.k ? " sorted" : ""),
    onClick: c.noSort ? undefined : () => setSort({ k: c.k, dir: sort.k === c.k && sort.dir === "asc" ? "desc" : "asc" }),
  }, c.label, !c.noSort && React.createElement("span", { className: "sort-ar" }, sort.k === c.k ? (sort.dir === "asc" ? "↑" : "↓") : "↕"));

  return React.createElement("div", { className: "co-table-wrap" },
    React.createElement("table", { className: "co-table" },
      React.createElement("thead", null, React.createElement("tr", null, cols.map(th))),
      React.createElement("tbody", null,
        rows.map((o) => React.createElement("tr", { key: o.id, className: selectedId === o.id ? "selected" : "", onClick: () => onRowClick(o) },
          React.createElement("td", { className: "co-cell-mono" }, o.ref),
          React.createElement("td", { className: "co-cell-strong" }, o.holder),
          React.createElement("td", null, React.createElement(window.Tag, { product: o.product })),
          React.createElement("td", { className: "co-cell-muted" }, o.deliver ? "Ship physical" : "Vault"),
          React.createElement("td", null, React.createElement(window.StatusPill, { status: o.status })),
          React.createElement("td", { className: "co-cell-muted" }, window.CardOps.flag(o.country), " ", o.country),
          React.createElement("td", null, React.createElement(window.Fee, { state: o.yearly, amount: o.yearlyAmt })),
          React.createElement("td", null, React.createElement(window.Fee, { state: o.shipping, amount: o.shipAmt })),
          React.createElement("td", { className: "co-cell-muted" }, o.created.replace(/ · .*/, "")),
          React.createElement("td", { className: "co-days " + daysClass(o.days) }, o.days, "d"))))));
}

function Orders({ globalProduct, setProduct, globalCountry, setCountry, role, selectedOrder, onOpenOrder, onCloseOrder, onStartActivation, initialFilter, onAction, loading }) {
  const [status, setStatus] = useStateOrd(initialFilter && initialFilter.status ? initialFilter.status : "all");
  const [type, setType] = useStateOrd("all");
  const [payment, setPayment] = useStateOrd("all");
  const [range, setRange] = useStateOrd("all");
  const [excOnly, setExcOnly] = useStateOrd(false);
  const [sort, setSort] = useStateOrd({ k: "days", dir: "desc" });

  React.useEffect(() => { if (initialFilter && initialFilter.status) setStatus(initialFilter.status); }, [initialFilter]);

  const statusOpts = Object.keys(window.CardOps.STATUS).map((k) => ({ v: k, label: window.CardOps.STATUS[k].label }));
  const rows = useMemoOrd(() => {
    let r = window.CardOps.ORDERS.slice();
    if (globalProduct !== "All") r = r.filter((o) => o.product === globalProduct);
    if (globalCountry !== "all") r = r.filter((o) => o.country === globalCountry);
    if (status !== "all") r = r.filter((o) => o.status === status);
    if (type !== "all") r = r.filter((o) => type === "ship" ? o.deliver : !o.deliver);
    if (payment !== "all") r = r.filter((o) => payment === "unpaid" ? (o.yearly === "unpaid" || o.shipping === "unpaid") : (o.yearly === "paid" && o.shipping !== "unpaid"));
    if (excOnly) r = r.filter((o) => window.CardOps.exceptionStatuses.includes(o.status));
    const dir = sort.dir === "asc" ? 1 : -1;
    r.sort((a, b) => {
      let x = a[sort.k], y = b[sort.k];
      if (typeof x === "number") return (x - y) * dir;
      return String(x).localeCompare(String(y)) * dir;
    });
    return r;
  }, [globalProduct, globalCountry, status, type, payment, range, excOnly, sort]);

  const clearAll = () => { setStatus("all"); setType("all"); setPayment("all"); setRange("all"); setExcOnly(false); };
  const anyFilter = status !== "all" || type !== "all" || payment !== "all" || range !== "all" || excOnly || globalProduct !== "All" || globalCountry !== "all";

  return React.createElement("div", { className: "co-page" },
    React.createElement("div", { className: "co-page-head" },
      React.createElement("div", null,
        React.createElement("h1", { className: "co-page-title" }, "All Cards"),
        React.createElement("p", { className: "co-page-sub" }, rows.length, " orders", anyFilter ? " · filtered" : "")),
      React.createElement(window.GatedButton, { perm: "start_activation", role, variant: "primary", icon: "activate", onClick: () => onStartActivation(null) }, "New activation")),

    React.createElement("div", { className: "co-filterbar" },
      React.createElement(FilterDropdown, { icon: "filter", label: "Product", value: globalProduct === "All" ? "all" : globalProduct, options: [{ v: "THORWallet", label: "THORWallet" }, { v: "MINE", label: "MINE" }], onChange: (v) => setProduct(v === "all" ? "All" : v), allLabel: "All products" }),
      React.createElement(FilterDropdown, { label: "Status", value: status, options: statusOpts, onChange: setStatus, allLabel: "Any status" }),
      React.createElement(FilterDropdown, { icon: "map", label: "Country", value: globalCountry, options: Object.keys(window.CardOps.COUNTRIES).map((c) => ({ v: c, label: window.CardOps.flag(c) + " " + window.CardOps.COUNTRIES[c] })), onChange: setCountry, allLabel: "All countries" }),
      React.createElement(FilterDropdown, { label: "Delivery", value: type, options: [{ v: "ship", label: "Ship physical" }, { v: "vault", label: "Vault physical" }], onChange: setType, allLabel: "Any delivery" }),
      React.createElement(FilterDropdown, { icon: "euro", label: "Payment", value: payment, options: [{ v: "paid", label: "Fully paid" }, { v: "unpaid", label: "Has unpaid fee" }], onChange: setPayment, allLabel: "Any payment" }),
      React.createElement(FilterDropdown, { icon: "calendar", label: "Date", value: range, options: [{ v: "1d", label: "Today" }, { v: "7d", label: "Last 7 days" }, { v: "30d", label: "Last 30 days" }], onChange: setRange, allLabel: "Any date" }),
      React.createElement("button", { className: "co-toggle-chip" + (excOnly ? " on" : ""), onClick: () => setExcOnly(!excOnly) },
        React.createElement(window.Icon, { name: "alert", size: 15 }), "Exceptions only"),
      anyFilter && React.createElement("button", { className: "co-btn co-btn-ghost co-btn-sm", onClick: clearAll, style: { marginLeft: "auto" } },
        React.createElement(window.Icon, { name: "x", size: 14 }), "Clear")),

    loading
      ? React.createElement("div", { className: "co-table-wrap" }, React.createElement(window.SkeletonRows, { rows: 8, cols: 10 }))
      : rows.length === 0
        ? React.createElement("div", { className: "co-card" }, React.createElement(window.EmptyState, { icon: "search", title: "No orders match", sub: "Try widening your filters or clearing them.", action: React.createElement(window.Button, { size: "sm", onClick: clearAll }, "Clear filters") }))
        : React.createElement(OrdersTable, { rows, sort, setSort, selectedId: selectedOrder && selectedOrder.id, onRowClick: onOpenOrder }),

    selectedOrder && React.createElement(window.OrderDrawer, { order: selectedOrder, role, onClose: onCloseOrder, onStartActivation, onAction }));
}

/* ── Order detail drawer (Task 4) ────────────────────────── */
function dotTone(title) {
  const t = title.toLowerCase();
  if (t.includes("fail") || t.includes("block") || t.includes("overdue") || t.includes("undeliver")) return "red";
  if (t.includes("activat") || t.includes("paid") || t.includes("verified") || t.includes("live")) return "green";
  if (t.includes("ship") || t.includes("started") || t.includes("reminder")) return "blue";
  if (t.includes("lost") || t.includes("return") || t.includes("renewal") || t.includes("dispos")) return "amber";
  return "";
}

function OrderDrawer({ order, role, onClose, onStartActivation, onAction }) {
  const o = order;
  const [revealed, setRevealed] = useStateOrd(false);
  const [editing, setEditing] = useStateOrd(false);
  const [draft, setDraft] = useStateOrd({});
  React.useEffect(() => { setRevealed(false); setEditing(false); }, [order && order.id]);
  const exc = window.CardOps.exceptionStatuses.includes(o.status);
  const canActivate = ["fee_paid", "activating"].includes(o.status);
  const canShip = o.status === "activated" && o.deliver;
  const blocked = o.status === "blocked";
  const owesPayment = o.yearly === "unpaid" || o.shipping === "unpaid" || o.status === "payment_overdue";
  const startEdit = () => { setDraft({ name: o.holderFull, email: o.email, phone: o.phone, line: o.address ? o.address.full.line : "", zip: o.address ? o.address.full.zip : "", city: o.address ? o.address.full.city : "" }); setRevealed(true); setEditing(true); };
  const saveEdit = () => {
    o.holderFull = draft.name.trim(); o.holder = chMaskName(o.holderFull);
    o.email = draft.email.trim(); o.emailMasked = chMaskEmail(o.email);
    o.phone = draft.phone.trim(); o.phoneMasked = chMaskPhone(o.phone);
    if (o.address) {
      o.address.full.line = draft.line.trim(); o.address.full.zip = draft.zip.trim(); o.address.full.city = draft.city.trim();
      o.address.masked.line = chMaskLine(o.address.full.line); o.address.masked.zip = "•••" + o.address.full.zip.slice(-1);
    }
    o.timeline = o.timeline.concat([{ title: "Cardholder details updated", who: (window.CardOps.USERS.find((u) => u.role === role) || {}).name || "you", source: null, time: "Jun 22 · now" }]);
    setEditing(false); onAction("details_saved", o);
  };
  const chField = (label, key, mono) => React.createElement("div", { className: "co-field" },
    React.createElement("label", null, label),
    React.createElement("input", { className: "co-input" + (mono ? " mono" : ""), value: draft[key] || "", onChange: (e) => setDraft(Object.assign({}, draft, { [key]: e.target.value })) }));
  return React.createElement(window.Drawer, { onClose },
    React.createElement("div", { className: "co-drawer-head" },
      React.createElement("div", null,
        React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 9, marginBottom: 6 } },
          React.createElement(window.Tag, { product: o.product }),
          React.createElement(window.StatusPill, { status: o.status })),
        React.createElement("div", { style: { fontSize: 19, fontWeight: 700, letterSpacing: "-0.01em" } }, o.holder),
        React.createElement("div", { style: { fontSize: 12.5, color: "var(--co-text-3)", fontFamily: "var(--co-mono)", marginTop: 2 } },
          o.ref, o.last4 ? "  ·  •••• " + o.last4 : "")),
      React.createElement("button", { className: "co-icon-btn", onClick: onClose }, React.createElement(window.Icon, { name: "x" }))),

    React.createElement("div", { className: "co-drawer-body" },
      exc && React.createElement("div", { className: "co-banner " + (window.CardOps.EXC_TYPES[o.status].sev === "critical" ? "red" : "amber"), style: { marginBottom: 18 } },
        React.createElement(window.Icon, { name: "alert" }),
        React.createElement("div", null, React.createElement("b", null, window.CardOps.EXC_TYPES[o.status].label), " — ", o.days, " days in this state.")),

      React.createElement("div", { className: "co-section-title" }, "Card status"),
      React.createElement("div", { style: { display: "flex", flexWrap: "wrap", gap: 7, marginBottom: 22 } },
        window.CardOps.cardTags(o).map((tg, i) => React.createElement("span", { key: i, className: "co-pill " + tg.tone },
          React.createElement("span", { className: "dot" }), tg.label))),

      React.createElement("div", { className: "co-section-title" }, "Plan & payment"),
      React.createElement(window.DL, { items: [
        ["Product", React.createElement("span", { style: { display: "inline-flex", alignItems: "center", gap: 6 } }, React.createElement(window.Tag, { product: o.product }), o.plan === "premium" ? "Premium" : o.plan)],
        ["Plan", "Premium · virtual + physical"],
        ["Physical delivery", o.deliver ? "Ship to cardholder" : "Vaulted (not ordered)"],
        ["Settlement", o.pay.currency === "USDC" ? "USDC (on-chain)" : "EUR (SEPA)"],
        ["Yearly fee", feeCell(o.yearly, o.yearlyAmt, o.pay.yearlyTx)],
        ["Shipping fee", feeCell(o.shipping, o.shipAmt, o.pay.shipTx)],
        ["Country", window.CardOps.flag(o.country) + " " + window.CardOps.COUNTRIES[o.country]],
      ] }),

      React.createElement("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 22, marginBottom: 12 } },
        React.createElement("div", { className: "co-section-title", style: { margin: 0 } }, "Cardholder · contact", o.address ? " & shipping" : ""),
        editing
          ? React.createElement("div", { style: { display: "flex", gap: 8 } },
              React.createElement(window.Button, { variant: "ghost", size: "sm", onClick: () => setEditing(false) }, "Cancel"),
              React.createElement(window.Button, { variant: "primary", size: "sm", icon: "check", onClick: saveEdit }, "Save"))
          : React.createElement("div", { style: { display: "flex", gap: 8 } },
              React.createElement("button", { className: "co-btn co-btn-ghost co-btn-sm", onClick: () => setRevealed(!revealed) },
                React.createElement(window.Icon, { name: revealed ? "eyeoff" : "eye", size: 15 }), revealed ? "Hide" : "Reveal"),
              React.createElement(window.GatedButton, { perm: "edit_cardholder", role, variant: "secondary", size: "sm", icon: "note", onClick: startEdit }, "Edit"))),
      editing
        ? React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 12 } },
            chField("Name", "name"),
            chField("Email", "email", true),
            chField("Phone", "phone", true),
            o.address && React.createElement("div", { style: { display: "grid", gridTemplateColumns: "2fr 1fr", gap: 12 } }, chField("Address", "line"), chField("Postcode", "zip")),
            o.address && chField("City", "city"))
        : React.createElement(React.Fragment, null,
            React.createElement(window.DL, { items: [
              ["Name", revealed ? o.holderFull : o.holder],
              ["Email", React.createElement("span", { style: { fontFamily: "var(--co-mono)", fontSize: 12.5 } }, revealed ? o.email : o.emailMasked)],
              ["Phone", React.createElement("span", { style: { fontFamily: "var(--co-mono)", fontSize: 12.5 } }, revealed ? o.phone : o.phoneMasked)],
            ] }),
            o.address && React.createElement("div", { className: "co-card", style: { padding: "14px 16px", marginTop: 12, background: "var(--co-surface-2)", display: "flex", gap: 12, alignItems: "flex-start" } },
              React.createElement(window.Icon, { name: "map", size: 18, style: { color: "var(--co-text-3)", marginTop: 2 } }),
              React.createElement("div", { style: { fontSize: 13, lineHeight: 1.6, fontFamily: "var(--co-mono)" } },
                revealed ? o.holderFull : o.holder, React.createElement("br"),
                (revealed ? o.address.full : o.address.masked).line, React.createElement("br"),
                (revealed ? o.address.full : o.address.masked).zip, " ", o.address.full.city, ", ", o.address.full.cc))),
      React.createElement("div", { className: "co-help", style: { marginTop: 8, display: "flex", alignItems: "center", gap: 6 } },
        React.createElement(window.Icon, { name: "lock", size: 12 }),
        editing ? "Every change to name, contact, or address is recorded in the audit log."
          : (revealed ? "Personal data unmasked — this view is recorded in the audit log." : "Personal data is masked by default. Revealing it is logged.")),

      React.createElement("div", { className: "co-section-title", style: { marginTop: 22 } }, "Event timeline"),
      React.createElement("div", { className: "co-timeline" },
        o.timeline.slice().reverse().map((e, i) => React.createElement("div", { className: "co-tl-item", key: i },
          React.createElement("div", { className: "co-tl-dot " + dotTone(e.title) }),
          React.createElement("div", { className: "co-tl-title" }, e.title),
          React.createElement("div", { className: "co-tl-meta" },
            e.time, " · ", e.who ? React.createElement("b", null, e.who) : React.createElement("b", null, e.source || "System"),
            e.who && e.source ? "" : (e.who ? "" : " (system)"))))),

      React.createElement("div", { className: "co-section-title", style: { marginTop: 22 } }, "Notes"),
      React.createElement("textarea", { className: "co-input", placeholder: "Add an internal note…", style: { height: 70, padding: 12, resize: "vertical", fontFamily: "inherit" }, disabled: !window.CardOps.can(role, "add_note") })),

    React.createElement("div", { className: "co-drawer-foot" },
      canActivate
        ? React.createElement(window.GatedButton, { perm: "start_activation", role, variant: "primary", icon: "activate", onClick: () => onStartActivation(o) }, o.status === "activating" ? "Resume activation" : "Start activation")
        : canShip
          ? React.createElement(window.GatedButton, { perm: "mark_shipped", role, variant: "primary", icon: "truck", onClick: () => onAction("ship", o) }, "Mark shipped")
          : owesPayment
            ? React.createElement(window.GatedButton, { perm: "send_reminder", role, variant: "primary", icon: "send", onClick: () => onAction("remind", o) }, "Send reminder")
            : null,
      blocked
        ? React.createElement(window.GatedButton, { perm: "block", role, variant: "primary", size: "sm", icon: "shieldcheck", onClick: () => onAction("unblock", o) }, "Unblock card")
        : React.createElement(window.GatedButton, { perm: "block", role, variant: "danger", size: "sm", icon: "ban", onClick: () => onAction("block", o) }, "Block card"),
      React.createElement(window.GatedButton, { perm: "start_activation", role, variant: "secondary", size: "sm", icon: "card", onClick: () => onAction("assign_new", o) }, "Assign new card"),
      React.createElement(window.GatedButton, { perm: "reissue", role, variant: "ghost", size: "sm", icon: "rotate", onClick: () => onAction("lost", o) }, "Report lost"),
      React.createElement(window.GatedButton, { perm: "send_reminder", role, variant: "ghost", size: "sm", icon: "send", onClick: () => onAction("remind", o) }, "Reminder")));
}

Object.assign(window, { Orders, OrderDrawer, FilterDropdown });
