/* ============================================================
   AfricaMart Admin — Accounts (Buyers, Suppliers, Verification)
   Full control: verify, suspend, ban, edit, view-as, message,
   adjust tier, flag, delete.
   ============================================================ */
const STATUS_BADGE = {
  active: "success", suspended: "warning", pending: "info", banned: "danger",
  live: "success", flagged: "danger", review: "info", approved: "success",
  completed: "success", "in transit": "info", processing: "info", "pending payment": "warning",
  cancelled: "neutral", disputed: "danger", open: "warning", investigating: "info", resolved: "success",
};

/* ---------- Account control actions (shared by buyers + suppliers) ---------- */
function accountActions({ acct, kind, setStatus, toast, confirm, message, edit }) {
  const isActive = acct.status === "active";
  const isBanned = acct.status === "banned";
  const list = [];
  if (acct.status === "pending") list.push({ label: "Approve account", icon: "user-check", variant: "success", run: () => { setStatus(acct.id, "active"); toast(acct.name + " approved & activated"); } });
  if (!acct.verified && acct.status !== "banned") list.push({ label: "Verify", icon: "badge-check", variant: "primary", run: () => { setStatus(acct.id, acct.status, { verified: true }); toast(acct.name + " marked verified"); } });
  list.push({ label: "Message", icon: "message-square", variant: "muted", run: () => message(acct) });
  list.push({ label: "View as " + kind, icon: "eye", variant: "muted", run: () => toast("Opening " + acct.name + " session (view-as)") });
  list.push({ label: "Edit details", icon: "edit", variant: "muted", run: () => edit(acct) });
  if (isActive) list.push({ label: "Suspend", icon: "pause", variant: "muted", run: () => confirm({ title: "Suspend " + acct.name + "?", body: "The account will be temporarily blocked from transacting. Open orders are paused. You can reactivate any time.", confirmLabel: "Suspend", icon: "pause", run: () => { setStatus(acct.id, "suspended"); toast(acct.name + " suspended", true); } }) });
  if (acct.status === "suspended") list.push({ label: "Reactivate", icon: "play", variant: "success", run: () => { setStatus(acct.id, "active"); toast(acct.name + " reactivated"); } });
  if (!isBanned) list.push({ label: "Ban account", icon: "ban", variant: "danger", run: () => confirm({ danger: true, title: "Ban " + acct.name + "?", body: "This permanently deactivates the account and cancels all open orders. This is a serious action — use for fraud or repeated violations.", confirmLabel: "Ban permanently", icon: "ban", run: () => { setStatus(acct.id, "banned"); toast(acct.name + " banned", true); } }) });
  return list;
}

/* ---------- Buyers ---------- */
function BuyersModule(props) {
  return React.createElement(AccountsTable, { ...props, kind: "buyer" });
}
function SuppliersModule(props) {
  return React.createElement(AccountsTable, { ...props, kind: "supplier" });
}

