/* global React, Icon, Chip, Button, api */

const SM_SERVICES = [
  { id: "SVC-001", name: "Visa Services",                 icon: "plane",          subs: ["Company visa", "Investor visa", "Employment visa", "Visit visa", "Transit visa"] },
  { id: "SVC-002", name: "Immigration & Labour",          icon: "users-round",    subs: ["Labour card issuance", "Work permit renewal", "MOL approval", "Immigration clearance"] },
  { id: "SVC-003", name: "PRO Services",                  icon: "file-signature", subs: ["Document clearance", "Government liaison", "Monthly PRO retainer", "Courier & typing"] },
  { id: "SVC-004", name: "Trade License Services",        icon: "badge-check",    subs: ["New license registration", "License renewal", "License amendment", "License cancellation"] },
  { id: "SVC-005", name: "Dubai Dept. Approvals",         icon: "landmark",       subs: ["Dubai Municipality", "Civil Defence approval", "DHA approval", "KHDA approval"] },
  { id: "SVC-006", name: "Business Setup Services",       icon: "briefcase",      subs: ["Mainland LLC setup", "Free zone setup", "Branch registration", "Bank account intro"] },
  { id: "SVC-007", name: "Dubai Economic Services",       icon: "building-2",     subs: ["DED registration", "Economic substance", "Commercial compliance", "Tax registration"] },
  { id: "SVC-008", name: "Certificate Attestation",       icon: "stamp",          subs: ["MOFA attestation", "Embassy legalisation", "Apostille", "Translation & notarisation"] },
];

