// Solo spec builder — step components (v2, consolidated 5-step flow).
//
// Each step receives { config, setConfig }. Visual language is intentionally
// minimal: one headline per step, no eyebrows, no body paragraphs, no card
// descriptions. Choice cards are short titles only. The live summary
// panel on the right does the heavy lifting for orientation.

/* ──────────── Shared step primitives ──────────── */

function StepHeader({ title, hint }) {
  return (
    <div style={{ marginBottom: 36 }}>
      <h2 style={{
        fontFamily: "var(--font-display)", fontWeight: 700,
        fontSize: "clamp(28px, 3.4vw, 44px)", lineHeight: 1.02,
        letterSpacing: "-0.005em", textTransform: "uppercase",
        margin: "0 0 12px", color: "var(--fg)",
      }}>{title}</h2>
      {hint && (
        <p style={{
          fontFamily: "var(--font-body)", fontSize: 14,
          lineHeight: 1.55, color: "var(--fg-soft)",
          margin: 0, maxWidth: 620,
        }}>{hint}</p>
      )}
    </div>
  );
}

// Title-only choice card — no body, no eyebrow, no footnote.
function ChoiceCard({ selected, onClick, title, small }) {
  return (
    <button
      type="button"
      onClick={onClick}
      style={{
        textAlign: "left",
        background: selected ? "var(--fg)" : "var(--bg)",
        color: selected ? "var(--bg)" : "var(--fg)",
        border: `1px solid ${selected ? "var(--fg)" : "var(--line)"}`,
        padding: small ? "16px 18px" : "20px 22px",
        cursor: "pointer",
        fontFamily: "var(--font-display)", fontWeight: 700,
        fontSize: small ? 14 : 16, letterSpacing: "0.005em",
        textTransform: "uppercase",
        transition: "background 120ms, color 120ms, border-color 120ms",
        minHeight: small ? 56 : 64,
        display: "flex", alignItems: "center",
      }}
    >
      {title}
    </button>
  );
}

// Row of small pill buttons for numeric / quick options.
function PillRow({ options, value, onChange }) {
  return (
    <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
      {options.map((opt) => {
        const v = typeof opt === "object" ? opt.value : opt;
        const label = typeof opt === "object" ? opt.label : opt;
        const isSel = v === value;
        return (
          <button
            key={String(v)}
            type="button"
            onClick={() => onChange(v)}
            style={{
              background: isSel ? "var(--fg)" : "var(--bg)",
              color: isSel ? "var(--bg)" : "var(--fg)",
              border: `1px solid ${isSel ? "var(--fg)" : "var(--line)"}`,
              padding: "10px 16px",
              cursor: "pointer",
              fontFamily: "var(--font-display)", fontWeight: 700,
              fontSize: 13, letterSpacing: "0.04em",
              textTransform: "uppercase",
              minWidth: 48, textAlign: "center",
              transition: "background 120ms, color 120ms",
            }}>{label}</button>
        );
      })}
    </div>
  );
}

// Compact label + control group with consistent spacing.
function FieldGroup({ label, children, hint }) {
  return (
    <div style={{ marginBottom: 24 }}>
      <div style={{
        fontFamily: "var(--font-body)", fontSize: 11,
        letterSpacing: "0.18em", color: "var(--fg-dim)",
        textTransform: "uppercase", marginBottom: 10, fontWeight: 500,
      }}>{label}</div>
      {children}
      {hint && (
        <div style={{
          fontFamily: "var(--font-body)", fontSize: 11.5,
          color: "var(--fg-faint)", marginTop: 6, lineHeight: 1.5,
        }}>{hint}</div>
      )}
    </div>
  );
}

// Two-column row helper for grouping related field groups side by side.
function TwoCol({ children }) {
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))",
      gap: 24,
    }}>{children}</div>
  );
}

/* ════════════════════ STEP 01 — TOWER ════════════════════
 * Combines: platform + region + application preset
 * (3 old steps → 1)
 */