function AccountsTable({ kind, accounts, setStatus, toast, confirm, search }) {
  const { Card, DataTable, Badge, Btn, SectionHeader, TabBar } = window.ModernTilesDesignSystem_50dd07;
  const [sel, setSel] = aUseState(null);
  const [filter, setFilter] = aUseState("All");
  const [editing, setEditing] = aUseState(null);
  const [messaging, setMessaging] = aUseState(null);
  const isBuyer = kind === "buyer";

  let rows = accounts.filter(a => {
    const q = (search || "").toLowerCase();
    const hay = (a.name + " " + (a.contact || "") + " " + (a.email || "") + " " + (a.country || "")).toLowerCase();
    return !q || hay.includes(q);
  });
  if (filter === "Pending") rows = rows.filter(a => a.status === "pending");
  else if (filter === "Suspended") rows = rows.filter(a => a.status === "suspended" || a.status === "banned");
  else if (filter === "Unverified") rows = rows.filter(a => !a.verified);
  else if (filter === "High risk") rows = rows.filter(a => a.risk === "high");

  const money = window.ADM.money;
  const cols = isBuyer ? [
    { key: "name", label: "Buyer", render: (_, r) => React.createElement(NameCell, { name: r.name, sub: r.contact, code: r.country, verified: r.verified }) },
    { key: "tier", label: "Tier", render: v => React.createElement(Badge, { status: "neutral", label: v }) },
    { key: "orders", label: "Orders", align: "right", mono: true, nowrap: true },
    { key: "gmv", label: "GMV", align: "right", mono: true, nowrap: true, render: v => money(v, true) },
    { key: "risk", label: "Risk", render: v => React.createElement(RiskPill, { level: v }) },
    { key: "status", label: "Status", render: v => React.createElement(Badge, { status: STATUS_BADGE[v], label: v }) },
    { key: "_a", label: "", align: "right", render: (_, r) => React.createElement(Btn, { variant: "ghost", size: "sm", onClick: e => { e.stopPropagation(); setSel(r); } }, "Manage") },
  ] : [
    { key: "name", label: "Supplier", render: (_, r) => React.createElement(NameCell, { name: r.name, sub: r.type, code: r.country, verified: r.verified }) },
    { key: "tier", label: "Plan", render: v => React.createElement(Badge, { status: v === "premium" ? "info" : v === "verified" ? "success" : "neutral", label: v }) },
    { key: "_orders", label: "Orders", align: "right", mono: true, nowrap: true, render: (_, r) => (window.ADM.SUPPLIER_ADMIN[r.id] || {}).orders ?? "—" },
    { key: "_gmv", label: "GMV", align: "right", mono: true, nowrap: true, render: (_, r) => { const a = window.ADM.SUPPLIER_ADMIN[r.id]; return a ? money(a.gmv, true) : "—"; } },
    { key: "_risk", label: "Risk", render: (_, r) => React.createElement(RiskPill, { level: (window.ADM.SUPPLIER_ADMIN[r.id] || {}).risk || "low" }) },
    { key: "status", label: "Status", render: (_, r) => { const st = (window.ADM.SUPPLIER_ADMIN[r.id] || {}).status || "active"; return React.createElement(Badge, { status: STATUS_BADGE[st], label: st }); } },
    { key: "_a", label: "", align: "right", render: (_, r) => React.createElement(Btn, { variant: "ghost", size: "sm", onClick: e => { e.stopPropagation(); setSel(r); } }, "Manage") },
  ];

  const counts = {
    total: accounts.length,
    pending: accounts.filter(a => a.status === "pending").length,
    suspended: accounts.filter(a => a.status === "suspended" || a.status === "banned").length,
  };

  return React.createElement("div", null,
    React.createElement(SectionHeader, { title: isBuyer ? "Buyers" : "Suppliers", subtitle: counts.total + " accounts · " + counts.pending + " pending · " + counts.suspended + " restricted" },
      React.createElement(Btn, { variant: "muted", size: "md", onClick: () => toast("Account export queued") }, React.createElement(AdmIcon, { name: "download", size: 14 }), "Export"),
      React.createElement(Btn, { variant: "primary", size: "md", onClick: () => toast("Invite link copied") }, React.createElement(AdmIcon, { name: "plus", size: 14 }), "Invite " + kind)),
    React.createElement(TabBar, { tabs: ["All", "Pending", "Unverified", "High risk", "Suspended"], active: filter, onChange: setFilter }),
    React.createElement(Card, null, React.createElement(DataTable, { columns: cols, rows, onRowClick: setSel, selectedId: sel && sel.id })),
    rows.length === 0 && React.createElement("div", { style: { textAlign: "center", padding: "40px 0", color: "#A09288", fontSize: 13 } }, "No accounts match this filter."),

    React.createElement(AccountDrawer, { acct: sel, kind, onClose: () => setSel(null), setStatus, toast,
      confirm: cfg => confirm({ ...cfg, onConfirm: cfg.run }),
      message: a => setMessaging(a), edit: a => setEditing(a) }),
    React.createElement(MessageModal, { acct: messaging, onClose: () => setMessaging(null), toast }),
    React.createElement(EditModal, { acct: editing, onClose: () => setEditing(null), toast }));
}

