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

const SSM_SERVICES = [
  { id: "SVC-001", name: "Visa Services",                 icon: "plane"          },
  { id: "SVC-002", name: "Immigration & Labour",          icon: "users-round"    },
  { id: "SVC-003", name: "PRO Services",                  icon: "file-signature" },
  { id: "SVC-004", name: "Trade License Services",        icon: "badge-check"    },
  { id: "SVC-005", name: "Dubai Dept. Approvals",         icon: "landmark"       },
  { id: "SVC-006", name: "Business Setup Services",       icon: "briefcase"      },
  { id: "SVC-007", name: "Dubai Economic Services",       icon: "building-2"     },
  { id: "SVC-008", name: "Certificate Attestation",       icon: "stamp"          },
];

const INIT_SUB_SERVICES = [
  /* ─── Visa Services ─── */
  { id: "SUB-001", svcId: "SVC-001", svc: "Visa Services", name: "Company visa",    desc: "Employment visas for company-sponsored employees under UAE mainland or free zone licence.", basePrice: "AED 1,200", processingTime: "5–7 working days",   status: "active" },
  { id: "SUB-002", svcId: "SVC-001", svc: "Visa Services", name: "Investor visa",   desc: "Long-term residence visas for business owners, shareholders and investors in the UAE.", basePrice: "AED 2,500", processingTime: "10–15 working days",  status: "active" },
  { id: "SUB-003", svcId: "SVC-001", svc: "Visa Services", name: "Employment visa", desc: "Residence and work permits for expatriate employees entering the UAE for work.", basePrice: "AED 1,800", processingTime: "7–14 working days",   status: "active" },
  { id: "SUB-004", svcId: "SVC-001", svc: "Visa Services", name: "Visit visa",      desc: "Short-stay tourist or family visit visas — 30, 60 or 90-day options.", basePrice: "AED 400",   processingTime: "2–5 working days",    status: "active" },
  { id: "SUB-005", svcId: "SVC-001", svc: "Visa Services", name: "Transit visa",    desc: "Short-stay transit visas for passengers transiting through UAE airports.", basePrice: "AED 200",   processingTime: "1–2 working days",    status: "active" },
  /* ─── Immigration & Labour ─── */
  { id: "SUB-006", svcId: "SVC-002", svc: "Immigration & Labour", name: "Labour card issuance",    desc: "Issue or update MOHRE labour cards for new and existing employees.", basePrice: "AED 900",   processingTime: "3–5 working days",    status: "active" },
  { id: "SUB-007", svcId: "SVC-002", svc: "Immigration & Labour", name: "Work permit renewal",     desc: "Renewal of existing work permits before expiry, including MOHRE filings.", basePrice: "AED 1,100", processingTime: "3–7 working days",    status: "active" },
  { id: "SUB-008", svcId: "SVC-002", svc: "Immigration & Labour", name: "MOL approval",            desc: "Ministry of Labour pre-approval for new hires and role changes.", basePrice: "AED 750",   processingTime: "2–5 working days",    status: "active" },
  { id: "SUB-009", svcId: "SVC-002", svc: "Immigration & Labour", name: "Immigration clearance",   desc: "GDRFA clearance for exit, status change or deportation prevention.", basePrice: "AED 600",   processingTime: "1–3 working days",    status: "active" },
  /* ─── PRO Services ─── */
  { id: "SUB-010", svcId: "SVC-003", svc: "PRO Services", name: "Document clearance",      desc: "Clearance and stamping of company and personal documents at government departments.", basePrice: "AED 800",       processingTime: "1–3 working days",    status: "active" },
  { id: "SUB-011", svcId: "SVC-003", svc: "PRO Services", name: "Government liaison",      desc: "Dedicated PRO representation at DED, GDRFA, MOHRE, AMER and other authorities.", basePrice: "AED 1,200",     processingTime: "2–5 working days",    status: "active" },
  { id: "SUB-012", svcId: "SVC-003", svc: "PRO Services", name: "Monthly PRO retainer",    desc: "On-demand PRO officer assigned to your company for all ongoing government tasks.", basePrice: "AED 2,500/mo",  processingTime: "Ongoing",             status: "active" },
  { id: "SUB-013", svcId: "SVC-003", svc: "PRO Services", name: "Courier & typing",        desc: "Certified document typing, translation and courier between offices and departments.", basePrice: "AED 150",       processingTime: "Same day",            status: "active" },
  /* ─── Trade License Services ─── */
  { id: "SUB-014", svcId: "SVC-004", svc: "Trade License Services", name: "New license registration", desc: "End-to-end DED or free zone trade license application for new business activities.", basePrice: "AED 5,500", processingTime: "7–14 working days",  status: "active" },
  { id: "SUB-015", svcId: "SVC-004", svc: "Trade License Services", name: "License renewal",          desc: "Annual renewal of existing DED or free zone trade licenses.", basePrice: "AED 2,500", processingTime: "5–10 working days",  status: "active" },
  { id: "SUB-016", svcId: "SVC-004", svc: "Trade License Services", name: "License amendment",        desc: "Amendments to trade name, activities, partners or legal structure.", basePrice: "AED 1,800", processingTime: "3–7 working days",   status: "active" },
  { id: "SUB-017", svcId: "SVC-004", svc: "Trade License Services", name: "License cancellation",     desc: "Formal cancellation and deregistration of a trade license with all authorities.", basePrice: "AED 1,200", processingTime: "5–10 working days",  status: "active" },
  /* ─── Dubai Dept. Approvals ─── */
  { id: "SUB-018", svcId: "SVC-005", svc: "Dubai Dept. Approvals", name: "Dubai Municipality",       desc: "Municipality approvals for food, health, construction and commercial activities.", basePrice: "AED 1,500", processingTime: "5–10 working days",  status: "active" },
  { id: "SUB-019", svcId: "SVC-005", svc: "Dubai Dept. Approvals", name: "Civil Defence approval",   desc: "Dubai Civil Defence fire safety certificates and compliance approvals.", basePrice: "AED 1,800", processingTime: "7–15 working days",  status: "active" },
  { id: "SUB-020", svcId: "SVC-005", svc: "Dubai Dept. Approvals", name: "DHA approval",             desc: "Dubai Health Authority approvals for healthcare facilities and professionals.", basePrice: "AED 2,000", processingTime: "10–15 working days", status: "active" },
  { id: "SUB-021", svcId: "SVC-005", svc: "Dubai Dept. Approvals", name: "KHDA approval",            desc: "Knowledge and Human Development Authority approvals for education sector entities.", basePrice: "AED 1,500", processingTime: "7–12 working days",  status: "active" },
  /* ─── Business Setup Services ─── */
  { id: "SUB-022", svcId: "SVC-006", svc: "Business Setup Services", name: "Mainland LLC setup",     desc: "Full incorporation of a Limited Liability Company under UAE mainland jurisdiction.", basePrice: "AED 8,500", processingTime: "10–21 working days", status: "active" },
  { id: "SUB-023", svcId: "SVC-006", svc: "Business Setup Services", name: "Free zone setup",        desc: "Company formation in UAE free zones including DMCC, DIFC, IFZA and others.", basePrice: "AED 6,000", processingTime: "7–14 working days",  status: "active" },
  { id: "SUB-024", svcId: "SVC-006", svc: "Business Setup Services", name: "Branch registration",    desc: "Registration of a UAE or foreign branch of an existing company.", basePrice: "AED 7,500", processingTime: "14–21 working days", status: "active" },
  { id: "SUB-025", svcId: "SVC-006", svc: "Business Setup Services", name: "Bank account intro",     desc: "Introduction and facilitation for corporate bank account opening with UAE banks.", basePrice: "AED 1,000", processingTime: "5–10 working days",  status: "active" },
  /* ─── Dubai Economic Services ─── */
  { id: "SUB-026", svcId: "SVC-007", svc: "Dubai Economic Services", name: "DED registration",       desc: "Registration of new business activities with the Dubai Department of Economy & Tourism.", basePrice: "AED 1,800", processingTime: "5–10 working days",  status: "active" },
  { id: "SUB-027", svcId: "SVC-007", svc: "Dubai Economic Services", name: "Economic substance",     desc: "Economic Substance Regulations (ESR) filing and compliance reporting.", basePrice: "AED 3,500", processingTime: "7–14 working days",  status: "active" },
  { id: "SUB-028", svcId: "SVC-007", svc: "Dubai Economic Services", name: "Commercial compliance",  desc: "Ongoing regulatory compliance for commercial operations under UAE law.", basePrice: "AED 2,200", processingTime: "5–10 working days",  status: "active" },
  { id: "SUB-029", svcId: "SVC-007", svc: "Dubai Economic Services", name: "Tax registration",       desc: "Corporate Tax and VAT registration with the Federal Tax Authority.", basePrice: "AED 2,500", processingTime: "3–7 working days",   status: "active" },
  /* ─── Certificate Attestation ─── */
  { id: "SUB-030", svcId: "SVC-008", svc: "Certificate Attestation", name: "MOFA attestation",           desc: "Ministry of Foreign Affairs attestation for personal and corporate documents.", basePrice: "AED 600", processingTime: "3–5 working days",   status: "active" },
  { id: "SUB-031", svcId: "SVC-008", svc: "Certificate Attestation", name: "Embassy legalisation",       desc: "Legalisation of UAE-issued documents at foreign embassies in Dubai.", basePrice: "AED 900", processingTime: "5–10 working days",  status: "active" },
  { id: "SUB-032", svcId: "SVC-008", svc: "Certificate Attestation", name: "Apostille",                  desc: "Apostille certification for use in Hague Convention signatory countries.", basePrice: "AED 750", processingTime: "3–7 working days",   status: "active" },
  { id: "SUB-033", svcId: "SVC-008", svc: "Certificate Attestation", name: "Translation & notarisation", desc: "Certified translation and notarisation of documents for official submission.", basePrice: "AED 350", processingTime: "1–2 working days",   status: "active" },
];

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

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

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

  const onSvcChange = e => {
    const svcId = e.target.value;
    const svc   = SSM_SERVICES.find(s => s.id === svcId);
    setForm(f => ({ ...f, svcId, svc: svc ? svc.name : "" }));
  };

  const validate = () => {
    const e = {};
    if (!form.svcId)       e.svcId = "Please select a service";
    if (!form.name.trim()) e.name  = "Sub-service name is required";
    return e;
  };

  const handleSave = () => {
    const e = validate();
    if (Object.keys(e).length) { setErrors(e); return; }
    onSave({ ...form });
  };

  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 }}>Sub-service Master</div>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>{isEdit ? "Edit sub-service" : "Add sub-service"}</h2>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>

        <div className="modal-body">
          {/* Service */}
          <div className="field">
            <label>Service <span style={{ color: "var(--danger-500)" }}>*</span></label>
            <select value={form.svcId} onChange={onSvcChange}>
              <option value="">Select service…</option>
              {SSM_SERVICES.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
            </select>
            {errors.svcId && <div style={errStyle}>{errors.svcId}</div>}
          </div>

          {/* Name */}
          <div className="field">
            <label>Sub-service name <span style={{ color: "var(--danger-500)" }}>*</span></label>
            <input value={form.name} onChange={set("name")} placeholder="e.g. Employment visa" />
            {errors.name && <div style={errStyle}>{errors.name}</div>}
          </div>

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

          {/* Base price + Processing time */}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <div className="field">
              <label>Base price</label>
              <input value={form.basePrice} onChange={set("basePrice")} placeholder="e.g. AED 1,200" />
            </div>
            <div className="field">
              <label>Processing time</label>
              <input value={form.processingTime} onChange={set("processingTime")} placeholder="e.g. 5–10 working days" />
            </div>
          </div>

          {/* Status */}
          <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 sub-service"}</Button>
          </div>
        </div>
      </div>
    </>
  );
}

