// Live summary panel + final spec card for the Solo spec builder.
//
// The live panel sits in the right rail of the builder page, always visible,
// updating as the user clicks through the wizard. The final spec card is
// what the user lands on at the end — a printable view they can save as PDF.

// The only email address the site shows/sends to, per direct
// instruction. Fallback only; real routing is
// SOLO_BACKEND.inbox.sales / .reseller etc. via submitForm() — the
// Builder's formType "builder" falls back to inbox.sales.
const BUILDER_INBOX = "contactus@solosecure.group";

/* ──────────── Pretty-print helpers ──────────── */
// Map raw config values → human-readable strings for the summary panel.
const labelMaps = {
  platform: { pro: "Pro Tower", ultra: "Ultra Tower" },
  region:   { UK: "United Kingdom", EU: "European Union", US: "North America", GCC: "Middle East / GCC" },
  preset:   { construction: "Construction", highways: "Highways", "oil-gas": "Oil & Gas", utilities: "Utilities", custom: "Custom" },
  brand:    { ajax: "Ajax", dahua: "Dahua", other: "Other" },
  procurement: {
    purchase:   "Outright purchase",
    "lease-24": "Lease — 24 months",
    "lease-36": "Lease — 36 months",
    "lease-48": "Lease — 48 months",
    managed:    "Managed service",
    custom:     "Custom",
  },
  led:      { red: "Red", blue: "Blue", custom: "Custom", none: "None" },
  voltage:  { "110v": "110 V", "230v": "230 V" },
};
const fmt = (group, val) => (val != null && labelMaps[group] && labelMaps[group][val]) || val || "—";
const yes = (v) => (v === true ? "Yes" : v === false ? "No" : "—");

/* ──────────── Live summary panel ────────────
 * Compact card that lives in the right rail of the wizard. Updates as the
 * user clicks through. Shows the current config in a key/value list.
 * Empty slots show "—" rather than vanishing so the height is stable.
 */
function BuilderLiveSummary({ config, quoteRef, locked, stepIdx }) {
  const c = config || {};

  // Trimmed summary — one row per logical area, values condensed.
  // Matches the consolidated 5-step flow: one row per step's net result,
  // so the right rail reads like a clean recap, not a checklist.
  const cameraSummary = c.cameras?.count
    ? `${c.cameras.count} × ${fmt("brand", c.cameras?.brand)}`
    : "—";
  const powerSummary = c.power?.batteries != null
    ? `${c.power.batteries}B / ${c.power?.antennas ?? "—"}A / ${fmt("voltage", c.power?.voltage)}`
    : "—";
  const commsSummary = c.comms?.router != null || c.comms?.switch != null
    ? [c.comms?.router && "Router", c.comms?.switch && "Switch"].filter(Boolean).join(" + ") || "None"
    : "—";
  // LEDs are pre-filled by the application preset on Step 01, but the
  // user doesn't actually choose them until Step 03 (Style & kit) — so
  // the live panel shouldn't reveal a value until they've reached that
  // step, even though config.leds is already populated underneath.
  // stepIdx is undefined on the final summary card (BuilderFinalSummary
  // is a separate component that always shows the real value there).
  const ledsReached = stepIdx == null || stepIdx >= 2;
  const ledSummary = ledsReached && (c.leds?.body || c.leds?.topHat)
    ? `Body ${fmt("led", c.leds?.body)} · Top ${fmt("led", c.leds?.topHat)}`
    : "—";
  const kitItems = Object.entries(c.kit || {})
    .filter(([k, v]) => v && k !== "batteryLooms")
    .length;
  const kitSummary = kitItems > 0 ? `${kitItems} item${kitItems === 1 ? "" : "s"}` : "—";

  const rows = [
    ["Tower",       c.platform ? fmt("platform", c.platform) : "—"],
    ["Region",      fmt("region",   c.region)],
    ["Application", fmt("preset",   c.preset)],
    ["Cameras",     cameraSummary],
    ["Comms",       commsSummary],
    ["Power",       powerSummary],
    ["LEDs",        ledSummary],
    ["Kit",         kitSummary],
    ["Procurement", fmt("procurement", c.procurement)],
  ];

  return (
    <aside style={{
      background: "var(--surface)",
      border: "1px solid var(--line)",
      padding: "28px 28px 30px",
      position: "sticky", top: 132,
      // Keep the panel under the nav while scrolling on tall steps.
      maxHeight: "calc(100vh - 152px)",
      overflow: "auto",
    }}>
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "baseline",
        marginBottom: 22, paddingBottom: 14, borderBottom: "1px solid var(--line)",
      }}>
        <Eyebrow>Live spec</Eyebrow>
        {quoteRef && (
          <div style={{
            fontFamily: "var(--font-body)", fontSize: 11,
            letterSpacing: "0.18em", textTransform: "uppercase",
            color: "var(--fg-dim)", fontWeight: 500,
          }}>{quoteRef}</div>
        )}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: "10px 14px" }}>
        {rows.map(([label, value]) => (
          <React.Fragment key={label}>
            <span style={{
              fontFamily: "var(--font-body)", fontSize: 11,
              letterSpacing: "0.14em", color: "var(--fg-dim)",
              textTransform: "uppercase", paddingTop: 3, fontWeight: 500,
            }}>{label}</span>
            <span style={{
              fontFamily: "var(--font-body)", fontSize: 13.5,
              color: value === "—" ? "var(--fg-faint)" : "var(--fg)",
              fontWeight: value === "—" ? 400 : 500,
            }}>{value}</span>
          </React.Fragment>
        ))}
      </div>

      {locked && (
        <div style={{
          marginTop: 24, paddingTop: 18, borderTop: "1px solid var(--line)",
          fontFamily: "var(--font-body)", fontSize: 12,
          color: "var(--fg-soft)", lineHeight: 1.55,
        }}>
          Final spec, quote reference and submission unlock once you complete <strong style={{ color: "var(--fg)" }}>Step 09 — Your details</strong>.
        </div>
      )}
    </aside>
  );
}

