/* Platform Admin — Approvals queue (core feature) */

// Bilingual priority labels (AP-1 / AP-2) — shared by the queue + drawer.
const PRIORITY_LABEL = {
  high:   { en: "High",   ar: "عاجل" },
  normal: { en: "Normal", ar: "عادي" },
  low:    { en: "Low",    ar: "منخفض" },
};
function _priorityLabel(p, lang) {
  const m = PRIORITY_LABEL[String(p || "").toLowerCase()];
  return m ? (m[lang] || m.en) : (p || "");
}

function ApprovalsPage({ lang, openApproval }) {
  const [filter, setFilter] = React.useState("all");
  const [typeFilter, setTypeFilter] = React.useState("all");
  const [sort, setSort] = React.useState("oldest");

  const all = window.ADMIN_APPROVALS;
  const filtered = all.filter(a => {
    if (filter === "high" && a.priority !== "high") return false;
    if (filter === "normal" && a.priority !== "normal") return false;
    if (filter === "low" && a.priority !== "low") return false;
    if (typeFilter !== "all" && a.type !== typeFilter) return false;
    return true;
  });

  const sorted = [...filtered].sort((a, b) => {
    if (sort === "oldest") return new Date(a.submitted) - new Date(b.submitted);
    if (sort === "newest") return new Date(b.submitted) - new Date(a.submitted);
    if (sort === "priority") {
      const rank = { high: 0, normal: 1, low: 2 };
      return rank[a.priority] - rank[b.priority];
    }
    return 0;
  });

  const counts = {
    all: all.length,
    high: all.filter(a => a.priority === "high").length,
    normal: all.filter(a => a.priority === "normal").length,
    low: all.filter(a => a.priority === "low").length,
  };

  const types = Object.keys(AP_TYPE_LABEL);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
      {/* Intro strip */}
      <div style={{
        padding: "20px 24px",
        background: "linear-gradient(100deg, var(--ink) 0%, #2a261f 100%)",
        color: "var(--paper)",
        borderRadius: 14,
        display: "flex", alignItems: "center", gap: 18, flexWrap: "wrap",
      }}>
        <div style={{ fontFamily: "var(--ff-display)", fontSize: 18, fontStyle: "italic", color: "var(--gold-soft)" }}>
          {lang === "en" ? "Every maker change lands here first." : "كلّ تغيير يمرّ من هنا أوّلًا."}
        </div>
        <div style={{ flex: 1, minWidth: 200, fontSize: 13, color: "rgba(244,237,226,0.75)" }}>
          {lang === "en"
            ? "Nothing goes live on the site until you approve it. Review the diff, approve, reject, or request changes."
            : "لا يُنشر شيء حتى توافق عليه. راجع التغيير وأقرّ أو ارفض أو اطلب تعديل."}
        </div>
        <div style={{ display: "flex", gap: 18 }}>
          <div>
            <div style={{ fontFamily: "var(--ff-display)", fontSize: 34, lineHeight: 1 }}>{counts.all}</div>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--gold-soft)" }}>{lang === "en" ? "pending" : "معلّق"}</div>
          </div>
          <div>
            <div style={{ fontFamily: "var(--ff-display)", fontSize: 34, lineHeight: 1, color: "#e8a890" }}>{counts.high}</div>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--gold-soft)" }}>{lang === "en" ? "high" : "عاجل"}</div>
          </div>
        </div>
      </div>

      {/* Filters */}
      <div style={{ display: "flex", gap: 14, flexWrap: "wrap", alignItems: "center" }}>
        <div style={{ display: "flex", gap: 6, padding: 4, background: "var(--paper-2)", borderRadius: 999 }}>
          {[
            { k: "all", l: lang === "en" ? "All" : "الكل", c: counts.all },
            { k: "high", l: lang === "en" ? "High" : "عاجل", c: counts.high },
            { k: "normal", l: lang === "en" ? "Normal" : "عادي", c: counts.normal },
            { k: "low", l: lang === "en" ? "Low" : "منخفض", c: counts.low },
          ].map(f => (
            <button key={f.k} onClick={() => setFilter(f.k)} style={{
              padding: "6px 14px", borderRadius: 999, border: 0,
              background: filter === f.k ? "var(--ink)" : "transparent",
              color: filter === f.k ? "var(--paper)" : "var(--ink)",
              fontSize: 12, fontFamily: "var(--ff-sans)", cursor: "pointer",
              display: "inline-flex", alignItems: "center", gap: 8,
            }}>
              {f.l}
              <span style={{ fontFamily: "var(--ff-mono)", fontSize: 9, opacity: 0.65 }}>{f.c}</span>
            </button>
          ))}
        </div>

        <select value={typeFilter} onChange={e => setTypeFilter(e.target.value)} style={{
          padding: "8px 14px", border: "1px solid var(--line-2)", borderRadius: 999, background: "var(--paper)",
          fontFamily: "var(--ff-sans)", fontSize: 12, cursor: "pointer", color: "var(--ink)",
        }}>
          <option value="all">{lang === "en" ? "All types" : "كل الأنواع"}</option>
          {types.map(t => <option key={t} value={t}>{AP_TYPE_LABEL[t][lang] || AP_TYPE_LABEL[t].en}</option>)}
        </select>

        <div style={{ flex: 1 }} />

        <select value={sort} onChange={e => setSort(e.target.value)} style={{
          padding: "8px 14px", border: "1px solid var(--line-2)", borderRadius: 999, background: "var(--paper)",
          fontFamily: "var(--ff-sans)", fontSize: 12, cursor: "pointer", color: "var(--ink)",
        }}>
          <option value="oldest">{lang === "en" ? "Oldest first" : "الأقدم أولًا"}</option>
          <option value="newest">{lang === "en" ? "Newest first" : "الأحدث أولًا"}</option>
          <option value="priority">{lang === "en" ? "By priority" : "بالأولويّة"}</option>
        </select>
      </div>

      {/* Table / list */}
      <div style={{ border: "1px solid var(--line-2)", borderRadius: 14, overflow: "hidden", background: "var(--paper)" }}>
        {/* Desktop header */}
        <div className="apr-row-h" style={{
          display: "grid",
          gridTemplateColumns: "44px 1.3fr 1fr 0.8fr 0.5fr 0.6fr 0.5fr",
          padding: "14px 22px", background: "var(--paper-2)",
          fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)",
        }}>
          <div></div>
          <div>{lang === "en" ? "Request" : "الطلب"}</div>
          <div>{lang === "en" ? "Maker" : "الصانع"}</div>
          <div>{lang === "en" ? "Type" : "النوع"}</div>
          <div>{lang === "en" ? "Pri." : "أولويّة"}</div>
          <div>{lang === "en" ? "Submitted" : "مقدَّم"}</div>
          <div></div>
        </div>

        {sorted.length === 0 && (
          <div style={{ padding: "60px 20px", textAlign: "center", color: "var(--muted)" }}>
            <div style={{ fontFamily: "var(--ff-display)", fontSize: 28, color: "var(--ink)" }}>{lang === "en" ? "Inbox zero." : "الصندوق فارغ."}</div>
            <div style={{ marginTop: 8, fontSize: 13 }}>{lang === "en" ? "No pending approvals for this filter." : "لا يوجد طلبات معلّقة."}</div>
          </div>
        )}

        {sorted.map((a, i) => {
          const type = AP_TYPE_LABEL[a.type] || { en: a.type, tone: "muted" };
          return (
            <button key={a.id} onClick={() => openApproval(a)} style={{
              width: "100%", textAlign: "left", border: 0, background: "transparent", cursor: "pointer",
              borderTop: i === 0 ? "none" : "1px solid var(--line-2)",
              padding: "16px 22px",
              display: "grid",
              gridTemplateColumns: "44px 1.3fr 1fr 0.8fr 0.5fr 0.6fr 0.5fr",
              gap: 14, alignItems: "center",
              transition: "background .15s",
            }}
            onMouseEnter={e => e.currentTarget.style.background = "var(--paper-2)"}
            onMouseLeave={e => e.currentTarget.style.background = "transparent"}
            className="apr-row">
              <AdminTypeIcon type={a.type} />
              <div style={{ minWidth: 0 }}>
                <div style={{ fontFamily: "var(--ff-display)", fontSize: 17, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{window.approvalTitle(a, lang)}</div>
                <div style={{ marginTop: 3, fontSize: 12, color: "var(--muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.summary}</div>
              </div>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 13, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.makerName}</div>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.2em", color: "var(--muted)" }}>{a.id}</div>
              </div>
              <AdminPill tone={type.tone}>{type[lang] || type.en}</AdminPill>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <PriorityDot p={a.priority} />
                <span style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)" }}>{_priorityLabel(a.priority, lang)}</span>
              </div>
              <div style={{ fontFamily: "var(--ff-mono)", fontSize: 11, color: "var(--muted)" }}>{window.fmtAge(a.age, lang)}</div>
              <span style={{ color: "var(--muted)", fontSize: 18, justifySelf: "end" }}>→</span>
            </button>
          );
        })}
      </div>

      <style>{`
        @media (max-width: 900px) {
          .apr-row-h { display: none !important; }
          .apr-row { grid-template-columns: 44px 1fr auto !important; grid-template-rows: auto auto; }
          .apr-row > :nth-child(3), .apr-row > :nth-child(4), .apr-row > :nth-child(5), .apr-row > :nth-child(6) { display: none; }
        }
      `}</style>
    </div>
  );
}

