/* ============================================================
   HALO SMS — Bulk import wizard (shared: students/staff/guardians)
   CSV -> map -> validate -> commit
   ============================================================ */
(function () {
  const { useState, h } = window.HReact;

  const CFG = {
    students: { title: "students", file: "students_jss1a.csv", warnLabel: "No guardian", errLabel: "Invalid date",
      cols: ["surname", "first_name", "gender", "dob", "class", "state", "guardian_phone"],
      fields: ["Surname", "First name", "Gender", "Date of birth", "Class & arm", "State of origin", "Guardian phone"],
      rows: [
        ["Adewale", "Tunde", "Male", "2013-04-02", "JSS 1A", "Oyo", "0803 111 2233", "ok"],
        ["Nnamdi", "Chioma", "Female", "2013-08-19", "JSS 1A", "Anambra", "0806 221 9087", "ok"],
        ["Bello", "Yusuf", "Male", "2012-12-30", "JSS 1A", "Kano", "", "warn"],
        ["Okafor", "Ada", "Female", "bad-date", "JSS 1A", "Imo", "0807 553 1190", "err"],
        ["Lawal", "Bisi", "Female", "2013-01-15", "JSS 1A", "Lagos", "0803 998 7711", "ok"],
        ["Eze", "Kelechi", "Male", "2013-06-07", "JSS 1A", "Enugu", "0806 112 3345", "ok"] ] },
    staff: { title: "staff", file: "staff_2025.csv", warnLabel: "No role", errLabel: "Invalid email",
      cols: ["surname", "first_name", "email", "title", "role", "phone"],
      fields: ["Surname", "First name", "Email", "Designation", "Role", "Phone"],
      rows: [
        ["Adeniyi", "Kunle", "k.adeniyi@school.ng", "Chemistry Teacher", "subject-teacher", "0803 221 0098", "ok"],
        ["Mohammed", "Aisha", "a.mohammed@school.ng", "French Teacher", "subject-teacher", "0806 553 7711", "ok"],
        ["Obi", "Stanley", "not-an-email", "Lab Technician", "subject-teacher", "0807 112 9087", "err"],
        ["Yakubu", "Hauwa", "h.yakubu@school.ng", "Counsellor", "", "0803 778 1290", "warn"] ] },
    guardians: { title: "guardians", file: "guardians.csv", warnLabel: "No email", errLabel: "Invalid phone",
      cols: ["name", "relationship", "phone", "email", "child_admission"],
      fields: ["Full name", "Relationship", "Phone", "Email", "Child admission no."],
      rows: [
        ["Mr. Sunday Etim", "Father", "0803 221 7788", "s.etim@gmail.com", "BFA/2025/0142", "ok"],
        ["Mrs. Rita Obi", "Mother", "0806 553 1199", "rita.obi@gmail.com", "BFA/2025/0148", "ok"],
        ["Mr. James Bala", "Guardian", "0807-bad", "", "BFA/2025/0150", "err"] ] },
    results: { title: "score rows", file: "jss1a_mathematics.csv", warnLabel: "Missing exam", errLabel: "Exceeds max",
      cols: ["admission_no", "ca1", "ca2", "exam"],
      fields: ["Admission no.", "CA 1 /20", "CA 2 /20", "Exam /60"],
      rows: [
        ["BFA/2025/0142", "17", "17", "52", "ok"],
        ["BFA/2025/0150", "18", "16", "53", "ok"],
        ["BFA/2025/0148", "15", "15", "47", "ok"],
        ["BFA/2025/0211", "14", "13", "99", "err"],
        ["BFA/2025/0212", "16", "", "44", "warn"] ] },
  };

  function Stepper({ step }) {
    const labels = ["Upload", "Map columns", "Validate", "Commit"];
    return h("div", { style: { display: "flex", alignItems: "center", gap: 0, marginBottom: 24 } }, labels.map((l, i) =>
      h(React.Fragment, { key: l },
        h("div", { style: { display: "flex", alignItems: "center", gap: 9 } },
          h("div", { style: { width: 26, height: 26, borderRadius: 99, display: "grid", placeItems: "center", fontSize: 12.5, fontWeight: 700,
            background: i < step ? "var(--ok)" : i === step ? "var(--brand)" : "var(--surface-3)", color: i <= step ? "var(--on-brand)" : "var(--ink-500)" } }, i < step ? h(Icon, { name: "check" }) : i + 1),
          h("span", { style: { fontSize: 13, fontWeight: i === step ? 600 : 500, color: i === step ? "var(--ink-900)" : "var(--ink-500)" } }, l)),
        i < 3 && h("div", { style: { width: 36, height: 2, background: i < step ? "var(--ok)" : "var(--line)", margin: "0 12px" } }))));
  }

  function BulkImport({ entity, navigate, onDone }) {
    const cfg = CFG[entity] || CFG.students;
    const [step, setStep] = useState(0);
    const [committing, setCommitting] = useState(false);
    const counts = cfg.rows.reduce((a, r) => { a[r[r.length - 1]] = (a[r[r.length - 1]] || 0) + 1; return a; }, {});
    const okCount = (counts.ok || 0) + (counts.warn || 0);

    function commit() { setCommitting(true); setTimeout(() => { setStep(4); }, 1300); }

    return h(window.DesktopScreen, { title: "Bulk import" },
      h("div", { className: "page-pad", style: { maxWidth: 860 } },
        h(PageHead, { back: { label: "Cancel import", onClick: onDone }, eyebrow: "Bulk import", title: "Import " + cfg.title }),
        step < 4 && h(Stepper, { step }),
        h("div", { className: "card", style: { padding: 0 } },
          step === 0 && h("div", { style: { padding: 28 } },
            h("div", { onClick: () => setStep(1), style: { border: "1.5px dashed var(--line)", borderRadius: 14, padding: "40px 20px", textAlign: "center", cursor: "pointer", background: "var(--surface-2)" } },
              h("div", { style: { width: 52, height: 52, borderRadius: 14, background: "var(--brand-soft)", color: "var(--brand-strong)", display: "grid", placeItems: "center", fontSize: 24, margin: "0 auto 14px" } }, h(Icon, { name: "upload" })),
              h("h3", { style: { fontSize: 17 } }, "Drop a CSV here, or click to browse"),
              h("p", { className: "muted", style: { fontSize: 13.5, marginTop: 6 } }, "Up to 1,000 rows. We'll map columns next.")),
            h("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 18 } },
              h("button", { className: "btn btn-quiet btn-sm", onClick: () => setStep(1) }, h(Icon, { name: "filetext" }), "Use sample: " + cfg.file),
              h("a", { className: "btn btn-quiet btn-sm", onClick: (e) => e.preventDefault(), href: "#" }, "Download template"))),

          step === 1 && h("div", null,
            h("div", { style: { padding: "20px 24px" } }, h("p", { className: "muted", style: { fontSize: 13.5 } }, "We matched your CSV columns to Halo fields. Adjust any that look wrong.")),
            h("div", { style: { padding: "0 24px 8px" } }, cfg.cols.map((c, i) =>
              h("div", { key: c, style: { display: "flex", alignItems: "center", gap: 14, padding: "11px 0", borderTop: i ? "1px solid var(--line-soft)" : "none" } },
                h("span", { className: "mono", style: { fontSize: 12.5, width: 160, color: "var(--ink-600)" } }, c),
                h(Icon, { name: "chevright", style: { color: "var(--ink-400)" } }),
                h("select", { className: "select", style: { flex: 1, maxWidth: 280 }, defaultValue: i }, cfg.fields.map((f, j) => h("option", { key: f, value: j }, f)), h("option", { value: -1 }, "— Skip column —")),
                h("span", { className: "chip chip-ok" }, h(Icon, { name: "check" }), "Matched")))),
            h(WizFoot, { onBack: () => setStep(0), onNext: () => setStep(2), nextLabel: "Validate rows" })),

          step === 2 && h("div", null,
            h("div", { style: { display: "flex", gap: 10, padding: "18px 24px", flexWrap: "wrap" } },
              h(Pill, { tone: "ok", n: counts.ok || 0, label: "Ready" }),
              h(Pill, { tone: "warn", n: counts.warn || 0, label: "Warnings" }),
              h(Pill, { tone: "bad", n: counts.err || 0, label: "Errors — skipped" })),
            h("div", { className: "tablewrap" }, h("table", { className: "data" },
              h("thead", null, h("tr", null, h("th", null, "Row"), cfg.fields.slice(0, 4).map((f) => h("th", { key: f }, f)), h("th", null, "Status"))),
              h("tbody", null, cfg.rows.map((r, i) => { const st = r[r.length - 1];
                return h("tr", { key: i, style: { cursor: "default", opacity: st === "err" ? .6 : 1 } },
                  h("td", { className: "mono", style: { color: "var(--ink-400)" } }, i + 2),
                  r.slice(0, 4).map((v, j) => h("td", { key: j, style: st === "err" && j === 3 ? { color: "var(--bad-fg)", fontWeight: 600 } : null }, v || "—")),
                  h("td", null, st === "ok" ? h("span", { className: "chip chip-ok" }, h("span", { className: "d" }), "Ready")
                    : st === "warn" ? h("span", { className: "chip chip-warn" }, h("span", { className: "d" }), (cfg.warnLabel || "Warning"))
                    : h("span", { className: "chip chip-bad" }, h(Icon, { name: "alert" }), (cfg.errLabel || "Invalid")))); }))),
            h(WizFoot, { onBack: () => setStep(1), onNext: () => setStep(3), nextLabel: "Continue (" + okCount + " rows)" }))),

          step === 3 && h("div", { style: { padding: 28 } },
            h("div", { className: "consequence", style: { background: "var(--info-bg)", borderColor: "var(--info-line)", color: "var(--info-fg)" } },
              h(Icon, { name: "info", style: { fontSize: 18 } }),
              h("div", null, h("b", null, "You're about to import " + okCount + " " + cfg.title + "."), " " + (counts.err || 0) + " rows with errors will be skipped. This creates records and (where applicable) login invites. It's audit-logged and reversible.")),
            committing
              ? h("div", { style: { textAlign: "center", padding: "30px 0" } }, h("div", { className: "skel", style: { height: 8, borderRadius: 99, marginBottom: 14 } }), h("p", { className: "muted", style: { fontSize: 13.5 } }, "Importing " + okCount + " " + cfg.title + "…"))
              : h("div", { style: { display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 18 } },
                  h(Button, { kind: "ghost", onClick: () => setStep(2) }, "Back"),
                  h(Button, { kind: "primary", icon: "check", onClick: commit }, "Import " + okCount + " " + cfg.title))),

          step === 4 && h("div", { style: { padding: 36, textAlign: "center" } },
            h("div", { style: { width: 60, height: 60, borderRadius: 17, background: "var(--ok-bg)", color: "var(--ok-fg)", display: "grid", placeItems: "center", fontSize: 28, margin: "0 auto 16px" } }, h(Icon, { name: "check" })),
            h("h2", { style: { fontSize: 22 } }, "Imported " + okCount + " " + cfg.title),
            h("p", { className: "muted", style: { fontSize: 14, marginTop: 8, maxWidth: 380, marginInline: "auto", lineHeight: 1.55 } }, (counts.err || 0) + " rows were skipped due to errors. You can fix and re-import them anytime."),
            h("div", { style: { display: "flex", gap: 10, justifyContent: "center", marginTop: 22 } },
              h(Button, { kind: "ghost", onClick: () => { setStep(0); setCommitting(false); } }, "Import more"),
              h(Button, { kind: "primary", onClick: onDone }, "Done"))))));
  }
  function WizFoot({ onBack, onNext, nextLabel }) {
    return h("div", { style: { display: "flex", justifyContent: "space-between", padding: "16px 24px", borderTop: "1px solid var(--line)" } },
      h(Button, { kind: "ghost", onClick: onBack }, "Back"), h(Button, { kind: "primary", iconRight: "chevright", onClick: onNext }, nextLabel));
  }
  function Pill({ tone, n, label }) {
    return h("div", { style: { display: "flex", alignItems: "center", gap: 9, padding: "8px 14px", borderRadius: 10, background: `var(--${tone}-bg)`, border: `1px solid var(--${tone}-line)` } },
      h("span", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 18, color: `var(--${tone}-fg)` } }, n),
      h("span", { style: { fontSize: 13, color: `var(--${tone}-fg)`, fontWeight: 600 } }, label));
  }

  window.BulkImport = BulkImport;
})();