/* ──────────── Final summary card ────────────
 * Full spec rendered as a printable card. The user lands here on Step 10
 * after providing their details on Step 09. Three actions: email to sales,
 * print/save as PDF, request callback (set in the contact step).
 */
function BuilderFinalSummary({ config, quoteRef, onSubmit, onPrint, submitted, submitting, submitResult }) {
  const c = config || {};
  const includedKit = Object.entries(c.kit || {})
    .filter(([_, v]) => !!v && !["batteryLooms"].includes(_))
    .map(([k]) => ({
      wheelsToFeet: "Base wheels to feet",
      drillSocket:  "19 mm drill socket",
      impactGun:    "Impact gun",
      drillBits:    "Drill bit set",
      sounder:      "Sounder / horn",
    }[k]))
    .filter(Boolean);

  return (
    <div style={{
      background: "var(--bg)", border: "1px solid var(--line-strong)",
      padding: "44px 48px 48px",
    }}>
      {/* Header */}
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "flex-end",
        marginBottom: 32, paddingBottom: 24, borderBottom: "1px solid var(--line)",
        gap: 24, flexWrap: "wrap",
      }}>
        <div>
          <Eyebrow style={{ marginBottom: 14 }}>Solo spec sheet</Eyebrow>
          <h3 style={{
            fontFamily: "var(--font-display)", fontWeight: 700,
            fontSize: "clamp(28px, 3.4vw, 44px)", lineHeight: 1,
            letterSpacing: "0.005em", textTransform: "uppercase",
            margin: 0, color: "var(--fg)",
          }}>{fmt("platform", c.platform)}</h3>
        </div>
        <div style={{ textAlign: "right" }}>
          <div style={{
            fontFamily: "var(--font-body)", fontSize: 11,
            letterSpacing: "0.18em", color: "var(--fg-dim)",
            textTransform: "uppercase", marginBottom: 4, fontWeight: 500,
          }}>Quote reference</div>
          <div style={{
            fontFamily: "var(--font-display)", fontWeight: 700,
            fontSize: 22, letterSpacing: "0.005em",
            color: "var(--fg)",
          }}>{quoteRef}</div>
        </div>
      </div>

      {/* Spec body — 3 columns of grouped fields */}
      <div style={{
        display: "grid", gridTemplateColumns: "repeat(3, 1fr)",
        gap: 40, marginBottom: 36,
      }}>
        <SpecGroup title="Platform & region">
          <SpecRow l="Platform"  v={fmt("platform", c.platform)} />
          <SpecRow l="Region"    v={fmt("region",   c.region)} />
          <SpecRow l="Preset"    v={fmt("preset",   c.preset)} />
          <SpecRow l="Model"     v={fmt("procurement", c.procurement)} />
        </SpecGroup>

        <SpecGroup title="Cameras & comms">
          <SpecRow l="Cameras"   v={c.cameras?.count ? `${c.cameras.count} channel${c.cameras.count > 1 ? "s" : ""}` : "—"} />
          <SpecRow l="Brand"     v={fmt("brand", c.cameras?.brand)} />
          <SpecRow l="Router"    v={yes(c.comms?.router)} />
          <SpecRow l="Switch"    v={yes(c.comms?.switch)} />
        </SpecGroup>

        <SpecGroup title="Power">
          <SpecRow l="Batteries" v={c.power?.batteries ?? "—"} />
          <SpecRow l="Antennas"  v={c.power?.antennas ?? "—"} />
          <SpecRow l="Voltage"   v={fmt("voltage", c.power?.voltage)} />
        </SpecGroup>

        <SpecGroup title="Visual identity">
          <SpecRow l="Body LEDs"     v={fmt("led", c.leds?.body)} />
          <SpecRow l="Top hat LEDs"  v={fmt("led", c.leds?.topHat)} />
        </SpecGroup>

        <SpecGroup title="Deployment kit">
          {includedKit.length === 0 ? (
            <SpecRow l="Kit" v="None selected" />
          ) : (
            includedKit.map((label) => <SpecRow key={label} l="·" v={label} />)
          )}
          {c.kit?.batteryLooms ? (
            <SpecRow l="Looms" v={`${c.kit.batteryLooms} × Battery loom`} />
          ) : null}
        </SpecGroup>

        <SpecGroup title="Requester">
          <SpecRow l="Name"     v={c.contact?.name || "—"} />
          <SpecRow l="Email"    v={c.contact?.email || "—"} />
          <SpecRow l="Company"  v={c.contact?.company || "—"} />
          <SpecRow l="Website"  v={c.contact?.website || "—"} />
          <SpecRow l="Phone"    v={c.contact?.phone || "—"} />
          <SpecRow l="Callback" v={yes(c.contact?.requestCallback)} />
        </SpecGroup>
      </div>

      {c.contact?.brief && (
        <div style={{
          background: "var(--surface)", border: "1px solid var(--line)",
          padding: "20px 24px", marginBottom: 36,
        }}>
          <Eyebrow style={{ marginBottom: 10 }}>Brief from requester</Eyebrow>
          <p style={{
            fontFamily: "var(--font-body)", fontSize: 14.5,
            lineHeight: 1.6, color: "var(--fg)", margin: 0, whiteSpace: "pre-wrap",
          }}>{c.contact.brief}</p>
        </div>
      )}

      {/* Footer — three actions */}
      <div style={{
        borderTop: "1px solid var(--line)",
        paddingTop: 32,
        display: "flex", gap: 12, flexWrap: "wrap",
        // Hide actions when printed
      }} className="builder-actions-no-print">
        {submitted ? (
          <div style={{
            background: "var(--surface)", border: "1px solid var(--fg)",
            padding: "16px 22px",
            fontFamily: "var(--font-body)", fontSize: 13.5,
            color: "var(--fg)",
          }}>
            {/* Real outcome, not an unconditional success message.
                submitResult.emailed === false means the submission was
                captured (see routes/contact.ts) but the confirmation
                email itself didn't go out yet — still true progress,
                worded honestly. */}
            {submitResult && submitResult.ok && submitResult.emailed === false
              ? `✓ Spec ${quoteRef} saved. ${submitResult.message || "Our team will still see it and be in touch."}`
              : `✓ Spec sent to Solo sales. We'll respond within one working day.`}
          </div>
        ) : submitResult && submitResult.ok === false ? (
          <div style={{ display: "flex", flexDirection: "column", gap: 10, width: "100%" }}>
            <div style={{
              background: "var(--surface)", border: "1px solid var(--fg)",
              padding: "14px 18px",
              fontFamily: "var(--font-body)", fontSize: 13,
              color: "var(--fg)",
            }}>
              Something went wrong submitting your spec ({submitResult.message || "unknown error"}). Please try again, or email it directly to {BUILDER_INBOX}.
            </div>
            <Button primary onClick={onSubmit}>Try again →</Button>
          </div>
        ) : (
          <Button primary onClick={onSubmit} disabled={submitting}>
            {submitting ? "Sending…" : "Submit spec to Solo sales →"}
          </Button>
        )}
        <Button onClick={onPrint}>Print / Save as PDF →</Button>
      </div>

      <p style={{
        fontFamily: "var(--font-body)", fontSize: 11,
        color: "var(--fg-faint)", letterSpacing: "0.14em",
        marginTop: 18, marginBottom: 0, textTransform: "uppercase",
      }}>
        // Submission is sent securely to {BUILDER_INBOX}
      </p>
    </div>
  );
}