// ——— Approval detail drawer ———
function ApprovalDrawer({ approval, onClose, lang, onAction }) {
  const [note, setNote] = React.useState("");
  const [action, setAction] = React.useState(null); // null | 'approve' | 'reject' | 'changes'

  // ESC closes the drawer; body scroll is locked while it's open.
  React.useEffect(() => {
    if (!approval) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = prev;
      window.removeEventListener("keydown", onKey);
    };
  }, [approval, onClose]);

  if (!approval) return null;
  const type = AP_TYPE_LABEL[approval.type] || { en: approval.type, tone: "muted" };

  // AP-4 — a note is REQUIRED when rejecting or requesting changes.
  const noteRequired = action === "reject" || action === "changes";
  const [noteErr, setNoteErr] = React.useState(false);

  React.useEffect(() => { setNoteErr(false); }, [action]);

  const submit = () => {
    if (noteRequired && !note.trim()) { setNoteErr(true); return; }
    onAction(approval, action, note);
    setNote(""); setAction(null); setNoteErr(false);
  };

  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, background: "rgba(28,26,21,0.6)", zIndex: 80,
      display: "flex", justifyContent: "flex-end",
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: "min(640px, 100%)", height: "100%", background: "var(--paper)",
        display: "flex", flexDirection: "column",
        boxShadow: "-20px 0 60px rgba(0,0,0,0.25)",
      }}>
        {/* Header */}
        <div style={{ padding: "22px 28px", borderBottom: "1px solid var(--line-2)", background: "var(--paper-2)" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
            <div style={{ display: "flex", gap: 14, alignItems: "flex-start", flex: 1 }}>
              <AdminTypeIcon type={approval.type} size={44} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                  <AdminPill tone={type.tone}>{type[lang] || type.en}</AdminPill>
                  <span style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", color: "var(--muted)" }}>{approval.id}</span>
                  <PriorityDot p={approval.priority} />
                </div>
                <h2 style={{ marginTop: 8, fontFamily: "var(--ff-display)", fontSize: 26, lineHeight: 1.15 }}>{window.approvalTitle(approval, lang)}</h2>
                <div style={{ marginTop: 4, fontSize: 13, color: "var(--muted)" }}>{approval.summary}</div>
              </div>
            </div>
            <button onClick={onClose} aria-label={lang === "en" ? "Close approval drawer" : "إغلاق المراجعة"} style={{ background: "transparent", border: 0, fontSize: 24, cursor: "pointer", color: "var(--muted)", marginLeft: 12, minWidth: 44, minHeight: 44, display: "inline-flex", alignItems: "center", justifyContent: "center", padding: 0 }}>×</button>
          </div>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflowY: "auto", padding: "24px 28px", display: "flex", flexDirection: "column", gap: 24 }}>
          {/* Maker card */}
          <div style={{ padding: 14, border: "1px solid var(--line-2)", borderRadius: 12, background: "var(--paper)", display: "flex", gap: 14, alignItems: "center" }}>
            <div style={{ width: 44, height: 44, borderRadius: "50%", overflow: "hidden", flexShrink: 0 }}>
              <Placeholder tone={(window.ADMIN_MAKERS.find(m => m.slug === approval.maker)?.tone) || "sand"} label="" meta="" />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: "var(--ff-display)", fontSize: 18 }}>{approval.makerName}</div>
              {approval.maker && <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)" }}>{(() => {
                const m = window.ADMIN_MAKERS.find(x => x.slug === approval.maker);
                if (!m) return "";
                const trade = window.categoryLabel ? window.categoryLabel(m.trade, lang) : m.trade;
                const rubric = (m.rubric != null)
                  ? `${m.rubric}/100`
                  : (lang === "en" ? "unrated" : "غير مقيَّم");
                return `${trade} · ${m.city} · ${lang === "en" ? "rubric" : "تقييم"} ${rubric}`;
              })()}</div>}
              {!approval.maker && <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--terracotta)" }}>{lang === "en" ? "New applicant" : "متقدّم جديد"}</div>}
            </div>
            {approval.maker && (
              <a href={`#/makers/${approval.maker}`} style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--terracotta)", textDecoration: "none", whiteSpace: "nowrap" }}>
                {lang === "en" ? "Public profile ↗" : "الصفحة العامّة ↗"}
              </a>
            )}
          </div>

          {/* Diff */}
          <div>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 10 }}>
              {lang === "en" ? "What's changing" : "ما الذي سيتغيّر"}
            </div>
            <div style={{ border: "1px solid var(--line-2)", borderRadius: 12, overflow: "hidden" }}>
              {approval.diff.map((d, i) => (
                <div key={i} style={{
                  padding: "14px 16px", borderTop: i === 0 ? "none" : "1px solid var(--line-2)",
                  display: "grid", gridTemplateColumns: "140px 1fr", gap: 14, alignItems: "flex-start",
                }}>
                  <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)", paddingTop: 2 }}>{d.k}</div>
                  <div>
                    {d.old && (
                      <div style={{
                        padding: "6px 10px", borderRadius: 6,
                        background: "rgba(194,99,66,0.08)",
                        color: "var(--terracotta-dk)",
                        fontSize: 13, marginBottom: 6,
                        textDecoration: "line-through",
                        fontFamily: "var(--ff-sans)",
                      }}>− {d.old}</div>
                    )}
                    <div style={{
                      padding: "6px 10px", borderRadius: 6,
                      background: d.old ? "rgba(123,132,99,0.10)" : "var(--paper-2)",
                      color: d.old ? "var(--olive)" : "var(--ink)",
                      fontSize: 13, fontFamily: "var(--ff-sans)",
                    }}>{d.old ? "+ " : ""}{d.new}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Maker note */}
          {approval.note && (
            <div>
              <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 8 }}>
                {lang === "en" ? "Note from maker" : "ملاحظة من الصانع"}
              </div>
              <div style={{
                padding: "14px 16px", borderLeft: "2px solid var(--gold)",
                background: "var(--paper-2)", borderRadius: "0 10px 10px 0",
                fontFamily: "var(--ff-editorial)", fontSize: 15, fontStyle: "italic", color: "var(--ink)",
                lineHeight: 1.5,
              }}>
                "{approval.note}"
              </div>
            </div>
          )}

          {/* Meta */}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, padding: "14px 16px", background: "var(--paper-2)", borderRadius: 10 }}>
            <div>
              <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "Submitted" : "مقدَّم"}</div>
              <div style={{ marginTop: 2, fontSize: 13 }}>{window.fmtDate(approval.submitted, lang)}</div>
            </div>
            <div>
              <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "Request ID" : "رقم الطلب"}</div>
              <div style={{ marginTop: 2, fontFamily: "var(--ff-mono)", fontSize: 13 }}>{approval.id}</div>
            </div>
          </div>

          {/* Action panel */}
          {action && (
            <div style={{ padding: "16px 18px", border: `1.5px solid ${action === "approve" ? "var(--olive)" : action === "reject" ? "var(--terracotta)" : "var(--gold)"}`, borderRadius: 12 }}>
              <div style={{ fontFamily: "var(--ff-display)", fontSize: 18, marginBottom: 10 }}>
                {action === "approve" && (lang === "en" ? "Approve this change?" : "موافقة على التغيير؟")}
                {action === "reject" && (lang === "en" ? "Reject this change?" : "رفض التغيير؟")}
                {action === "changes" && (lang === "en" ? "Ask for changes?" : "اطلب تعديل؟")}
              </div>
              <textarea
                value={note} onChange={e => { setNote(e.target.value); if (e.target.value.trim()) setNoteErr(false); }}
                rows={3}
                placeholder={lang === "en"
                  ? (action === "approve" ? "Optional note to the maker…" : "Tell the maker why (required)…")
                  : (action === "approve" ? "ملاحظة اختياريّة للصانع…" : "أخبر الصانع بالسبب (مطلوب)…")}
                style={{
                  width: "100%", padding: "10px 12px",
                  border: `1px solid ${noteErr ? "var(--terracotta)" : "var(--line-2)"}`, borderRadius: 8,
                  background: "var(--paper)", fontFamily: "var(--ff-sans)", fontSize: 13, resize: "vertical",
                }} />
              {noteErr && (
                <div role="alert" style={{ marginTop: 6, fontSize: 12, color: "var(--terracotta)" }}>
                  {lang === "en"
                    ? "A note is required when rejecting or requesting changes."
                    : "الملاحظة مطلوبة عند الرفض أو طلب التعديل."}
                </div>
              )}
              <div style={{ display: "flex", gap: 8, marginTop: 10 }}>
                <button onClick={submit} className="btn" style={{ padding: "10px 18px", fontSize: 11 }}>
                  {lang === "en" ? "Send" : "إرسال"} →
                </button>
                <button onClick={() => { setAction(null); setNote(""); }} className="btn ghost" style={{ padding: "10px 18px", fontSize: 11 }}>
                  {lang === "en" ? "Cancel" : "إلغاء"}
                </button>
              </div>
            </div>
          )}
        </div>

        {/* Footer actions */}
        {!action && (
          <div style={{ padding: "16px 28px", borderTop: "1px solid var(--line-2)", background: "var(--paper-2)", display: "flex", gap: 10, flexWrap: "wrap" }}>
            <button onClick={() => setAction("approve")} style={{
              flex: 1, padding: "14px 20px", border: 0, borderRadius: 999,
              background: "var(--olive)", color: "var(--paper)",
              fontFamily: "var(--ff-sans)", fontSize: 12, letterSpacing: "0.14em", textTransform: "uppercase",
              cursor: "pointer", fontWeight: 500,
            }}>✓ {lang === "en" ? "Approve" : "موافقة"}</button>
            <button onClick={() => setAction("changes")} style={{
              padding: "14px 20px", border: "1px solid var(--line)", borderRadius: 999,
              background: "var(--paper)", color: "var(--ink)",
              fontFamily: "var(--ff-sans)", fontSize: 12, letterSpacing: "0.14em", textTransform: "uppercase", cursor: "pointer",
            }}>↻ {lang === "en" ? "Request changes" : "طلب تعديل"}</button>
            <button onClick={() => setAction("reject")} style={{
              padding: "14px 20px", border: "1px solid var(--terracotta)", borderRadius: 999,
              background: "transparent", color: "var(--terracotta)",
              fontFamily: "var(--ff-sans)", fontSize: 12, letterSpacing: "0.14em", textTransform: "uppercase", cursor: "pointer",
            }}>× {lang === "en" ? "Reject" : "رفض"}</button>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { ApprovalsPage, ApprovalDrawer });
