// Solo spec builder — main page.
//
// Stepped wizard à la Fyrfly. State is owned here; each step is a thin
// component that receives { config, setConfig }. Live summary panel on
// the right rail. Lead-gated: user must complete Step 09 (their details)
// before the final summary card unlocks.
//
// Output: mailto email to sales + on-screen spec card + print-as-PDF.

// Consolidated 5-step flow (was 9). The new steps roll multiple decisions
// into a single screen each — much less back-and-forth, less visual chrome.
const BUILDER_STEPS = [
  { id: "tower",       title: "Tower",        Component: () => window.StepTower },
  { id: "spec",        title: "Spec",         Component: () => window.StepSpec },
  { id: "style-kit",   title: "Style & kit",  Component: () => window.StepStyleKit },
  { id: "procurement", title: "Procurement",  Component: () => window.StepProcurement },
  { id: "details",     title: "Your details", Component: () => window.StepDetails },
  // Final summary step (no Component — rendered directly in this file)
  { id: "summary",     title: "Summary",      Component: null },
];

// Sensible defaults per application preset, used when the user picks one.
const PRESET_DEFAULTS = {
  construction: {
    cameras: { count: 4, brand: "dahua" },
    comms:   { router: true, switch: true },
    power:   { batteries: 4, antennas: 2, voltage: "230v" },
    leds:    { body: "blue", topHat: "blue" },
    kit:     { wheelsToFeet: true, drillSocket: true, impactGun: true, drillBits: true, sounder: true, batteryLooms: 4 },
  },
  highways: {
    cameras: { count: 4, brand: "dahua" },
    comms:   { router: true, switch: true },
    power:   { batteries: 6, antennas: 2, voltage: "230v" },
    leds:    { body: "red", topHat: "red" },
    kit:     { wheelsToFeet: true, drillSocket: true, impactGun: true, drillBits: true, sounder: true, batteryLooms: 6 },
  },
  "oil-gas": {
    cameras: { count: 4, brand: "dahua" },
    comms:   { router: true, switch: true },
    power:   { batteries: 6, antennas: 2, voltage: "230v" },
    leds:    { body: "none", topHat: "none" },
    kit:     { wheelsToFeet: true, drillSocket: false, impactGun: false, drillBits: false, sounder: true, batteryLooms: 6 },
  },
  utilities: {
    cameras: { count: 4, brand: "ajax" },
    comms:   { router: true, switch: true },
    power:   { batteries: 6, antennas: 2, voltage: "230v" },
    leds:    { body: "blue", topHat: "blue" },
    kit:     { wheelsToFeet: true, drillSocket: true, impactGun: true, drillBits: true, sounder: true, batteryLooms: 6 },
  },
  custom: {},  // no defaults — user chooses everything from scratch
};