/* ──────────── Mini bits ──────────── */
function SpecGroup({ title, children }) {
  return (
    <div>
      <Eyebrow style={{ marginBottom: 14, color: "var(--fg)" }}>{title}</Eyebrow>
      <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: "8px 14px" }}>
        {children}
      </div>
    </div>
  );
}
function SpecRow({ l, v }) {
  return (
    <>
      <span style={{
        fontFamily: "var(--font-body)", fontSize: 11,
        letterSpacing: "0.14em", color: "var(--fg-dim)",
        textTransform: "uppercase", paddingTop: 2, fontWeight: 500,
      }}>{l}</span>
      <span style={{
        fontFamily: "var(--font-body)", fontSize: 14,
        color: "var(--fg)", fontWeight: 500,
      }}>{v}</span>
    </>
  );
}

// Generate a friendly quote reference like Q-2026-742891.
// Stable for this session — saved to localStorage and reused on refresh.
function generateQuoteRef() {
  const existing = localStorage.getItem("solo-builder-quote-ref");
  if (existing) return existing;
  const year = new Date().getFullYear();
  const n = Math.floor(100000 + Math.random() * 900000);
  const ref = `Q-${year}-${n}`;
  localStorage.setItem("solo-builder-quote-ref", ref);
  return ref;
}