const INIT_SM_STAGES = [
  /* ─── Visa Services · Employment visa (9 stages) ─── */
  { id: "STG-001", svcId: "SVC-001", svc: "Visa Services", sub: "Employment visa",  no: 1, name: "Job Offer & Contract Approval",       desc: "Employment contract attested and approved by MOHRE",                    status: "active" },
  { id: "STG-002", svcId: "SVC-001", svc: "Visa Services", sub: "Employment visa",  no: 2, name: "Work Permit Application (MOHRE)",       desc: "Work permit application submitted to Ministry of Human Resources",      status: "active" },
  { id: "STG-003", svcId: "SVC-001", svc: "Visa Services", sub: "Employment visa",  no: 3, name: "Entry Permit Issuance",                 desc: "Entry permit issued via GDRFA for applicant to enter UAE",              status: "active" },
  { id: "STG-004", svcId: "SVC-001", svc: "Visa Services", sub: "Employment visa",  no: 4, name: "Entry into UAE / Status Change",        desc: "Applicant enters UAE or status changed inside country",                 status: "active" },
  { id: "STG-005", svcId: "SVC-001", svc: "Visa Services", sub: "Employment visa",  no: 5, name: "Biometric Registration",                desc: "Fingerprints and biometrics registered at GDRFA/ICP centre",           status: "active" },
  { id: "STG-006", svcId: "SVC-001", svc: "Visa Services", sub: "Employment visa",  no: 6, name: "Medical Fitness Test",                  desc: "Medical test completed at approved government centre",                  status: "active" },
  { id: "STG-007", svcId: "SVC-001", svc: "Visa Services", sub: "Employment visa",  no: 7, name: "Labour Contract Upload",                desc: "Final labour contract uploaded to MOHRE smart system",                  status: "active" },
  { id: "STG-008", svcId: "SVC-001", svc: "Visa Services", sub: "Employment visa",  no: 8, name: "Residence Visa Application",            desc: "Residence visa stamp application submitted to GDRFA",                   status: "active" },
  { id: "STG-009", svcId: "SVC-001", svc: "Visa Services", sub: "Employment visa",  no: 9, name: "Emirates ID & Visa Issuance",           desc: "Emirates ID and residence visa issued and delivered",                   status: "active" },
  /* ─── Visa Services · Visit visa (7 stages) ─── */
  { id: "STG-010", svcId: "SVC-001", svc: "Visa Services", sub: "Visit visa",       no: 1, name: "Online Application Submission",         desc: "Application form submitted via GDRFA or ICP portal",                   status: "active" },
  { id: "STG-011", svcId: "SVC-001", svc: "Visa Services", sub: "Visit visa",       no: 2, name: "Document Upload",                       desc: "Passport copy, photo, travel insurance and itinerary uploaded",         status: "active" },
  { id: "STG-012", svcId: "SVC-001", svc: "Visa Services", sub: "Visit visa",       no: 3, name: "Fee Payment",                           desc: "Application fee settled online or at service centre",                   status: "active" },
  { id: "STG-013", svcId: "SVC-001", svc: "Visa Services", sub: "Visit visa",       no: 4, name: "Immigration Review & Security Check",   desc: "Application reviewed by UAE immigration authorities",                   status: "active" },
  { id: "STG-014", svcId: "SVC-001", svc: "Visa Services", sub: "Visit visa",       no: 5, name: "Approval / Rejection Decision",         desc: "Decision issued by immigration department",                            status: "active" },
  { id: "STG-015", svcId: "SVC-001", svc: "Visa Services", sub: "Visit visa",       no: 6, name: "E-Visa Issuance",                       desc: "E-visa document generated and sent to applicant",                       status: "active" },
  { id: "STG-016", svcId: "SVC-001", svc: "Visa Services", sub: "Visit visa",       no: 7, name: "Application Tracking & Completion",     desc: "Visa confirmed active; entry stamp tracked on arrival",                 status: "active" },
  /* ─── Trade License Services · License renewal (6 stages) ─── */
  { id: "STG-017", svcId: "SVC-004", svc: "Trade License Services", sub: "License renewal", no: 1, name: "Business Activity Selection",      desc: "Business activities confirmed; DED or free zone authority selected",   status: "active" },
  { id: "STG-018", svcId: "SVC-004", svc: "Trade License Services", sub: "License renewal", no: 2, name: "Initial Approval",                 desc: "Trade name reserved and initial approval obtained",                    status: "active" },
  { id: "STG-019", svcId: "SVC-004", svc: "Trade License Services", sub: "License renewal", no: 3, name: "Document Preparation & Submission", desc: "MOA, lease agreement and supporting documents submitted",              status: "active" },
  { id: "STG-020", svcId: "SVC-004", svc: "Trade License Services", sub: "License renewal", no: 4, name: "License Fee Payment",               desc: "License and government fees settled",                                  status: "active" },
  { id: "STG-021", svcId: "SVC-004", svc: "Trade License Services", sub: "License renewal", no: 5, name: "Trade License Issuance",             desc: "Trade license issued by DED or free zone authority",                   status: "active" },
  { id: "STG-022", svcId: "SVC-004", svc: "Trade License Services", sub: "License renewal", no: 6, name: "Post-License Setup",                 desc: "Signboard, E-channel, bank account referral completed",                status: "active" },
  /* ─── Business Setup Services · Mainland LLC setup (7 stages) ─── */
  { id: "STG-023", svcId: "SVC-006", svc: "Business Setup Services", sub: "Mainland LLC setup", no: 1, name: "Business Structure Selection",  desc: "Mainland, free zone or offshore jurisdiction confirmed",               status: "active" },
  { id: "STG-024", svcId: "SVC-006", svc: "Business Setup Services", sub: "Mainland LLC setup", no: 2, name: "Name Reservation",              desc: "Company name approved and reserved with authority",                    status: "active" },
  { id: "STG-025", svcId: "SVC-006", svc: "Business Setup Services", sub: "Mainland LLC setup", no: 3, name: "Initial Approval",              desc: "Initial approval obtained from DED or free zone",                      status: "active" },
  { id: "STG-026", svcId: "SVC-006", svc: "Business Setup Services", sub: "Mainland LLC setup", no: 4, name: "Document Preparation (MOA/AoA)", desc: "Memorandum and Articles of Association drafted and notarised",        status: "active" },
  { id: "STG-027", svcId: "SVC-006", svc: "Business Setup Services", sub: "Mainland LLC setup", no: 5, name: "License Application & Fee Payment", desc: "License application submitted and all fees settled",              status: "active" },
  { id: "STG-028", svcId: "SVC-006", svc: "Business Setup Services", sub: "Mainland LLC setup", no: 6, name: "Company Registration",          desc: "Trade license and certificate of incorporation issued",                 status: "active" },
  { id: "STG-029", svcId: "SVC-006", svc: "Business Setup Services", sub: "Mainland LLC setup", no: 7, name: "Post-Setup Services",           desc: "Bank account, visa quota, E-channel and signboard arranged",           status: "active" },
  /* ─── Certificate Attestation · MOFA attestation (6 stages) ─── */
  { id: "STG-030", svcId: "SVC-008", svc: "Certificate Attestation", sub: "MOFA attestation", no: 1, name: "Document Submission & Verification", desc: "Original documents received and verified for authenticity",          status: "active" },
  { id: "STG-031", svcId: "SVC-008", svc: "Certificate Attestation", sub: "MOFA attestation", no: 2, name: "Notarisation",                    desc: "Documents notarised by certified notary public",                       status: "active" },
  { id: "STG-032", svcId: "SVC-008", svc: "Certificate Attestation", sub: "MOFA attestation", no: 3, name: "MOFA Attestation",                desc: "Ministry of Foreign Affairs stamp obtained",                           status: "active" },
  { id: "STG-033", svcId: "SVC-008", svc: "Certificate Attestation", sub: "MOFA attestation", no: 4, name: "Embassy / Consulate Legalisation", desc: "Documents legalised at relevant embassy or consulate",               status: "active" },
  { id: "STG-034", svcId: "SVC-008", svc: "Certificate Attestation", sub: "MOFA attestation", no: 5, name: "Ministry Attestation (MOE / MOH)", desc: "Attestation from Ministry of Education or Health where required",    status: "active" },
  { id: "STG-035", svcId: "SVC-008", svc: "Certificate Attestation", sub: "MOFA attestation", no: 6, name: "Final Delivery",                  desc: "Fully attested documents collected and delivered to client",            status: "active" },
];

