/* Platform Admin — shared data scaffold + formatters.
   ALL data is loaded from Supabase via window.loadAdminData() in supabase-client.jsx.
   These globals are initialized as empty so the UI shows skeleton/empty states until data arrives. */

window.ADMIN_MAKERS       = [];
window.ADMIN_APPROVALS    = [];
window.ADMIN_APPLICATIONS = [];  // maker onboarding queue (admin_list_maker_applications)
window.ADMIN_ORDERS       = [];
window.ADMIN_CUSTOMERS    = [];
window.ADMIN_PIECES       = [];
window.ADMIN_TEAM         = [];
window.ADMIN_AUDIT        = [];
window.ADMIN_WORKSHOPS    = [];
window.ADMIN_CONTENT      = [];
window.ADMIN_FINANCE      = { ytdGmv: 0, ytdFees: 0, ytdPayouts: 0, ytdReturns: 0, returnRate: 0, monthly: [], payouts: [] };
window.ADMIN_STATS        = {
  gmv: 0, gmvDelta: "0",
  makers: 0, makersDelta: 0, applicants: 0,
  piecesLive: 0, piecesDraft: 0,
  customers: 0, customerDelta: 0,
  pendingApprovals: 0, highApprovals: 0, todayApprovals: 0,
};

// ——— Helpers ———
// NOTE: fmtDate / fmtDateTime are the locale-aware 3-arg versions defined in
// i18n.jsx (iso, lang, opts). We deliberately do NOT redefine fmtDate here —
// an earlier single-arg duplicate (en-GB only) was shadowing the localized
// version and breaking Arabic dates (GL-1).

// ——— Locale-aware number formatting (OV-5) ———
// In Arabic, KPI/money/count numbers must render with Arabic-Indic digits
// (ar-EG); in English, grouped Western digits (en-US). Never mix Western digits
// beside Arabic-Indic in an AR view.
//   adminNum(n, lang)        → grouped integer  (e.g. "1,240" / "١٬٢٤٠")
//   adminThousandsK(n, lang) → compact "k" with localized digits (e.g. "120k" / "١٢٠ ألف")
window.adminNum = function (n, lang) {
  const v = Number(n);
  if (!isFinite(v)) return lang === "ar" ? "٠" : "0";
  return v.toLocaleString(lang === "ar" ? "ar-EG" : "en-US");
};
// Compact thousands. EN keeps the familiar "120k"; AR uses localized digits +
// the Arabic thousands word "ألف" so no Western "k" sits beside Arabic numerals.
window.adminThousandsK = function (n, lang, digits = 0) {
  const k = Number(n) / 1000;
  if (!isFinite(k)) return lang === "ar" ? "٠" : "0";
  const num = k.toLocaleString(lang === "ar" ? "ar-EG" : "en-US", {
    minimumFractionDigits: digits, maximumFractionDigits: digits,
  });
  return lang === "ar" ? `${num} ألف` : `${num}k`;
};

window.AdminPill = function AdminPill({ children, tone = "muted" }) {
  const colors = {
    olive:      { bg: "rgba(123,132,99,0.14)",  fg: "var(--olive)" },
    terracotta: { bg: "rgba(194,99,66,0.12)",   fg: "var(--terracotta-dk)" },
    gold:       { bg: "rgba(202,167,108,0.18)", fg: "#7d6635" },
    ink:        { bg: "rgba(28,26,21,0.85)",    fg: "var(--paper)" },
    muted:      { bg: "var(--paper-2)",         fg: "var(--muted)" },
  };
  const c = colors[tone] || colors.muted;
  return (
    <span style={{
      display: "inline-block", padding: "3px 10px", borderRadius: 999,
      background: c.bg, color: c.fg,
      fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.2em",
      textTransform: "uppercase", fontWeight: 500, whiteSpace: "nowrap",
    }}>{children}</span>
  );
};

window.PriorityDot = function PriorityDot({ p }) {
  const c = p === "high" ? "#c26342" : p === "normal" ? "#caa76c" : "#9c9686";
  return <span style={{ display: "inline-block", width: 8, height: 8, borderRadius: "50%", background: c, flexShrink: 0 }} />;
};

window.AdminTypeIcon = function AdminTypeIcon({ type, size = 32 }) {
  const meta = window.AP_TYPE_LABEL[type] || { iconName: "star", tone: "muted" };
  const colors = {
    olive: "#7b8463", terracotta: "#c26342", gold: "#caa76c", muted: "#9c9686",
  };
  return (
    <div style={{
      width: size, height: size, borderRadius: "50%",
      background: (colors[meta.tone] || "#9c9686") + "22",
      color: colors[meta.tone] || "#9c9686",
      display: "grid", placeItems: "center", flexShrink: 0,
    }}>
      <Icon name={meta.iconName || "star"} size={Math.round(size * 0.5)} />
    </div>
  );
};

