// Perdura — shared workbook uploader (Stage 6). File picker → validate (dry-run)
// → inline tie-out report → import. Used by the onboarding wizard (Step 4) and the
// standalone /data-import page so the upload + report UX is identical everywhere.
// Generic: no industry/customer-conditional logic.
//
// Props: { companyId, onImported(report), forceReseed (default true), compact }
// window.WorkbookUploader

(function () {
  const R = window.React;
  if (!R) return;
  const { useState, useRef } = R;

  const fmtNum = (n) => (n == null ? "—" : Number(n).toLocaleString());

  function GateRow({ label, pass, detail }) {
    return R.createElement("div", { style: { display: "flex", alignItems: "center", gap: 8, fontSize: 12.5, padding: "3px 0" } },
      R.createElement("span", { style: { color: pass ? "#10b981" : "#b7791f", fontWeight: 700 } }, pass ? "✓" : "⚠"),
      R.createElement("span", { style: { color: "var(--text-2)" } }, label, " — ", pass ? "balanced" : detail));
  }

  function Report({ report }) {
    if (!report) return null;
    const c = report.counts || {};
    const g = report.gates || {};
    const am = report.auto_mapped || {};
    const failed = report.status === "validation_failed";
    if (failed) {
      return R.createElement("div", { style: { marginTop: 12, padding: "12px 14px", background: "rgba(239,68,68,0.06)", border: "1px solid rgba(239,68,68,0.25)", borderRadius: 8, fontSize: 13, color: "var(--danger, #c0392b)", lineHeight: 1.5 } },
        R.createElement("strong", null, "Validation failed — nothing was imported. "),
        report.detail || report.error || "The workbook could not be parsed.");
    }
    const jeFail = g.je_balance && !g.je_balance.pass;
    const tbFail = g.gl_to_tb && !g.gl_to_tb.pass;
    return R.createElement("div", { style: { marginTop: 12 } },
      R.createElement("div", { style: { display: "flex", gap: 16, flexWrap: "wrap", fontSize: 12.5, color: "var(--text-2)" } },
        ["accounts", "gl_transactions", "ar_aging", "ap_aging", "trial_balance_accounts"].map((k) =>
          R.createElement("span", { key: k }, k.replace(/_/g, " "), ": ", R.createElement("strong", { style: { color: "var(--text-1)" } }, fmtNum(c[k]))))),
      R.createElement("div", { style: { marginTop: 8 } },
        g.je_balance ? R.createElement(GateRow, { label: "JE balance (debits = credits)", pass: g.je_balance.pass, detail: `${(g.je_balance.offenders || []).length} unbalanced JE(s)` }) : null,
        g.gl_to_tb ? R.createElement(GateRow, { label: "GL ties to Trial Balance", pass: g.gl_to_tb.pass, detail: `${(g.gl_to_tb.diffs || []).length} account(s) off` }) : null),
      am.unmapped ? R.createElement("div", { style: { marginTop: 6, fontSize: 12, color: "var(--text-3)" } },
        `${am.unmapped} unmapped account(s): ${(am.unmapped_account_nos || []).slice(0, 8).join(", ")}${am.unmapped > 8 ? "…" : ""}`) : null,
      (jeFail || tbFail) ? R.createElement("div", { style: { marginTop: 8, fontSize: 12, color: "#b7791f" } },
        "Tie-outs didn't fully reconcile. You can import anyway and fix later, or correct the workbook and re-upload — nothing is dropped silently.") : null,
      report.data_range ? R.createElement("div", { style: { marginTop: 6, fontSize: 11.5, color: "var(--text-3)" } }, `Data range: ${report.data_range.min || "—"} → ${report.data_range.max || "—"}`) : null);
  }

  function WorkbookUploader(props) {
    const companyId = props.companyId;
    const forceReseed = props.forceReseed !== false;
    const [phase, setPhase] = useState("idle"); // idle | validating | validated | importing | imported | error
    const [report, setReport] = useState(null);
    const [fileObj, setFileObj] = useState(null);
    const [error, setError] = useState("");
    const inputRef = useRef(null);

    async function onPick(file) {
      if (!file) return;
      setFileObj(file); setError(""); setReport(null); setPhase("validating");
      try {
        const r = await window.PerduraIngest.uploadWorkbook(file, { companyId, validateOnly: true });
        setReport(r);
        setPhase(r.status === "validation_failed" ? "error" : "validated");
      } catch (e) { setError(String(e.message || e)); setPhase("error"); }
    }

    async function doImport() {
      if (!fileObj) return;
      setPhase("importing"); setError("");
      try {
        const r = await window.PerduraIngest.uploadWorkbook(fileObj, { companyId, forceReseed });
        setReport(r); setPhase("imported");
        if (props.onImported) props.onImported(r);
      } catch (e) { setError(String(e.message || e)); setPhase("error"); }
    }

    const busy = phase === "validating" || phase === "importing";
    const canImport = phase === "validated" || (phase === "error" && report && report.status !== "validation_failed");

    return R.createElement("div", null,
      R.createElement("div", {
        onClick: () => !busy && inputRef.current && inputRef.current.click(),
        style: {
          border: "1.5px dashed var(--border, #d8dee6)", borderRadius: 10, padding: props.compact ? "16px" : "24px",
          textAlign: "center", cursor: busy ? "wait" : "pointer", background: "var(--surface-2, #f6f8fb)",
        },
      },
        R.createElement("div", { style: { fontSize: 13.5, fontWeight: 600, color: "var(--text-1)" } },
          phase === "validating" ? "Validating…" : phase === "importing" ? "Importing…" : (fileObj ? fileObj.name : "Drop or choose your Excel workbook")),
        R.createElement("div", { style: { fontSize: 11.5, color: "var(--text-3)", marginTop: 4 } },
          "Required tabs: Company Profile, Chart of Accounts, GL Detail. .xlsx up to 100MB."),
        R.createElement("input", { ref: inputRef, type: "file", accept: ".xlsx,.xls", style: { display: "none" },
          onChange: (e) => { const f = e.target.files && e.target.files[0]; if (f) onPick(f); e.target.value = ""; } }),
        R.createElement("button", { className: "pc-btn pc-btn-ghost", style: { marginTop: 10, fontSize: 12.5 }, disabled: busy }, "Choose file")),

      error && phase === "error" && !report ? R.createElement("div", { style: { marginTop: 12, color: "var(--danger, #c0392b)", fontSize: 13 } }, error) : null,
      R.createElement(Report, { report }),

      canImport ? R.createElement("div", { style: { marginTop: 12, display: "flex", gap: 10, alignItems: "center" } },
        R.createElement("button", { className: "pc-btn pc-btn-primary", style: { fontSize: 13 }, disabled: busy, onClick: doImport },
          busy ? "Importing…" : "Import this workbook"),
        R.createElement("span", { style: { fontSize: 11.5, color: "var(--text-3)" } }, "Re-import replaces this company's data (no duplicates).")) : null,

      phase === "imported" ? R.createElement("div", { style: { marginTop: 12, padding: "10px 14px", background: "rgba(16,185,129,0.08)", border: "1px solid rgba(16,185,129,0.25)", borderRadius: 8, fontSize: 13, color: "var(--text-1)" } },
        "✓ Imported. ",
        report && report.counts ? `${fmtNum(report.counts.gl_transactions)} GL rows, ${fmtNum(report.counts.accounts)} accounts.` : "") : null);
  }

  window.WorkbookUploader = WorkbookUploader;
})();