function newStgId() { return "STG-" + Date.now().toString(36).toUpperCase(); }

/* ─── Add / Edit Modal ─── */
function StageFormModal({ stage, stages, onClose, onSave }) {
  const isEdit = !!stage;
  const blank  = { svcId: "", sub: "", no: "", name: "", desc: "", status: "active" };
  const [form, setForm]     = React.useState(isEdit ? { ...stage, no: String(stage.no) } : blank);
  const [errors, setErrors] = React.useState({});

  const set = k => e => setForm(f => ({ ...f, [k]: e.target.value }));

  const selectedSvc = SM_SERVICES.find(s => s.id === form.svcId);
  const subOptions  = selectedSvc ? selectedSvc.subs : [];

  const onSvcChange = e => {
    setForm(f => ({ ...f, svcId: e.target.value, sub: "", no: "" }));
  };

  const onSubChange = e => {
    const sub = e.target.value;
    const sibling = stages.filter(s => s.svcId === form.svcId && s.sub === sub && (!isEdit || s.id !== stage.id));
    const nextNo   = sibling.length > 0 ? Math.max(...sibling.map(s => s.no)) + 1 : 1;
    setForm(f => ({ ...f, sub, no: isEdit ? f.no : String(nextNo) }));
  };

  const validate = () => {
    const e = {};
    if (!form.svcId)        e.svcId = "Please select a service";
    if (!form.sub)          e.sub   = "Please select a sub-service";
    if (!form.name.trim())  e.name  = "Stage name is required";
    if (!form.no || isNaN(parseInt(form.no, 10)) || parseInt(form.no, 10) < 1) e.no = "Must be a positive number";
    return e;
  };

  const handleSave = () => {
    const e = validate();
    if (Object.keys(e).length) { setErrors(e); return; }
    const svc = SM_SERVICES.find(s => s.id === form.svcId);
    onSave({ ...form, id: isEdit ? form.id : newStgId(), svc: svc ? svc.name : "", no: parseInt(form.no, 10) });
  };

  const errStyle = { color: "var(--danger-500)", fontSize: 11.5, marginTop: 3 };

  return (
    <>
      <div className="scrim" onClick={onClose} />
      <div className="modal" role="dialog" aria-modal="true">
        <div className="modal-head">
          <div>
            <div className="eyebrow" style={{ marginBottom: 4 }}>Stage Master</div>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>{isEdit ? "Edit stage" : "Add new stage"}</h2>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>

        <div className="modal-body">
          {/* Service + Sub-service */}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <div className="field">
              <label>Service <span style={{ color: "var(--danger-500)" }}>*</span></label>
              <select value={form.svcId} onChange={onSvcChange}>
                <option value="">Select service…</option>
                {SM_SERVICES.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select>
              {errors.svcId && <div style={errStyle}>{errors.svcId}</div>}
            </div>
            <div className="field">
              <label>Sub-service <span style={{ color: "var(--danger-500)" }}>*</span></label>
              <select value={form.sub} onChange={onSubChange} disabled={!form.svcId}>
                <option value="">{form.svcId ? "Select sub-service…" : "Select service first"}</option>
                {subOptions.map(s => <option key={s} value={s}>{s}</option>)}
              </select>
              {errors.sub && <div style={errStyle}>{errors.sub}</div>}
            </div>
          </div>

          {/* Stage no + Name */}
          <div style={{ display: "grid", gridTemplateColumns: "110px 1fr", gap: 14 }}>
            <div className="field">
              <label>Stage no. <span style={{ color: "var(--danger-500)" }}>*</span></label>
              <input type="number" min="1" value={form.no} onChange={set("no")} placeholder="1" />
              {errors.no && <div style={errStyle}>{errors.no}</div>}
            </div>
            <div className="field">
              <label>Stage name <span style={{ color: "var(--danger-500)" }}>*</span></label>
              <input value={form.name} onChange={set("name")} placeholder="e.g. Document Collection & Verification" />
              {errors.name && <div style={errStyle}>{errors.name}</div>}
            </div>
          </div>

          {/* Description */}
          <div className="field">
            <label>Description</label>
            <textarea rows={3} value={form.desc} onChange={set("desc")}
              placeholder="Brief description of what happens at this stage…"
              style={{ resize: "vertical" }} />
          </div>

          {/* Status toggle */}
          <div className="field">
            <label>Status</label>
            <div style={{ display: "flex", gap: 8, marginTop: 2 }}>
              {["active", "inactive"].map(s => (
                <button key={s} type="button" onClick={() => setForm(f => ({ ...f, status: s }))}
                  style={{
                    padding: "7px 20px", borderRadius: 6, cursor: "pointer",
                    fontFamily: "inherit", fontSize: 13, fontWeight: 500,
                    border: form.status === s ? "2px solid var(--brand-burgundy)" : "1px solid var(--border-subtle)",
                    background: form.status === s ? "var(--plum-50)" : "#fff",
                    color: form.status === s ? "var(--brand-burgundy)" : "var(--fg-3)",
                  }}>
                  {s === "active" ? "Active" : "Inactive"}
                </button>
              ))}
            </div>
          </div>

          <div className="modal-footer">
            <Button variant="secondary" type="button" onClick={onClose}>Cancel</Button>
            <Button icon="check" onClick={handleSave}>{isEdit ? "Save changes" : "Add stage"}</Button>
          </div>
        </div>
      </div>
    </>
  );
}

/* ─── Delete Confirmation ─── */
function DeleteConfirmModal({ stage, onClose, onConfirm }) {
  return (
    <>
      <div className="scrim" onClick={onClose} />
      <div className="modal" role="dialog" style={{ maxWidth: 420 }}>
        <div className="modal-head">
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>Delete stage?</h2>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>
        <div className="modal-body">
          <div style={{ padding: "10px 14px", background: "var(--ink-50)", borderRadius: 8, marginBottom: 18, fontSize: 13 }}>
            <div style={{ fontWeight: 600 }}>Stage {String(stage.no).padStart(2, "0")} — {stage.name}</div>
            <div style={{ color: "var(--fg-3)", fontSize: 12, marginTop: 2 }}>{stage.svc} › {stage.sub}</div>
          </div>
          <p style={{ fontSize: 13.5, color: "var(--fg-2)", margin: "0 0 6px" }}>
            This stage will be permanently removed from the stage master.
          </p>
          <p style={{ fontSize: 13, color: "var(--fg-3)", margin: 0 }}>
            Existing engagements already past this stage will not be affected.
          </p>
          <div className="modal-footer" style={{ marginTop: 20 }}>
            <Button variant="secondary" onClick={onClose}>Cancel</Button>
            <button className="btn" onClick={onConfirm}
              style={{ background: "var(--danger-500)", color: "#fff", border: "1px solid var(--danger-500)", display: "flex", alignItems: "center", gap: 6, padding: "8px 16px", borderRadius: 6, cursor: "pointer", fontFamily: "inherit", fontSize: 13.5, fontWeight: 600 }}>
              <Icon name="trash-2" size={14} />Delete stage
            </button>
          </div>
        </div>
      </div>
    </>
  );
}

/* ─── Main Page ─── */
function StageMasterPage() {
  const [stages,    setStages]    = React.useState([]);
  const [loading,   setLoading]   = React.useState(true);
  const [svcFilter, setSvcFilter] = React.useState("all");
  const [subFilter, setSubFilter] = React.useState("all");
  const [search,    setSearch]    = React.useState("");
  const [modal,     setModal]     = React.useState(null);
  const [delStage,  setDelStage]  = React.useState(null);

  React.useEffect(() => {
    api.get("/stages")
      .then(res => setStages((res.data || []).map(api.map.stage)))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const selectedSvc = SM_SERVICES.find(s => s.id === svcFilter);
  const subOptions  = selectedSvc ? selectedSvc.subs : [];

  const onSvcFilterChange = v => { setSvcFilter(v); setSubFilter("all"); };

  /* filtered flat list */
  const q = search.toLowerCase();
  const filtered = stages.filter(s => {
    if (svcFilter !== "all" && s.svcId !== svcFilter) return false;
    if (subFilter !== "all" && s.sub !== subFilter)   return false;
    if (q && !s.name.toLowerCase().includes(q) && !s.desc.toLowerCase().includes(q) && !s.sub.toLowerCase().includes(q)) return false;
    return true;
  });

  /* group by service + sub-service, preserving first-occurrence order */
  const grouped = [];
  const seenKeys = new Set();
  filtered.forEach(s => {
    const key = s.svcId + "||" + s.sub;
    if (!seenKeys.has(key)) {
      seenKeys.add(key);
      grouped.push({
        key,
        svc: s.svc,
        svcId: s.svcId,
        sub: s.sub,
        icon: (SM_SERVICES.find(sv => sv.id === s.svcId) || {}).icon || "layers",
        items: filtered.filter(x => x.svcId === s.svcId && x.sub === s.sub).sort((a, b) => a.no - b.no),
      });
    }
  });

  const handleSave = async (stg) => {
    try {
      if (stg._id) {
        const res = await api.put("/stages/" + stg._id, { name: stg.name, desc: stg.desc, stageNo: stg.no, status: stg.status });
        const updated = api.map.stage(res.data);
        setStages(prev => prev.map(s => s._id === updated._id ? updated : s));
      } else {
        const res = await api.post("/stages", { service: stg.svcId, subService: stg.subId, stageNo: stg.no, name: stg.name, desc: stg.desc, status: stg.status });
        setStages(prev => [...prev, api.map.stage(res.data)]);
      }
      setModal(null);
    } catch (err) {
      alert(err.message);
    }
  };

  const handleDelete = async () => {
    try {
      await api.delete("/stages/" + delStage._id);
      setStages(prev => prev.filter(s => s._id !== delStage._id));
      setDelStage(null);
    } catch (err) {
      alert(err.message);
    }
  };

  /* KPIs */
  const totalStages   = stages.length;
  const activeStages  = stages.filter(s => s.status === "active").length;
  const configSvcs    = new Set(stages.map(s => s.svcId)).size;
  const configSubs    = new Set(stages.map(s => s.svcId + "||" + s.sub)).size;

  /* pill button helper */
  const pill = (label, active, onClick, icon) => (
    <button onClick={onClick}
      style={{
        display: "flex", alignItems: "center", gap: icon ? 6 : 0,
        padding: "6px 14px", borderRadius: 6, border: "1px solid", cursor: "pointer",
        fontFamily: "inherit", fontSize: 13, whiteSpace: "nowrap",
        background: active ? "var(--plum-900)" : "#fff",
        color:      active ? "#fff"            : "var(--fg-2)",
        borderColor: active ? "var(--plum-900)" : "var(--border-strong)",
      }}>
      {icon && <Icon name={icon} size={13} />}
      {label}
    </button>
  );

  const subPill = (label, active, onClick) => (
    <button key={label} onClick={onClick}
      style={{
        padding: "5px 12px", borderRadius: 6, border: "1px solid", cursor: "pointer",
        fontFamily: "inherit", fontSize: 12.5,
        background: active ? "var(--brand-burgundy)" : "#fff",
        color:      active ? "#fff"                  : "var(--fg-2)",
        borderColor: active ? "var(--brand-burgundy)" : "var(--border-strong)",
      }}>
      {label}
    </button>
  );

  return (
    <>
    <div className="page">
      {/* Header */}
      <div className="page-head">
        <div>
          <div className="eyebrow">Setup · Services</div>
          <h1 className="page-title">Stage master</h1>
          <div className="page-sub">
            {totalStages} stages &nbsp;·&nbsp; {configSvcs} service{configSvcs !== 1 ? "s" : ""} &nbsp;·&nbsp; {configSubs} sub-service{configSubs !== 1 ? "s" : ""} configured
          </div>
        </div>
        <Button icon="plus" onClick={() => setModal("add")}>Add stage</Button>
      </div>

      {/* KPIs */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 24 }}>
        {[
          { lbl: "Total stages",           val: totalStages  },
          { lbl: "Active stages",          val: activeStages },
          { lbl: "Services configured",    val: configSvcs   },
          { lbl: "Sub-services configured",val: configSubs   },
        ].map(k => (
          <div key={k.lbl} className="kpi">
            <div className="lbl">{k.lbl}</div>
            <div className="val">{k.val}</div>
          </div>
        ))}
      </div>

      {/* Filter card */}
      <div className="card card-pad" style={{ marginBottom: 20 }}>
        {/* Service row */}
        <div style={{ marginBottom: svcFilter !== "all" && subOptions.length ? 16 : 0 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: 9 }}>Filter by service</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {pill("All services", svcFilter === "all", () => onSvcFilterChange("all"))}
            {SM_SERVICES.map(sv => pill(sv.name, svcFilter === sv.id, () => onSvcFilterChange(sv.id), sv.icon))}
          </div>
        </div>

        {/* Sub-service row — shown only when a service is selected */}
        {svcFilter !== "all" && subOptions.length > 0 && (
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: 9 }}>Filter by sub-service</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
              {subPill("All sub-services", subFilter === "all", () => setSubFilter("all"))}
              {subOptions.map(sub => subPill(sub, subFilter === sub, () => setSubFilter(sub)))}
            </div>
          </div>
        )}
      </div>

      {/* Search + count bar */}
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 18 }}>
        <div style={{ position: "relative", flex: 1, maxWidth: 380 }}>
          <span style={{ position: "absolute", left: 10, top: "50%", transform: "translateY(-50%)", color: "var(--fg-3)", pointerEvents: "none", display: "flex" }}>
            <Icon name="search" size={15} />
          </span>
          <input value={search} onChange={e => setSearch(e.target.value)}
            placeholder="Search stages by name or description…"
            style={{ width: "100%", padding: "8px 12px 8px 34px", border: "1px solid var(--border-subtle)", borderRadius: 8, fontFamily: "inherit", fontSize: 13, outline: "none", background: "#fff" }} />
        </div>
        {search && (
          <button onClick={() => setSearch("")}
            style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 12.5, color: "var(--fg-3)", background: "transparent", border: 0, cursor: "pointer", fontFamily: "inherit" }}>
            <Icon name="x" size={12} />Clear
          </button>
        )}
        <div style={{ fontSize: 13, color: "var(--fg-3)", marginLeft: "auto" }}>
          {filtered.length} stage{filtered.length !== 1 ? "s" : ""}
        </div>
      </div>

      {/* Grouped stage tables */}
      {grouped.length === 0 ? (
        <div className="card" style={{ textAlign: "center", padding: "64px 20px", color: "var(--fg-3)" }}>
          <Icon name="layers" size={32} />
          <div style={{ marginTop: 12, fontSize: 15, fontWeight: 500, color: "var(--fg-2)" }}>No stages found</div>
          <div style={{ fontSize: 13, marginTop: 4 }}>Adjust your filters or search, or add a new stage.</div>
          <button className="btn btn-primary" style={{ marginTop: 18, display: "inline-flex", alignItems: "center", gap: 6 }}
            onClick={() => setModal("add")}>
            <Icon name="plus" size={14} />Add stage
          </button>
        </div>
      ) : grouped.map(group => (
        <div key={group.key} className="card" style={{ marginBottom: 16, padding: 0, overflow: "hidden" }}>

          {/* Group header */}
          <div style={{
            padding: "13px 20px", background: "var(--plum-50)",
            borderBottom: "1px solid var(--border-subtle)",
            display: "flex", alignItems: "center", justifyContent: "space-between",
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <div style={{ width: 30, height: 30, borderRadius: 7, background: "var(--brand-burgundy)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                <Icon name={group.icon} size={15} />
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
                <span style={{ fontSize: 13, fontWeight: 700, color: "var(--brand-burgundy)" }}>{group.svc}</span>
                <span style={{ fontSize: 13, color: "var(--fg-4)" }}>›</span>
                <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--fg-1)" }}>{group.sub}</span>
              </div>
              <span style={{ fontSize: 11.5, color: "var(--fg-3)", background: "var(--ink-100)", borderRadius: 10, padding: "2px 9px" }}>
                {group.items.length} stage{group.items.length !== 1 ? "s" : ""}
              </span>
            </div>
            <button className="btn btn-ghost btn-sm"
              onClick={() => setModal({ svcId: group.svcId, svc: group.svc, sub: group.sub, no: "", name: "", desc: "", status: "active" })}>
              <Icon name="plus" size={13} />Add stage here
            </button>
          </div>

          {/* Stage table */}
          <table style={{ width: "100%", borderCollapse: "collapse" }}>
            <thead>
              <tr style={{ background: "var(--ink-50)" }}>
                {["No.", "Stage name", "Description", "Status", ""].map((h, i) => (
                  <th key={i} style={{
                    padding: "8px 20px", textAlign: i === 4 ? "right" : "left",
                    fontSize: 10.5, fontWeight: 700, color: "var(--fg-3)",
                    textTransform: "uppercase", letterSpacing: "0.1em",
                    width: [64, "auto", "auto", 90, 110][i],
                  }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {group.items.map((stg, i) => (
                <tr key={stg.id} style={{ borderTop: "1px solid var(--border-subtle)" }}>
                  <td style={{ padding: "11px 20px" }}>
                    <div style={{
                      display: "inline-flex", alignItems: "center", justifyContent: "center",
                      width: 30, height: 30, borderRadius: 7,
                      background: stg.status === "active" ? "var(--plum-50)" : "var(--ink-100)",
                      color: stg.status === "active" ? "var(--brand-burgundy)" : "var(--fg-4)",
                      fontWeight: 700, fontSize: 12, fontFamily: "var(--font-mono)",
                    }}>
                      {String(stg.no).padStart(2, "0")}
                    </div>
                  </td>
                  <td style={{ padding: "11px 20px" }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600 }}>{stg.name}</div>
                  </td>
                  <td style={{ padding: "11px 20px" }}>
                    <div style={{ fontSize: 12.5, color: "var(--fg-3)", lineHeight: 1.45, maxWidth: 360 }}>{stg.desc || <span style={{ color: "var(--fg-4)" }}>No description</span>}</div>
                  </td>
                  <td style={{ padding: "11px 20px" }}>
                    <Chip kind={stg.status === "active" ? "success" : "default"}>{stg.status === "active" ? "Active" : "Inactive"}</Chip>
                  </td>
                  <td style={{ padding: "11px 20px", textAlign: "right" }}>
                    <div style={{ display: "flex", gap: 4, justifyContent: "flex-end" }}>
                      <button className="btn btn-ghost btn-sm" onClick={() => setModal(stg)}>
                        <Icon name="pencil" size={13} />Edit
                      </button>
                      <button className="btn btn-ghost btn-sm" title="Delete"
                        style={{ color: "var(--danger-500)" }}
                        onClick={() => setDelStage(stg)}>
                        <Icon name="trash-2" size={13} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ))}
    </div>

    {/* Add / Edit modal */}
    {modal !== null && (
      <StageFormModal
        stage={modal === "add" ? null : modal}
        stages={stages}
        onClose={() => setModal(null)}
        onSave={handleSave}
      />
    )}

    {/* Delete confirmation */}
    {delStage && (
      <DeleteConfirmModal
        stage={delStage}
        onClose={() => setDelStage(null)}
        onConfirm={handleDelete}
      />
    )}
    </>
  );
}

Object.assign(window, { StageMasterPage });