function StepTower({ config, setConfig }) {
  return (
    <>
      <StepHeader
        title="Your tower."
        hint="Pick the platform, region and application — defaults apply for the rest of the spec, which you can fine-tune on the next steps."
      />

      <FieldGroup label="Platform">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          <ChoiceCard
            selected={config.platform === "pro"}
            onClick={() => setConfig({ platform: "pro" })}
            title="Pro Tower"
          />
          <ChoiceCard
            selected={config.platform === "ultra"}
            onClick={() => setConfig({ platform: "ultra" })}
            title="Ultra Tower"
          />
        </div>
      </FieldGroup>

      <FieldGroup label="Region">
        <div style={{
          display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))",
          gap: 8,
        }}>
          {[
            { val: "UK",  label: "United Kingdom" },
            { val: "EU",  label: "European Union" },
            { val: "US",  label: "North America" },
            { val: "GCC", label: "Middle East / GCC" },
          ].map((r) => (
            <ChoiceCard
              key={r.val}
              small
              selected={config.region === r.val}
              onClick={() => setConfig({ region: r.val })}
              title={r.label}
            />
          ))}
        </div>
      </FieldGroup>

      <FieldGroup label="Application">
        <div style={{
          display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))",
          gap: 8,
        }}>
          {[
            { val: "construction", label: "Construction" },
            { val: "highways",     label: "Highways" },
            { val: "oil-gas",      label: "Oil & Gas" },
            { val: "utilities",    label: "Utilities" },
            { val: "custom",       label: "Custom" },
          ].map((p) => (
            <ChoiceCard
              key={p.val}
              small
              selected={config.preset === p.val}
              onClick={() => setConfig({ preset: p.val })}
              title={p.label}
            />
          ))}
        </div>
      </FieldGroup>
    </>
  );
}

/* ════════════════════ STEP 02 — SPEC ════════════════════
 * Combines: cameras + connectivity + power
 * (3 old steps → 1)
 */
function StepSpec({ config, setConfig }) {
  const isNA = config.region === "US";
  const isProTower = config.platform === "pro";
  // Battery looms always mirror battery count.
  const setBatteries = (n) => setConfig({
    power: { ...config.power, batteries: n },
    kit:   { ...config.kit,   batteryLooms: n },
  });
  // Pro Tower's chassis only accommodates up to 3 battery bays — Ultra
  // Tower keeps the full 1-6 range.
  const batteryOptions = isProTower ? [1, 2, 3] : [1, 2, 3, 4, 5, 6];
  // Dahua is not NDAA-compliant, so it's excluded from the North America
  // camera brand options.
  const brandOptions = [
    { val: "ajax",  label: "Ajax" },
    { val: "dahua", label: "Dahua" },
    { val: "other", label: "Other" },
  ].filter((b) => !(isNA && b.val === "dahua"));
  // 240 V (230 V) mains is not offered in North America.
  const voltageOptions = [
    { value: "110v", label: "110 V" },
    { value: "230v", label: "230 V" },
  ].filter((v) => !(isNA && v.value === "230v"));
  return (
    <>
      <StepHeader
        title="Spec."
        hint="Cameras, network and power. Defaults from your application preset are pre-filled — change anything that doesn't fit."
      />

      <TwoCol>
        <FieldGroup label="Cameras">
          <PillRow
            options={[1, 2, 3, 4]}
            value={config.cameras?.count}
            onChange={(v) => setConfig({ cameras: { ...config.cameras, count: v } })}
          />
        </FieldGroup>

        <FieldGroup
          label="Camera brand"
          hint={isNA ? "Dahua is not offered in North America (NDAA compliance)." : null}
        >
          <div style={{ display: "flex", gap: 6 }}>
            {brandOptions.map((b) => (
              <ChoiceCard
                key={b.val}
                small
                selected={config.cameras?.brand === b.val}
                onClick={() => setConfig({ cameras: { ...config.cameras, brand: b.val } })}
                title={b.label}
              />
            ))}
          </div>
        </FieldGroup>
      </TwoCol>

      <TwoCol>
        <FieldGroup label="Router">
          <PillRow
            options={[{ value: true, label: "Include" }, { value: false, label: "None" }]}
            value={config.comms?.router}
            onChange={(v) => setConfig({ comms: { ...config.comms, router: v } })}
          />
        </FieldGroup>

        <FieldGroup label="Network switch">
          <PillRow
            options={[{ value: true, label: "Include" }, { value: false, label: "None" }]}
            value={config.comms?.switch}
            onChange={(v) => setConfig({ comms: { ...config.comms, switch: v } })}
          />
        </FieldGroup>
      </TwoCol>

      <TwoCol>
        <FieldGroup
          label="Batteries"
          hint={isProTower ? "Pro Tower supports up to 3 batteries. Looms auto-mirror battery count." : "Looms auto-mirror battery count."}
        >
          <PillRow
            options={batteryOptions}
            value={config.power?.batteries}
            onChange={setBatteries}
          />
        </FieldGroup>

        <FieldGroup label="Antennas">
          <PillRow
            options={[1, 2]}
            value={config.power?.antennas}
            onChange={(v) => setConfig({ power: { ...config.power, antennas: v } })}
          />
        </FieldGroup>
      </TwoCol>

      <FieldGroup
        label="Mains voltage"
        hint={isNA ? "240 V mains is not available in North America." : null}
      >
        <PillRow
          options={voltageOptions}
          value={config.power?.voltage}
          onChange={(v) => setConfig({ power: { ...config.power, voltage: v } })}
        />
      </FieldGroup>
    </>
  );
}