/* ─── Delete Confirmation ─── */
function SubDeleteConfirmModal({ sub, 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 sub-service?</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 }}>{sub.name}</div>
            <div style={{ color: "var(--fg-3)", fontSize: 12, marginTop: 2 }}>{sub.svc}</div>
          </div>
          <p style={{ fontSize: 13.5, color: "var(--fg-2)", margin: "0 0 4px" }}>
            This sub-service will be permanently removed. Any stages linked to it in Stage Master will become orphaned.
          </p>
          <p style={{ fontSize: 13, color: "var(--fg-3)", margin: 0 }}>
            Active engagements using this sub-service 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
            </button>
          </div>
        </div>
      </div>
    </>
  );
}

/* ─── Main Page ─── */
function SubServiceMasterPage() {
  const [subs,      setSubs]      = React.useState([]);
  const [loading,   setLoading]   = React.useState(true);
  const [svcFilter, setSvcFilter] = React.useState("all");
  const [search,    setSearch]    = React.useState("");
  const [modal,     setModal]     = React.useState(null);
  const [delSub,    setDelSub]    = React.useState(null);

  React.useEffect(() => {
    api.get("/sub-services?status=")
      .then(res => setSubs((res.data || []).map(api.map.subService)))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

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

  /* group by service */
  const grouped = [];
  const seen = new Set();
  filtered.forEach(s => {
    if (!seen.has(s.svcId)) {
      seen.add(s.svcId);
      const svMeta = SSM_SERVICES.find(sv => sv.id === s.svcId) || {};
      grouped.push({
        svcId: s.svcId,
        svc:   s.svc,
        icon:  svMeta.icon || "layers",
        items: filtered.filter(x => x.svcId === s.svcId),
      });
    }
  });

  const handleSave = async (sub) => {
    try {
      if (sub._id) {
        const res = await api.put("/sub-services/" + sub._id, { name: sub.name, desc: sub.desc, basePrice: sub.basePrice, processingTime: sub.processingTime, status: sub.status });
        const updated = api.map.subService(res.data);
        setSubs(prev => prev.map(s => s._id === updated._id ? updated : s));
      } else {
        const res = await api.post("/sub-services", { service: sub.svcId, name: sub.name, desc: sub.desc, basePrice: sub.basePrice, processingTime: sub.processingTime, status: sub.status });
        setSubs(prev => [...prev, api.map.subService(res.data)]);
      }
      setModal(null);
    } catch (err) {
      alert(err.message);
    }
  };

  const handleDelete = async () => {
    try {
      await api.delete("/sub-services/" + delSub._id);
      setSubs(prev => prev.filter(s => s._id !== delSub._id));
      setDelSub(null);
    } catch (err) {
      alert(err.message);
    }
  };

  /* KPIs */
  const totalSubs   = subs.length;
  const activeSubs  = subs.filter(s => s.status === "active").length;
  const configSvcs  = new Set(subs.map(s => s.svcId)).size;

  /* pill helper */
  const pill = (label, active, onClick, icon) => (
    <button key={label} 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>
  );

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

      {/* KPIs */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 24 }}>
        {[
          { lbl: "Total sub-services",  val: totalSubs  },
          { lbl: "Active",              val: activeSubs  },
          { lbl: "Inactive",            val: totalSubs - activeSubs },
          { lbl: "Services covered",    val: configSvcs  },
        ].map(k => (
          <div key={k.lbl} className="kpi">
            <div className="lbl">{k.lbl}</div>
            <div className="val">{k.val}</div>
          </div>
        ))}
      </div>

      {/* Service filter */}
      <div className="card card-pad" style={{ marginBottom: 20 }}>
        <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", () => setSvcFilter("all"))}
          {SSM_SERVICES.map(sv => pill(sv.name, svcFilter === sv.id, () => setSvcFilter(sv.id), sv.icon))}
        </div>
      </div>

      {/* Search + count */}
      <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 sub-services 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} sub-service{filtered.length !== 1 ? "s" : ""}
        </div>
      </div>

      {/* Grouped tables */}
      {grouped.length === 0 ? (
        <div className="card" style={{ textAlign: "center", padding: "64px 20px", color: "var(--fg-3)" }}>
          <Icon name="list-tree" size={32} />
          <div style={{ marginTop: 12, fontSize: 15, fontWeight: 500, color: "var(--fg-2)" }}>No sub-services found</div>
          <div style={{ fontSize: 13, marginTop: 4 }}>Adjust your filters or add a new sub-service.</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 sub-service
          </button>
        </div>
      ) : grouped.map(group => (
        <div key={group.svcId} 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>
              <span style={{ fontSize: 13.5, fontWeight: 700, color: "var(--brand-burgundy)" }}>{group.svc}</span>
              <span style={{ fontSize: 11.5, color: "var(--fg-3)", background: "var(--ink-100)", borderRadius: 10, padding: "2px 9px" }}>
                {group.items.length} sub-service{group.items.length !== 1 ? "s" : ""}
              </span>
            </div>
            <button className="btn btn-ghost btn-sm"
              onClick={() => {
                const sv = SSM_SERVICES.find(s => s.id === group.svcId);
                setModal({ svcId: group.svcId, svc: group.svc, name: "", desc: "", basePrice: "", processingTime: "", status: "active" });
              }}>
              <Icon name="plus" size={13} />Add here
            </button>
          </div>

          {/* Table */}
          <table style={{ width: "100%", borderCollapse: "collapse" }}>
            <thead>
              <tr style={{ background: "var(--ink-50)" }}>
                {["Sub-service name", "Description", "Base price", "Processing time", "Status", ""].map((h, i) => (
                  <th key={i} style={{
                    padding: "8px 20px",
                    textAlign: i === 5 ? "right" : "left",
                    fontSize: 10.5, fontWeight: 700, color: "var(--fg-3)",
                    textTransform: "uppercase", letterSpacing: "0.1em",
                    width: [null, null, 130, 160, 90, 110][i],
                  }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {group.items.map((sub, i) => (
                <tr key={sub.id} style={{ borderTop: "1px solid var(--border-subtle)" }}>
                  {/* Name */}
                  <td style={{ padding: "12px 20px" }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600 }}>{sub.name}</div>
                    <div style={{ fontSize: 11, fontFamily: "var(--font-mono)", color: "var(--fg-4)", marginTop: 2 }}>{sub.id}</div>
                  </td>
                  {/* Description */}
                  <td style={{ padding: "12px 20px" }}>
                    <div style={{ fontSize: 12.5, color: "var(--fg-3)", lineHeight: 1.45, maxWidth: 320 }}>
                      {sub.desc || <span style={{ color: "var(--fg-4)" }}>No description</span>}
                    </div>
                  </td>
                  {/* Base price */}
                  <td style={{ padding: "12px 20px" }}>
                    <div style={{ fontSize: 13, fontWeight: 600, fontFamily: "var(--font-mono)" }}>
                      {sub.basePrice || <span style={{ color: "var(--fg-4)", fontFamily: "inherit", fontWeight: 400 }}>—</span>}
                    </div>
                  </td>
                  {/* Processing time */}
                  <td style={{ padding: "12px 20px" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 13, color: "var(--fg-2)" }}>
                      {sub.processingTime ? <><Icon name="clock" size={13} />{sub.processingTime}</> : <span style={{ color: "var(--fg-4)" }}>—</span>}
                    </div>
                  </td>
                  {/* Status */}
                  <td style={{ padding: "12px 20px" }}>
                    <Chip kind={sub.status === "active" ? "success" : "default"}>
                      {sub.status === "active" ? "Active" : "Inactive"}
                    </Chip>
                  </td>
                  {/* Actions */}
                  <td style={{ padding: "12px 20px", textAlign: "right" }}>
                    <div style={{ display: "flex", gap: 4, justifyContent: "flex-end" }}>
                      <button className="btn btn-ghost btn-sm" onClick={() => setModal(sub)}>
                        <Icon name="pencil" size={13} />Edit
                      </button>
                      <button className="btn btn-ghost btn-sm" title="Delete"
                        style={{ color: "var(--danger-500)" }}
                        onClick={() => setDelSub(sub)}>
                        <Icon name="trash-2" size={13} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ))}
    </div>

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

    {/* Delete confirmation */}
    {delSub && (
      <SubDeleteConfirmModal
        sub={delSub}
        onClose={() => setDelSub(null)}
        onConfirm={handleDelete}
      />
    )}
    </>
  );
}

Object.assign(window, { SubServiceMasterPage });