function NameCell({ name, sub, code, verified }) {
  return React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 10 } },
    React.createElement(Avatar, { name, size: 32, color: "#2A4E62" }),
    React.createElement("div", { style: { minWidth: 0 } },
      React.createElement("div", { style: { fontSize: 13, fontWeight: 600, color: "#1A1614", display: "flex", alignItems: "center", gap: 5 } },
        React.createElement("span", { style: { whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", maxWidth: 200 } }, name),
        verified && React.createElement(AdmIcon, { name: "badge-check", size: 13, color: "#1750A0" })),
      React.createElement("div", { style: { fontSize: 11.5, color: "#857870", display: "flex", alignItems: "center", gap: 5 } },
        React.createElement(AdmFlag, { code, size: 13 }), sub)));
}

/* ---------- Account detail drawer ---------- */
function AccountDrawer({ acct, kind, onClose, setStatus, toast, confirm, message, edit }) {
  const { Btn, Badge, StatRow } = window.ModernTilesDesignSystem_50dd07;
  if (!acct) return null;
  const isBuyer = kind === "buyer";
  const sa = !isBuyer ? (window.ADM.SUPPLIER_ADMIN[acct.id] || {}) : null;
  const status = isBuyer ? acct.status : (sa.status || "active");
  const risk = isBuyer ? acct.risk : (sa.risk || "low");
  const money = window.ADM.money;
  const acctForActions = isBuyer ? acct : { ...acct, status, verified: acct.verified };
  const actions = accountActions({ acct: acctForActions, kind, setStatus, toast, confirm, message, edit });

  return React.createElement(Drawer, { open: !!acct, onClose, width: 480 },
    // Header
    React.createElement("div", { style: { padding: "20px 22px", borderBottom: "1px solid #F0EBE5", display: "flex", gap: 14, alignItems: "flex-start" } },
      React.createElement(Avatar, { name: acct.name, size: 48, color: acct.color || "#2A4E62" }),
      React.createElement("div", { style: { flex: 1, minWidth: 0 } },
        React.createElement("div", { style: { fontFamily: "'Outfit',sans-serif", fontSize: 18, fontWeight: 600, color: "#1A1614", display: "flex", alignItems: "center", gap: 6 } }, acct.name,
          acct.verified && React.createElement(AdmIcon, { name: "badge-check", size: 15, color: "#1750A0" })),
        React.createElement("div", { style: { fontSize: 12.5, color: "#857870", marginTop: 2, display: "flex", alignItems: "center", gap: 6 } },
          React.createElement(AdmFlag, { code: acct.country, size: 13 }),
          window.AM.countryByCode[acct.country].name, " · ", isBuyer ? acct.contact : acct.type),
        React.createElement("div", { style: { display: "flex", gap: 7, marginTop: 9 } },
          React.createElement(Badge, { status: STATUS_BADGE[status], label: status }),
          React.createElement(RiskPill, { level: risk }))),
      React.createElement("button", { onClick: onClose, style: { background: "none", border: "none", cursor: "pointer", padding: 4 } }, React.createElement(AdmIcon, { name: "x", size: 18, color: "#857870" }))),

    // Body
    React.createElement("div", { style: { flex: 1, overflowY: "auto", padding: "18px 22px" } },
      React.createElement("div", { style: { fontSize: 11, fontWeight: 700, color: "#A09288", letterSpacing: ".08em", textTransform: "uppercase", marginBottom: 8 } }, "Account"),
      React.createElement("div", { style: { background: "#FDFCFA", border: "1px solid #F0EBE5", borderRadius: 10, padding: "4px 14px", marginBottom: 18 } },
        React.createElement(StatRow, { label: isBuyer ? "Email" : "Phone", value: isBuyer ? acct.email : (acct.phone || "—"), mono: true }),
        React.createElement(StatRow, { label: "Joined", value: isBuyer ? acct.since : (sa.joined || acct.since) }),
        React.createElement(StatRow, { label: "Plan", value: acct.tier }),
        React.createElement(StatRow, { label: "KYC", value: isBuyer ? (acct.verified ? "Verified" : "Incomplete") : (sa.kyc || "verified") }),
        React.createElement(StatRow, { label: "Active", value: isBuyer ? acct.lastActive : "Recently" })),

      React.createElement("div", { style: { fontSize: 11, fontWeight: 700, color: "#A09288", letterSpacing: ".08em", textTransform: "uppercase", marginBottom: 8 } }, "Performance"),
      React.createElement("div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 18 } },
        React.createElement(DrawerStat, { label: "Lifetime GMV", value: money(isBuyer ? acct.gmv : sa.gmv, true) }),
        React.createElement(DrawerStat, { label: "Orders", value: isBuyer ? acct.orders : (sa.orders || 0) }),
        React.createElement(DrawerStat, { label: isBuyer ? "Open RFQs" : "Listings", value: isBuyer ? acct.openRfqs : (acct.products || 0) }),
        React.createElement(DrawerStat, { label: isBuyer ? "Disputes" : "Flags", value: isBuyer ? acct.disputes : (sa.flags || 0), warn: (isBuyer ? acct.disputes : sa.flags) > 0 })),

      !isBuyer && sa.payoutHold && React.createElement("div", { style: { background: "#FEF3E2", border: "1px solid #FCE6D7", borderRadius: 10, padding: "10px 14px", marginBottom: 18, display: "flex", gap: 9, alignItems: "center" } },
        React.createElement(AdmIcon, { name: "alert-triangle", size: 16, color: "#A05C08" }),
        React.createElement("div", { style: { fontSize: 12.5, color: "#A05C08" } }, "Payouts on hold pending KYC completion.")),

      React.createElement("div", { style: { fontSize: 11, fontWeight: 700, color: "#A09288", letterSpacing: ".08em", textTransform: "uppercase", marginBottom: 8 } }, "Recent orders"),
      React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 6 } },
        window.ADM.ORDERS.filter(o => isBuyer ? o.buyer === acct.id : o.supplier === acct.id).slice(0, 4).map(o =>
          React.createElement("div", { key: o.id, style: { display: "flex", alignItems: "center", gap: 10, padding: "8px 12px", background: "#FDFCFA", border: "1px solid #F0EBE5", borderRadius: 8 } },
            React.createElement("span", { style: { fontFamily: "'JetBrains Mono',monospace", fontSize: 11.5, color: "#6B6158" } }, o.id),
            React.createElement("span", { style: { flex: 1, fontSize: 12, color: "#2A2420", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" } }, o.product),
            React.createElement("span", { style: { fontFamily: "'JetBrains Mono',monospace", fontSize: 11.5, fontWeight: 600 } }, money(o.value, true)),
            React.createElement(Badge, { status: STATUS_BADGE[o.status], label: o.status }))),
        window.ADM.ORDERS.filter(o => isBuyer ? o.buyer === acct.id : o.supplier === acct.id).length === 0 &&
          React.createElement("div", { style: { fontSize: 12.5, color: "#A09288", padding: "6px 2px" } }, "No orders yet.")),

      // Tier control
      React.createElement("div", { style: { fontSize: 11, fontWeight: 700, color: "#A09288", letterSpacing: ".08em", textTransform: "uppercase", margin: "18px 0 8px" } }, "Adjust tier"),
      React.createElement("div", { style: { display: "flex", gap: 7, flexWrap: "wrap" } },
        (isBuyer ? ["Standard", "Growth", "Enterprise"] : ["free", "verified", "premium"]).map(t =>
          React.createElement("button", { key: t, onClick: () => { setStatus(acct.id, status, { tier: t }); toast(acct.name + " moved to " + t); },
            style: { padding: "6px 12px", borderRadius: 100, border: "1.5px solid " + (acct.tier === t ? "#1E3A4A" : "#E4DED6"), background: acct.tier === t ? "#1E3A4A" : "#fff", color: acct.tier === t ? "#fff" : "#524940", fontSize: 12, fontWeight: 600, cursor: "pointer", textTransform: "capitalize", fontFamily: "'Figtree',sans-serif" } }, t)))),

    // Footer actions
    React.createElement("div", { style: { borderTop: "1px solid #F0EBE5", padding: "14px 22px", display: "flex", gap: 8, flexWrap: "wrap" } },
      actions.map((a, i) => React.createElement(Btn, { key: i, variant: a.variant, size: "sm", onClick: a.run },
        React.createElement(AdmIcon, { name: a.icon, size: 14 }), a.label))));
}

function DrawerStat({ label, value, warn }) {
  return React.createElement("div", { style: { background: "#FDFCFA", border: "1px solid #F0EBE5", borderRadius: 10, padding: "12px 14px" } },
    React.createElement("div", { style: { fontFamily: "'Outfit',sans-serif", fontSize: 20, fontWeight: 700, color: warn ? "#B91C1C" : "#1A1614", lineHeight: 1 } }, value),
    React.createElement("div", { style: { fontSize: 11, color: "#857870", marginTop: 4 } }, label));
}

/* ---------- Message modal ---------- */
function MessageModal({ acct, onClose, toast }) {
  const { Btn } = window.ModernTilesDesignSystem_50dd07;
  const [text, setText] = aUseState("");
  if (!acct) return null;
  return React.createElement(ModalShell, { title: "Message " + acct.name, icon: "message-square", onClose },
    React.createElement("textarea", { value: text, onChange: e => setText(e.target.value), rows: 5, placeholder: "Write a message to the account owner…",
      style: { width: "100%", border: "1.5px solid #E4DED6", borderRadius: 8, padding: "10px 12px", fontSize: 13, fontFamily: "'Figtree',sans-serif", color: "#1A1614", resize: "vertical", outline: "none", boxSizing: "border-box" } }),
    React.createElement("div", { style: { display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 14 } },
      React.createElement(Btn, { variant: "muted", onClick: onClose }, "Cancel"),
      React.createElement(Btn, { variant: "primary", onClick: () => { onClose(); toast("Message sent to " + acct.name); } }, React.createElement(AdmIcon, { name: "send", size: 14 }), "Send")));
}

/* ---------- Edit modal ---------- */
function EditModal({ acct, onClose, toast }) {
  const { Btn } = window.ModernTilesDesignSystem_50dd07;
  if (!acct) return null;
  const field = (label, val) => React.createElement("div", { style: { marginBottom: 12 } },
    React.createElement("div", { style: { fontSize: 11, fontWeight: 600, color: "#857870", marginBottom: 5, textTransform: "uppercase", letterSpacing: ".04em" } }, label),
    React.createElement("input", { defaultValue: val, style: { width: "100%", border: "1.5px solid #E4DED6", borderRadius: 8, padding: "9px 12px", fontSize: 13, fontFamily: "'Figtree',sans-serif", color: "#1A1614", outline: "none", boxSizing: "border-box" } }));
  return React.createElement(ModalShell, { title: "Edit " + acct.name, icon: "edit", onClose },
    field("Account name", acct.name),
    field("Primary contact", acct.contact || acct.type || ""),
    field("Email", acct.email || ""),
    React.createElement("div", { style: { display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 6 } },
      React.createElement(Btn, { variant: "muted", onClick: onClose }, "Cancel"),
      React.createElement(Btn, { variant: "primary", onClick: () => { onClose(); toast("Account details saved"); } }, "Save changes")));
}

function ModalShell({ title, icon, onClose, children }) {
  return React.createElement("div", { style: { position: "fixed", inset: 0, zIndex: 185, display: "flex", alignItems: "center", justifyContent: "center", padding: 20 } },
    React.createElement("div", { onClick: onClose, style: { position: "absolute", inset: 0, background: "rgba(15,34,50,.48)" } }),
    React.createElement("div", { style: { position: "relative", background: "#fff", borderRadius: 14, width: "min(460px,100%)", boxShadow: "0 16px 48px rgba(26,22,20,.2)", overflow: "hidden", animation: "admPop .2s var(--ease-out,ease) both" } },
      React.createElement("div", { style: { padding: "18px 22px", borderBottom: "1px solid #F0EBE5", display: "flex", alignItems: "center", gap: 10 } },
        React.createElement("div", { style: { width: 32, height: 32, borderRadius: 8, background: "#F1F7FA", display: "flex", alignItems: "center", justifyContent: "center" } }, React.createElement(AdmIcon, { name: icon, size: 16, color: "#2A4E62" })),
        React.createElement("h3", { style: { fontFamily: "'Outfit',sans-serif", fontSize: 16, fontWeight: 600, color: "#1A1614" } }, title)),
      React.createElement("div", { style: { padding: "18px 22px" } }, children)));
}

Object.assign(window, { BuyersModule, SuppliersModule, AccountsTable, AccountDrawer, MessageModal, EditModal, ModalShell, NameCell, STATUS_BADGE, accountActions });