/* ════════════════════ STEP 03 — STYLE & KIT ════════════════════
 * Combines: LEDs + deployment kit
 * (2 old steps → 1)
 */
function StepStyleKit({ config, setConfig }) {
  const isNA = config.region === "US";
  const ledOptions = [
    { val: "red",    label: "Red" },
    { val: "blue",   label: "Blue" },
    { val: "custom", label: "Custom" },
    { val: "none",   label: "None" },
  ];
  // Base wheels-to-feet (not yet sourceable in NA — may enable later),
  // impact gun (liability) and drill bit set (specs pending) are not
  // offered for North America builds.
  const kitItems = [
    { key: "wheelsToFeet", label: "Base wheels to feet" },
    { key: "drillSocket",  label: "19 mm drill socket" },
    { key: "impactGun",    label: "Impact gun" },
    { key: "drillBits",    label: "Drill bit set" },
    { key: "sounder",      label: "Sounder / horn" },
  ].filter((item) => !(isNA && ["wheelsToFeet", "impactGun", "drillBits"].includes(item.key)));
  const looms = config.kit?.batteryLooms ?? config.power?.batteries ?? 0;

  return (
    <>
      <StepHeader
        title="Style & kit."
        hint="LED treatment and optional deployment accessories. Skip what you don't need."
      />

      <TwoCol>
        <FieldGroup label="Body LEDs">
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            {ledOptions.map((o) => (
              <ChoiceCard
                key={o.val}
                small
                selected={config.leds?.body === o.val}
                onClick={() => setConfig({ leds: { ...config.leds, body: o.val } })}
                title={o.label}
              />
            ))}
          </div>
        </FieldGroup>

        <FieldGroup label="Top hat LEDs">
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            {ledOptions.map((o) => (
              <ChoiceCard
                key={o.val}
                small
                selected={config.leds?.topHat === o.val}
                onClick={() => setConfig({ leds: { ...config.leds, topHat: o.val } })}
                title={o.label}
              />
            ))}
          </div>
        </FieldGroup>
      </TwoCol>

      <FieldGroup
        label="Deployment kit (optional)"
        hint={[
          looms ? `Battery looms mirror battery count: ${looms} loom${looms === 1 ? "" : "s"}.` : null,
          isNA ? "Base wheels to feet, impact gun and drill bit set are not yet offered in North America." : null,
        ].filter(Boolean).join(" ") || null}
      >
        <div style={{
          display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))",
          gap: 8,
        }}>
          {kitItems.map((item) => (
            <ChoiceCard
              key={item.key}
              small
              selected={!!config.kit?.[item.key]}
              onClick={() => setConfig({
                kit: { ...config.kit, [item.key]: !config.kit?.[item.key] },
              })}
              title={item.label}
            />
          ))}
        </div>
      </FieldGroup>
    </>
  );
}

/* ════════════════════ STEP 04 — PROCUREMENT ════════════════════
 * (1 old step, unchanged in scope but tightened visually)
 */
function StepProcurement({ config, setConfig }) {
  const isNA = config.region === "US";
  // Leasing, managed service and custom procurement are not yet available
  // in North America — only outright purchase is offered there for now.
  const options = [
    { val: "purchase",   label: "Outright purchase" },
    { val: "lease-24",   label: "Lease · 24 months" },
    { val: "lease-36",   label: "Lease · 36 months" },
    { val: "lease-48",   label: "Lease · 48 months" },
    { val: "managed",    label: "Managed service" },
    { val: "custom",     label: "Custom" },
  ].filter((o) => !(isNA && ["lease-24", "lease-36", "lease-48", "managed", "custom"].includes(o.val)));
  return (
    <>
      <StepHeader
        title="Procurement."
        hint={isNA
          ? "How would you like to acquire the unit? We can enable leasing, managed service and custom options in North America in the future."
          : "How would you like to acquire the unit? Sales will quote on this basis."}
      />
      <div style={{
        display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))",
        gap: 8,
      }}>
        {options.map((o) => (
          <ChoiceCard
            key={o.val}
            selected={config.procurement === o.val}
            onClick={() => setConfig({ procurement: o.val })}
            title={o.label}
          />
        ))}
      </div>
    </>
  );
}