function clearQuoteRef() {
  localStorage.removeItem("solo-builder-quote-ref");
}

// Build the email-body string for the mailto submission.
function buildSpecEmailBody(config, quoteRef) {
  const c = config || {};
  const out = [];
  out.push(`Solo spec — quote reference: ${quoteRef}`);
  out.push("");
  out.push("─── Platform & region ───");
  out.push(`Platform:    ${fmt("platform", c.platform)}`);
  out.push(`Region:      ${fmt("region", c.region)}`);
  out.push(`Preset:      ${fmt("preset", c.preset)}`);
  out.push(`Procurement: ${fmt("procurement", c.procurement)}`);
  out.push("");
  out.push("─── Cameras & comms ───");
  out.push(`Cameras:     ${c.cameras?.count || 0} × ${fmt("brand", c.cameras?.brand)}`);
  out.push(`Router:      ${yes(c.comms?.router)}`);
  out.push(`Switch:      ${yes(c.comms?.switch)}`);
  out.push("");
  out.push("─── Power ───");
  out.push(`Batteries:   ${c.power?.batteries ?? "—"}`);
  out.push(`Antennas:    ${c.power?.antennas ?? "—"}`);
  out.push(`Voltage:     ${fmt("voltage", c.power?.voltage)}`);
  out.push("");
  out.push("─── Visual identity ───");
  out.push(`Body LEDs:     ${fmt("led", c.leds?.body)}`);
  out.push(`Top hat LEDs:  ${fmt("led", c.leds?.topHat)}`);
  out.push("");
  out.push("─── Deployment kit ───");
  out.push(`Wheels to feet:  ${yes(c.kit?.wheelsToFeet)}`);
  out.push(`Drill socket:    ${yes(c.kit?.drillSocket)}`);
  out.push(`Impact gun:      ${yes(c.kit?.impactGun)}`);
  out.push(`Drill bits:      ${yes(c.kit?.drillBits)}`);
  out.push(`Sounder / horn:  ${yes(c.kit?.sounder)}`);
  out.push(`Battery looms:   ${c.kit?.batteryLooms ?? 0}`);
  out.push("");
  out.push("─── Requester ───");
  out.push(`Name:     ${c.contact?.name || "—"}`);
  out.push(`Email:    ${c.contact?.email || "—"}`);
  out.push(`Company:  ${c.contact?.company || "—"}`);
  out.push(`Website:  ${c.contact?.website || "—"}`);
  out.push(`Phone:    ${c.contact?.phone || "—"}`);
  out.push(`Callback: ${yes(c.contact?.requestCallback)}`);
  if (c.contact?.brief) {
    out.push("");
    out.push("─── Brief from requester ───");
    out.push(c.contact.brief);
  }
  out.push("");
  out.push("---");
  out.push(`Submitted from solosecure.tech · spec builder · ${quoteRef}`);
  return out.join("\n");
}

Object.assign(window, {
  BuilderLiveSummary, BuilderFinalSummary,
  generateQuoteRef, clearQuoteRef, buildSpecEmailBody, BUILDER_INBOX,
});