// ——— Labels & formatting helpers ———
// iconName maps to the hand-drawn folk Icon set in primitives.jsx.
window.AP_TYPE_LABEL = {
  "piece.create":    { en: "New piece",        ar: "قطعة جديدة",         iconName: "box",      tone: "olive" },
  "piece.photos":    { en: "Photo update",     ar: "تحديث الصور",        iconName: "eye",      tone: "gold" },
  "price.change":    { en: "Price change",     ar: "تغيير السعر",         iconName: "wax",      tone: "terracotta" },
  "stock.update":    { en: "Stock update",     ar: "تحديث المخزون",       iconName: "basket",   tone: "olive" },
  "profile.edit":    { en: "Profile edit",     ar: "تعديل الملف",         iconName: "feather",  tone: "gold" },
  "workshop.create": { en: "New workshop",     ar: "ورشة جديدة",         iconName: "scissors", tone: "olive" },
  "payout.request":  { en: "Payout request",   ar: "طلب صرف",           iconName: "gift",     tone: "terracotta" },
  "maker.apply":     { en: "Maker application", ar: "طلب انضمام صانع",    iconName: "hand",     tone: "terracotta" },
};

// ——— Maker-application status labels (onboarding review queue) ———
// maker_applications.status enum: received | shortlisted | accepted | rejected.
// Open/pending = received | shortlisted; rendered as a bilingual AdminPill.
window.APPLICATION_STATUS_LABEL = {
  received:    { en: "Received",    ar: "مُستلَم",   tone: "gold" },
  shortlisted: { en: "Shortlisted", ar: "مرشَّح",    tone: "olive" },
  accepted:    { en: "Accepted",    ar: "مقبول",     tone: "olive" },
  rejected:    { en: "Rejected",    ar: "مرفوض",     tone: "terracotta" },
};
window.applicationStatusLabel = function (status, lang) {
  if (!status) return "—";
  const m = window.APPLICATION_STATUS_LABEL[String(status).toLowerCase()];
  return m ? (m[lang] || m.en) : String(status).replace(/[_.]+/g, " ").trim();
};
window.applicationStatusTone = function (status) {
  const m = window.APPLICATION_STATUS_LABEL[String(status || "").toLowerCase()];
  return m ? m.tone : "muted";
};
// Open applications = those still awaiting a decision (badge + empty-state logic).
window.isOpenApplication = function (a) {
  const s = String(a && a.status || "").toLowerCase();
  return s === "received" || s === "shortlisted";
};

// ——— Audit-event action labels (AU-1 / F3) ———
// audit_log.action is a raw enum (e.g. "approval_approved", "order_created").
// Map known events to a friendly bilingual phrase; unknown tokens are humanised
// (underscores/dots → spaces) so no raw machine key ever reaches the user.
window.AUDIT_ACTION_LABEL = {
  approval_approved:   { en: "approved a request",        ar: "وافق على طلب" },
  approval_rejected:   { en: "rejected a request",        ar: "رفض طلبًا" },
  approval_changes_requested: { en: "requested changes",  ar: "طلب تعديلات" },
  approval_decided:    { en: "reviewed a request",        ar: "راجع طلبًا" },
  order_created:       { en: "placed an order",           ar: "أنشأ طلبًا" },
  order_placed:        { en: "placed an order",           ar: "أنشأ طلبًا" },
  order_confirmed:     { en: "confirmed an order",        ar: "أكّد طلبًا" },
  order_status_changed:{ en: "changed an order status",   ar: "غيّر حالة طلب" },
  order_note_added:    { en: "added an order note",       ar: "أضاف ملاحظة على طلب" },
  order_item_maker_status: { en: "updated a maker status", ar: "حدّث حالة صانع" },
  order_item_maker_status_changed: { en: "updated a maker status", ar: "حدّث حالة صانع" },
  payout_created:      { en: "created a payout",           ar: "أنشأ صرفية" },
  payout_paid:         { en: "marked a payout paid",      ar: "صرف دفعة" },
  payout_requested:    { en: "requested a payout",        ar: "طلب صرفية" },
  maker_suspended:     { en: "suspended a maker",         ar: "علّق صانعًا" },
  maker_reactivated:   { en: "reactivated a maker",       ar: "أعاد تفعيل صانع" },
  maker_published:     { en: "published a maker",         ar: "نشر صانعًا" },
  product_published:   { en: "published a piece",         ar: "نشر قطعة" },
  product_unpublished: { en: "unpublished a piece",       ar: "أخفى قطعة" },
  product_created:     { en: "created a piece",            ar: "أنشأ قطعة" },
  role_changed:        { en: "changed a team role",       ar: "غيّر دورًا" },
  login:               { en: "signed in",                 ar: "سجّل الدخول" },
  user_login:          { en: "signed in",                 ar: "سجّل الدخول" },
  return_decided:      { en: "decided a return",          ar: "بتّ في إرجاع" },
  return_requested:    { en: "requested a return",        ar: "طلب إرجاعًا" },
  return_approved:     { en: "approved a return",         ar: "وافق على إرجاع" },
  return_received:     { en: "received a return",         ar: "استلم إرجاعًا" },
  return_refunded:     { en: "refunded a return",         ar: "ردّ مبلغ إرجاع" },
  review_submitted:    { en: "submitted a review",        ar: "أضاف تقييمًا" },
  approval_sla_breached: { en: "an approval SLA was breached", ar: "تجاوُز مهلة موافقة" },
  qc_decided:          { en: "decided a QC review",       ar: "بتّ في فحص جودة" },
  qc_opened:           { en: "opened a QC review",        ar: "فتح فحص جودة" },
  shipment_upserted:   { en: "updated a shipment",        ar: "حدّث شحنة" },
  workshop_status_changed: { en: "changed a workshop status", ar: "غيّر حالة ورشة" },
};
window.auditActionLabel = function (action, lang) {
  if (!action) return "—";
  // audit_log.action uses dot notation (e.g. "maker.reactivated"); the map keys
  // are underscore-normalised, so collapse both separators before lookup.
  const key = String(action).toLowerCase().replace(/[.]+/g, "_");
  const m = window.AUDIT_ACTION_LABEL[key];
  if (m) return m[lang] || m.en;
  // Friendly fallback — humanise the raw token, never show dots/underscores.
  return String(action).replace(/[_.]+/g, " ").trim();
};