function BuilderPage({ onNavigate }) {
  // Initial config — defaults to nothing; user picks each option.
  const [config, setConfigRaw] = useState(() => {
    // Allow deep-link from product page: ?builder-product=pro|ultra
    const params = new URLSearchParams(window.location.search);
    const platform = params.get("builder-product");
    return platform === "pro" || platform === "ultra" ? { platform } : {};
  });
  const [stepIdx, setStepIdx] = useState(0);
  const [submitted, setSubmitted] = useState(false);
  // Real outcome of the last submitForm() call (see contact-form.jsx for
  // the same pattern) — used so BuilderFinalSummary can show honest
  // copy instead of always claiming the spec was sent.
  const [submitResult, setSubmitResult] = useState(null);
  const [submitting, setSubmitting] = useState(false);
  const [quoteRef, setQuoteRef] = useState("");

  // North America (region "US") carries a set of hard restrictions that
  // don't apply elsewhere: no 230 V mains, no Dahua cameras (NDAA), no
  // base-wheels/impact-gun/drill-bit-set kit items, and only outright
  // purchase (no leasing/managed/custom) is offered yet. Pro Tower is
  // separately capped at 3 batteries everywhere (chassis limit), not just
  // in NA. Since PRESET_DEFAULTS pre-fills 230V/Dahua/up-to-6-batteries
  // regardless of region, any config that violates these rules — whether
  // just-applied from a preset or left over from before the user changed
  // region/platform — needs to be corrected. This runs after every merge
  // so the config is never left in an invalid state for the current
  // region/platform, however the user reached it.
  const sanitizeForRegionAndPlatform = (cfg) => {
    const next = { ...cfg };
    const isNA = next.region === "US";
    const isProTower = next.platform === "pro";

    if (isNA && next.power?.voltage === "230v") {
      next.power = { ...next.power, voltage: "110v" };
    }
    if (isNA && next.cameras?.brand === "dahua") {
      next.cameras = { ...next.cameras, brand: "ajax" };
    }
    if (isNA && next.kit) {
      const cleanedKit = { ...next.kit };
      delete cleanedKit.wheelsToFeet;
      delete cleanedKit.impactGun;
      delete cleanedKit.drillBits;
      next.kit = cleanedKit;
    }
    if (isNA && ["lease-24", "lease-36", "lease-48", "managed", "custom"].includes(next.procurement)) {
      next.procurement = "purchase";
    }
    if (isProTower && next.power?.batteries != null && next.power.batteries > 3) {
      next.power = { ...next.power, batteries: 3 };
      next.kit = { ...(next.kit || {}), batteryLooms: 3 };
    }
    return next;
  };

  // setConfig merges partial updates. Applies preset defaults when the user
  // picks a preset on Step 03.
  const setConfig = (patch) => {
    setConfigRaw((prev) => {
      let next = { ...prev, ...patch };
      // Merge nested objects rather than overwriting them.
      for (const key of ["cameras", "comms", "power", "leds", "kit", "contact"]) {
        if (patch[key] != null) {
          next[key] = { ...(prev[key] || {}), ...patch[key] };
        }
      }
      // Apply preset defaults — only when the preset changes.
      if (patch.preset && patch.preset !== prev.preset) {
        const defaults = PRESET_DEFAULTS[patch.preset] || {};
        next = {
          ...next,
          cameras: { ...defaults.cameras, ...(next.cameras || {}) },
          comms:   { ...defaults.comms,   ...(next.comms   || {}) },
          power:   { ...defaults.power,   ...(next.power   || {}) },
          leds:    { ...defaults.leds,    ...(next.leds    || {}) },
          kit:     { ...defaults.kit,     ...(next.kit     || {}) },
        };
        // Mirror battery looms to battery count on preset application
        if (next.power?.batteries != null) {
          next.kit = { ...(next.kit || {}), batteryLooms: next.power.batteries };
        }
      }
      return sanitizeForRegionAndPlatform(next);
    });
  };

  // Validate the current step. Disabled "Next" button if invalid.
  // 5-step flow indexes:
  //   0 Tower (platform + region + preset)
  //   1 Spec  (cameras + comms + power)
  //   2 Style & kit (LEDs + kit — kit fully optional, LEDs required since defaults pre-fill)
  //   3 Procurement
  //   4 Your details (gates the summary)
  const detailsStep = BUILDER_STEPS.length - 2; // index of details step
  const stepValid = (i) => {
    const c = config;
    switch (i) {
      case 0: return !!c.platform && !!c.region && !!c.preset;
      case 1: return !!c.cameras?.count && !!c.cameras?.brand
                  && c.comms?.router != null && c.comms?.switch != null
                  && c.power?.batteries != null && c.power?.antennas != null
                  && c.power?.voltage != null;
      case 2: return !!c.leds?.body && !!c.leds?.topHat;
      case 3: return !!c.procurement;
      case 4: return !!(c.contact?.name && c.contact?.email && c.contact?.company && c.contact?.phone && c.contact?.website);
      default: return true;
    }
  };

  // Move to the summary step (last in BUILDER_STEPS). Generate the quote ref
  // when we unlock the summary — keyed on the user completing the details step.
  const goSummary = () => {
    setQuoteRef(generateQuoteRef());
    setStepIdx(BUILDER_STEPS.length - 1);
  };

  const goNext = () => {
    if (!stepValid(stepIdx)) return;
    if (stepIdx === detailsStep) { goSummary(); return; }
    setStepIdx((i) => Math.min(BUILDER_STEPS.length - 1, i + 1));
  };
  const goPrev = () => setStepIdx((i) => Math.max(0, i - 1));

  const handleSubmit = async () => {
    const helpers = window.SOLO_BACKEND_HELPERS;
    const platformName = (config.platform === "pro" ? "Pro Tower" : "Ultra Tower");
    const subjectBits = [
      platformName,
      config.preset || "",
      config.contact?.requestCallback ? "REQUEST CALLBACK" : "",
    ].filter(Boolean);
    const subject = subjectBits.join(" · ");

    if (helpers && helpers.submitForm) {
      // Flatten the nested config into a single fields object for the
      // generic payload contract. The mailto formatter handles labelling.
      const fields = {
        platform:    platformName,
        region:      config.region,
        preset:      config.preset,
        procurement: config.procurement,
        cameras:     config.cameras?.count ? `${config.cameras.count} × ${config.cameras.brand || ""}` : undefined,
        router:      config.comms?.router,
        switch:      config.comms?.switch,
        batteries:   config.power?.batteries,
        antennas:    config.power?.antennas,
        voltage:     config.power?.voltage,
        bodyLEDs:    config.leds?.body,
        topHatLEDs:  config.leds?.topHat,
        kit:         Object.entries(config.kit || {}).filter(([_, v]) => v).map(([k]) => k).join(", "),
        name:        config.contact?.name,
        email:       config.contact?.email,
        company:     config.contact?.company,
        website:     config.contact?.website,
        phone:       config.contact?.phone,
        brief:       config.contact?.brief,
        requestCallback: config.contact?.requestCallback ? "Yes" : "No",
      };
      setSubmitting(true);
      const result = await helpers.submitForm({
        formType: "builder",
        subject,
        reference: quoteRef,
        fields,
      });
      setSubmitting(false);
      setSubmitResult(result);
      // Only claim success when the backend actually confirms it —
      // previously this always ran regardless of the (discarded)
      // result, so a broken backend still showed "Spec sent".
      if (result && result.ok) setSubmitted(true);
    } else {
      // Defensive fallback if solo-backend.js failed to load.
      const body = buildSpecEmailBody(config, quoteRef);
      const url = `mailto:${BUILDER_INBOX}?subject=${encodeURIComponent(`[SPEC] ${quoteRef} · ${subject}`)}&body=${encodeURIComponent(body)}`;
      window.location.href = url;
      setSubmitResult(null);
      setSubmitted(true);
    }
  };

  const handlePrint = () => {
    window.print();
  };

  const handleReset = () => {
    clearQuoteRef();
    setConfigRaw({});
    setStepIdx(0);
    setSubmitted(false);
    setSubmitResult(null);
    setQuoteRef("");
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const isSummary = stepIdx === BUILDER_STEPS.length - 1;
  const currentStep = BUILDER_STEPS[stepIdx];
  const ActiveStep = currentStep.Component ? currentStep.Component() : null;

  return (
    <>
      {/* Print styles — hide everything except the spec card when printing.
          Also bake in good defaults for the PDF (no chrome, black-on-white). */}
      <style>{`
        @media print {
          body { background: #fff !important; }
          header, footer, .builder-no-print { display: none !important; }
          .builder-spec-print { box-shadow: none !important; border: 1px solid #000 !important; }
          .builder-actions-no-print { display: none !important; }
        }
      `}</style>

      {/* HERO — quieter; takes up less vertical space so the wizard is the focus */}
      <section className="builder-no-print" style={{
        padding: "60px 36px 32px", borderBottom: "1px solid var(--line)",
      }}>
        <div style={{ maxWidth: 1480, margin: "0 auto" }}>
          <Eyebrow style={{ marginBottom: 18 }}>Spec builder</Eyebrow>
          <h1 style={{
            fontFamily: "var(--font-display)", fontWeight: 700,
            fontSize: "clamp(40px, 5vw, 80px)", lineHeight: 1,
            letterSpacing: "-0.005em", textTransform: "uppercase",
            margin: "0 0 14px", color: "var(--fg)",
          }}>
            Configure your tower.
          </h1>
          <p style={{
            fontFamily: "var(--font-body)", fontSize: 15,
            lineHeight: 1.55, color: "var(--fg-soft)", maxWidth: 720, margin: 0,
          }}>
            Five short steps. We'll quote pricing tailored to your region after you submit.
          </p>
        </div>
      </section>

      {/* WIZARD BODY */}
      <section style={{ padding: "32px 36px 100px" }}>
        <div style={{ maxWidth: 1480, margin: "0 auto" }}>
          {/* When the user is on summary, show a centred wide spec card.
              Otherwise, two-column layout: steps + live summary panel. */}
          {isSummary ? (
            <div className="builder-spec-print">
              <BuilderFinalSummary
                config={config}
                quoteRef={quoteRef}
                onSubmit={handleSubmit}
                onPrint={handlePrint}
                submitted={submitted}
                submitting={submitting}
                submitResult={submitResult}
              />
              <div className="builder-actions-no-print" style={{
                marginTop: 36, display: "flex", gap: 12, justifyContent: "space-between",
                flexWrap: "wrap", borderTop: "1px solid var(--line)", paddingTop: 32,
              }}>
                <Button onClick={() => setStepIdx(detailsStep)}>← Edit your details</Button>
                <Button onClick={handleReset}>Start a new spec</Button>
              </div>
            </div>
          ) : (
            <div style={{
              display: "grid",
              gridTemplateColumns: "minmax(0, 180px) minmax(0, 1fr) minmax(0, 320px)",
              gap: 36,
              alignItems: "start",
            }} className="builder-no-print">

              {/* ── Step rail ── */}
              <nav>
                <ol style={{ listStyle: "none", padding: 0, margin: 0 }}>
                  {BUILDER_STEPS.slice(0, BUILDER_STEPS.length - 1).map((s, i) => {
                    const active = i === stepIdx;
                    const done   = i < stepIdx && stepValid(i);
                    const disabled = i > stepIdx && !stepValid(stepIdx);
                    return (
                      <li key={s.id}>
                        <button
                          type="button"
                          onClick={() => { if (!disabled) setStepIdx(i); }}
                          style={{
                            display: "block", width: "100%", textAlign: "left",
                            background: "none", border: "none",
                            borderLeft: active ? "2px solid var(--fg)" : "2px solid var(--line)",
                            padding: "10px 0 10px 18px",
                            cursor: disabled ? "default" : "pointer",
                            opacity: disabled ? 0.4 : 1,
                            fontFamily: "var(--font-body)",
                          }}>
                          <div style={{
                            fontSize: 10, letterSpacing: "0.22em",
                            textTransform: "uppercase", color: "var(--fg-dim)",
                            fontWeight: 500, marginBottom: 4,
                          }}>
                            {done ? "✓" : `Step ${String(i + 1).padStart(2, "0")}`}
                          </div>
                          <div style={{
                            fontFamily: "var(--font-display)", fontWeight: 700,
                            fontSize: 14, letterSpacing: "0.005em",
                            textTransform: "uppercase",
                            color: active ? "var(--fg)" : "var(--fg-soft)",
                          }}>{s.title}</div>
                        </button>
                      </li>
                    );
                  })}
                </ol>

                {/* Reset link */}
                <button
                  type="button"
                  onClick={handleReset}
                  style={{
                    background: "none", border: "none", padding: "20px 0 0 20px",
                    cursor: "pointer",
                    fontFamily: "var(--font-body)", fontSize: 11,
                    letterSpacing: "0.16em", textTransform: "uppercase",
                    color: "var(--fg-faint)", fontWeight: 500,
                  }}>Reset spec</button>
              </nav>

              {/* ── Step content ── */}
              <div>
                <div style={{
                  background: "var(--bg)", border: "1px solid var(--line)",
                  padding: "40px 44px 40px",
                }}>
                  {ActiveStep ? <ActiveStep config={config} setConfig={setConfig} /> : null}
                </div>

                {/* Step navigation footer */}
                <div style={{
                  display: "flex", justifyContent: "space-between", alignItems: "center",
                  marginTop: 24,
                }}>
                  <Button onClick={goPrev}>
                    ← Previous
                  </Button>
                  <div style={{
                    fontFamily: "var(--font-body)", fontSize: 12,
                    letterSpacing: "0.16em", textTransform: "uppercase",
                    color: "var(--fg-dim)", fontWeight: 500,
                  }}>
                    Step {stepIdx + 1} of {BUILDER_STEPS.length - 1}
                  </div>
                  {stepIdx < detailsStep ? (
                    <button
                      type="button"
                      onClick={goNext}
                      disabled={!stepValid(stepIdx)}
                      style={{
                        background: stepValid(stepIdx) ? "var(--fg)" : "var(--line-strong)",
                        color: "var(--bg)",
                        border: `1px solid ${stepValid(stepIdx) ? "var(--fg)" : "var(--line-strong)"}`,
                        padding: "14px 26px",
                        cursor: stepValid(stepIdx) ? "pointer" : "not-allowed",
                        fontFamily: "var(--font-body)",
                        fontSize: 12, fontWeight: 500,
                        letterSpacing: "0.18em", textTransform: "uppercase",
                      }}>Next →</button>
                  ) : (
                    <button
                      type="button"
                      onClick={goSummary}
                      disabled={!stepValid(stepIdx)}
                      style={{
                        background: stepValid(stepIdx) ? "var(--fg)" : "var(--line-strong)",
                        color: "var(--bg)",
                        border: `1px solid ${stepValid(stepIdx) ? "var(--fg)" : "var(--line-strong)"}`,
                        padding: "14px 26px",
                        cursor: stepValid(stepIdx) ? "pointer" : "not-allowed",
                        fontFamily: "var(--font-body)",
                        fontSize: 12, fontWeight: 500,
                        letterSpacing: "0.18em", textTransform: "uppercase",
                      }}>View your spec →</button>
                  )}
                </div>
              </div>

              {/* ── Live summary ── */}
              <BuilderLiveSummary
                config={config}
                quoteRef={quoteRef}
                locked={!quoteRef}
                stepIdx={stepIdx}
              />
            </div>
          )}
        </div>
      </section>
    </>
  );
}

Object.assign(window, { BuilderPage });