/* ════════════════════ STEP 05 — DETAILS (gates summary) ════════════════════
 * Trimmed: removed verbose hints, just the form.
 */
function StepDetails({ config, setConfig }) {
  const isNA = config.region === "US";
  // Default phone placeholder mirrors the selected region's dialling code
  // rather than always suggesting +44 (which is wrong for North America
  // and every non-UK region).
  const phonePlaceholder = {
    UK: "+44 …",
    EU: "+31 …",
    US: "+1 …",
    GCC: "+971 …",
  }[config.region] || "+1 …";
  return (
    <>
      <StepHeader
        title="Your details."
        hint="Name, email, company and phone are required so we can prepare your quote."
      />

      <TwoCol>
        <FieldGroup label="Full name *">
          <input
            type="text" required
            value={config.contact?.name || ""}
            onChange={(e) => setConfig({ contact: { ...config.contact, name: e.target.value } })}
            placeholder="Jane Operator"
            style={inputStyle}
          />
        </FieldGroup>

        <FieldGroup label="Work email *">
          <input
            type="email" required
            value={config.contact?.email || ""}
            onChange={(e) => setConfig({ contact: { ...config.contact, email: e.target.value } })}
            placeholder="jane@example.com"
            style={inputStyle}
          />
        </FieldGroup>
      </TwoCol>

      <TwoCol>
        <FieldGroup label="Company *">
          <input
            type="text" required
            value={config.contact?.company || ""}
            onChange={(e) => setConfig({ contact: { ...config.contact, company: e.target.value } })}
            placeholder="Acme Security Ltd"
            style={inputStyle}
          />
        </FieldGroup>

        <FieldGroup label="Phone *">
          <input
            type="tel" required
            value={config.contact?.phone || ""}
            onChange={(e) => setConfig({ contact: { ...config.contact, phone: e.target.value } })}
            placeholder={phonePlaceholder}
            style={inputStyle}
          />
        </FieldGroup>
      </TwoCol>

      <FieldGroup label="Company website *">
        <input
          type="url" required
          value={config.contact?.website || ""}
          onChange={(e) => setConfig({ contact: { ...config.contact, website: e.target.value } })}
          placeholder="https://acmesecurity.com"
          style={inputStyle}
        />
      </FieldGroup>

      <FieldGroup label="Brief (optional)">
        <textarea
          rows={3}
          value={config.contact?.brief || ""}
          onChange={(e) => setConfig({ contact: { ...config.contact, brief: e.target.value } })}
          placeholder="Site details, timing, or anything else not captured above."
          style={{ ...inputStyle, resize: "vertical" }}
        />
      </FieldGroup>

      <label style={{
        display: "flex", gap: 12, alignItems: "flex-start",
        cursor: "pointer", marginTop: 0, marginBottom: 0,
        fontFamily: "var(--font-body)", fontSize: 13,
        lineHeight: 1.5, color: "var(--fg)",
      }}>
        <input
          type="checkbox"
          checked={!!config.contact?.requestCallback}
          onChange={(e) => setConfig({ contact: { ...config.contact, requestCallback: e.target.checked } })}
          style={{
            width: 18, height: 18, accentColor: "var(--fg)",
            margin: 0, marginTop: 2, flexShrink: 0,
          }}
        />
        <span>Request a callback from Solo sales.</span>
      </label>
    </>
  );
}

/* ────────────────────────────────────────────────────────
 * Backwards-compat exports — the previous flow had 9 step components.
 * The new builder-page.jsx wiring will use only the 5 below, but we
 * keep the old names as aliases so other code that referenced them
 * doesn't break. The page state machine wires up just the new five.
 * ──────────────────────────────────────────────────────── */
const StepPlatform     = StepTower;
const StepRegion       = StepTower;
const StepPreset       = StepTower;
const StepCameras      = StepSpec;
const StepConnectivity = StepSpec;
const StepLEDs         = StepStyleKit;
const StepKit          = StepStyleKit;

const inputStyle = {
  width: "100%", boxSizing: "border-box",
  background: "var(--bg)", border: "1px solid var(--line)",
  color: "var(--fg)", fontFamily: "var(--font-body)",
  fontSize: 15, padding: "12px 14px", outline: "none",
};

Object.assign(window, {
  // New 5-step flow
  StepTower, StepSpec, StepStyleKit, StepProcurement, StepDetails,
  // Legacy aliases (in case anything else references them)
  StepPlatform, StepRegion, StepPreset, StepCameras, StepConnectivity, StepLEDs, StepKit,
});