// ——— Craft category labels (F11) ———
// Maker/piece "trade" comes through as a category name_en (or slug). Render the
// bilingual category name; proper names / cities are DATA and stay untouched.
window.CATEGORY_LABEL = {
  macrame:   { en: "Macramé",  ar: "مكرمية" },
  candles:   { en: "Candles",  ar: "شموع" },
  candle:    { en: "Candles",  ar: "شموع" },
  resin:     { en: "Resin",    ar: "راتنج" },
  ceramics:  { en: "Ceramics", ar: "فخار" },
  ceramic:   { en: "Ceramics", ar: "فخار" },
  pottery:   { en: "Ceramics", ar: "فخار" },
};
window.categoryLabel = function (value, lang) {
  if (!value) return "—";
  // Strip Latin diacritics so "Macramé" matches the "macrame" key (Arabic
  // combining marks live in a different block, so they're untouched).
  const key = String(value).toLowerCase().trim()
    .normalize("NFD").replace(/[̀-ͯ]/g, "");
  const m = window.CATEGORY_LABEL[key];
  return m ? (m[lang] || m.en) : value;
};

// ——— Notification template labels (F5) ———
// notification rows carry a raw template_key (e.g. "order_confirmed_customer").
// Map known keys to a friendly bilingual phrase; unknown keys are humanised so
// no raw machine token surfaces.
window.NOTIF_TEMPLATE_LABEL = {
  order_confirmed_customer:  { en: "Order confirmed",      ar: "تأكيد الطلب" },
  order_placed_customer:     { en: "Order received",       ar: "استلام الطلب" },
  order_shipped_customer:    { en: "Order shipped",        ar: "شحن الطلب" },
  order_delivered_customer:  { en: "Order delivered",      ar: "تسليم الطلب" },
  order_cancelled_customer:  { en: "Order cancelled",      ar: "إلغاء الطلب" },
  refund_processed_customer: { en: "Refund processed",     ar: "تمّ الاسترداد" },
  maker_new_order:           { en: "New order for maker",  ar: "طلب جديد للصانع" },
  maker_status_changed:      { en: "Maker status updated",  ar: "تحديث حالة الصانع" },
  return_approved_customer:  { en: "Return approved",      ar: "قبول الإرجاع" },
  return_rejected_customer:  { en: "Return rejected",      ar: "رفض الإرجاع" },
};
window.notifTemplateLabel = function (key, lang) {
  if (!key) return "—";
  const m = window.NOTIF_TEMPLATE_LABEL[String(key).toLowerCase()];
  if (m) return m[lang] || m.en;
  return String(key).replace(/[_.]+/g, " ").trim();
};
window.NOTIF_CHANNEL_LABEL = {
  email:    { en: "Email",    ar: "بريد" },
  whatsapp: { en: "WhatsApp", ar: "واتساب" },
  sms:      { en: "SMS",      ar: "رسالة" },
  push:     { en: "Push",     ar: "إشعار" },
  in_app:   { en: "In-app",   ar: "داخل التطبيق" },
};
window.notifChannelLabel = function (ch, lang) {
  if (!ch) return "—";
  const m = window.NOTIF_CHANNEL_LABEL[String(ch).toLowerCase()];
  return m ? (m[lang] || m.en) : String(ch).replace(/[_.]+/g, " ").trim();
};

// ——— Approval display title (F5) ———
// A real human title is preferred; when the only title is the raw kind enum
// (e.g. "piece.create"), fall back to the friendly bilingual type label.
window.approvalTitle = function (approval, lang) {
  if (!approval) return "";
  const t = approval.title;
  const kindMeta = window.AP_TYPE_LABEL[approval.type];
  // If title is missing or is just the raw kind token, use the type label.
  if (!t || t === approval.type) {
    return kindMeta ? (kindMeta[lang] || kindMeta.en) : String(approval.type || "").replace(/[_.]+/g, " ");
  }
  return t;
};
