/* Configurator step — sticky kiln preview + option panels. Three layout variants. */

function Configurator({ config, setConfig, onBack, onNext, layout = 'sticky', volumeItem = 'mug' }) {
  const model = window.LE200.MODELS.find(m => m.id === config.size);
  const data = window.LE200;
  const price = computePrice(config, data);
  const lead = leadTime(config, data);
  const [openDoor, setOpenDoor] = useState(false);

  if (!model) return null;

  const optionGroups = Object.entries(data.OPTIONS).filter(
    ([, group]) => !group.onlyFor || group.onlyFor.includes(config.size)
  );

  return (
    <div className="page">
      <main>
        <section className="container" style={{ paddingTop: 32, paddingBottom: 16 }}>
          <SectionHeader
            tag={`[02] · Step 2 of 4 · Configure your ${model.sku}`}
            title="Spec the kiln to your studio."
            sub="Every choice changes the unit you'll receive. The preview to the right updates as you go — watch the door hinge swap, the panel mirror, the footprint grow."
            action={<button className="btn btn-ghost" onClick={onBack}>← Change size</button>}
          />
        </section>

        {layout === 'sticky' && (
          <section className="container" style={{ paddingBottom: 60 }}>
            <div style={{
              display: 'grid',
              gridTemplateColumns: 'minmax(0, 1.05fr) minmax(0, 1fr)',
              gap: 48,
              alignItems: 'start',
            }}>
              {/* LEFT — options */}
              <div>
                {optionGroups.map(([gid, group]) => (
                  <OptionGroup
                    key={gid}
                    gid={gid}
                    group={group}
                    selected={config[gid]}
                    onSelect={(id) => setConfig({ [gid]: id })}
                  />
                ))}
                <UpgradesGroup config={config} setConfig={setConfig} />
              </div>

              {/* RIGHT — sticky preview */}
              <div style={{ position: 'sticky', top: 80 }}>
                <PreviewPanel
                  model={model}
                  config={config}
                  openDoor={openDoor}
                  setOpenDoor={setOpenDoor}
                  price={price}
                  lead={lead}
                  volumeItem={volumeItem}
                  onNext={onNext}
                />
              </div>
            </div>
          </section>
        )}

        {layout === 'single' && (
          <section className="container" style={{ paddingBottom: 60 }}>
            <div style={{ marginBottom: 40 }}>
              <PreviewPanel
                model={model}
                config={config}
                openDoor={openDoor}
                setOpenDoor={setOpenDoor}
                price={price}
                lead={lead}
                volumeItem={volumeItem}
                onNext={onNext}
                horizontal
              />
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 32 }}>
              {optionGroups.map(([gid, group]) => (
                <OptionGroup
                  key={gid}
                  gid={gid}
                  group={group}
                  selected={config[gid]}
                  onSelect={(id) => setConfig({ [gid]: id })}
                />
              ))}
              <div style={{ gridColumn: '1 / -1' }}>
                <UpgradesGroup config={config} setConfig={setConfig} />
              </div>
            </div>
          </section>
        )}

        {layout === 'step' && (
          <StepByStep
            optionGroups={optionGroups}
            config={config}
            setConfig={setConfig}
            model={model}
            openDoor={openDoor}
            setOpenDoor={setOpenDoor}
            price={price}
            lead={lead}
            volumeItem={volumeItem}
            onNext={onNext}
          />
        )}
      </main>
      <Footer />
    </div>
  );
}

// ─────────────────────────────────────────────────────────── OptionGroup
function OptionGroup({ gid, group, selected, onSelect }) {
  return (
    <div style={{ marginBottom: 36 }}>
      <div className="rule" style={{ paddingTop: 16, marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'baseline' }}>
          <span className="mono upper" style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.12em' }}>[{gid.toUpperCase()}]</span>
          <h3 className="display" style={{ margin: 0, fontSize: 22 }}>{group.label}</h3>
        </div>
        {selected && (
          <span className="mono" style={{ fontSize: 11, color: 'var(--accent-deep)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>
            ✓ {group.choices.find(c => c.id === selected)?.label}
          </span>
        )}
      </div>
      {group.help && (
        <p style={{ margin: '0 0 16px', color: 'var(--ink-2)', fontSize: 13, lineHeight: 1.5, maxWidth: 560 }}>
          {group.help}
        </p>
      )}
      <div style={{ display: 'grid', gridTemplateColumns: group.choices.length > 2 ? '1fr' : '1fr 1fr', gap: 10 }}>
        {group.choices.map(c => (
          <Choice
            key={c.id}
            active={selected === c.id}
            onClick={() => onSelect(c.id)}
            label={c.label}
            sub={c.sub}
            delta={c.delta}
          />
        ))}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────── UpgradesGroup
function UpgradesGroup({ config, setConfig }) {
  const data = window.LE200;
  const toggleUpgrade = (id) => {
    const upgrades = { ...(config.upgrades || {}) };
    upgrades[id] = !upgrades[id];
    if (id === 'hood' && !upgrades.hood) upgrades.hoodSS = false;
    setConfig({ upgrades });
  };
  return (
    <div style={{ marginBottom: 36 }}>
      <div className="rule" style={{ paddingTop: 16, marginBottom: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'baseline' }}>
          <span className="mono upper" style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.12em' }}>[UPGRADES]</span>
          <h3 className="display" style={{ margin: 0, fontSize: 22 }}>Optional upgrades</h3>
        </div>
        <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>
          {Object.values(config.upgrades || {}).filter(Boolean).length} selected
        </span>
      </div>
      <p style={{ margin: '0 0 16px', color: 'var(--ink-2)', fontSize: 13, lineHeight: 1.5, maxWidth: 560 }}>
        Each one bolts onto the standard build. Prices scale with kiln size.
      </p>
      <div style={{ display: 'grid', gap: 10 }}>
        {data.UPGRADES.map(up => {
          const active = !!config.upgrades?.[up.id];
          const disabled = up.requires && !config.upgrades?.[up.requires];
          const price = up.pricing[config.size] || 0;
          return (
            <label key={up.id} className="choice" aria-checked={active}
                   style={{ cursor: disabled ? 'not-allowed' : 'pointer', opacity: disabled ? 0.4 : 1 }}>
              {active && <span className="stripe" />}
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
                <input
                  type="checkbox"
                  checked={active}
                  disabled={disabled}
                  onChange={() => !disabled && toggleUpgrade(up.id)}
                  style={{
                    width: 16, height: 16, marginTop: 2,
                    accentColor: 'var(--accent-deep)',
                  }}
                />
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 600, fontSize: 15 }}>{up.label}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4, lineHeight: 1.4 }}>{up.sub}{up.requires && <span style={{ color: 'var(--warn)', marginLeft: 6 }}>· requires {up.requires}</span>}</div>
                </div>
                <span className="mono" style={{ fontSize: 12, color: 'var(--ink-2)', whiteSpace: 'nowrap' }}>+{fmtUSD(price)}</span>
              </div>
            </label>
          );
        })}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────── PreviewPanel (the sticky right column)
function PreviewPanel({ model, config, openDoor, setOpenDoor, price, lead, volumeItem, onNext, horizontal = false }) {
  return (
    <div style={{
      border: '1px solid var(--rule)',
      background: 'var(--field-2)',
      padding: 0,
      position: 'relative',
    }}>
      <Crosshairs />

      {/* Header strip */}
      <div style={{
        padding: '14px 20px',
        borderBottom: '1px solid var(--rule)',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        background: 'var(--field)',
      }}>
        <div className="mono upper" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--ink-3)' }}>
          Live preview
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          <button
            onClick={() => setOpenDoor(false)}
            className="chip"
            style={{ cursor: 'pointer', background: !openDoor ? 'var(--ink)' : 'transparent', color: !openDoor ? 'var(--field)' : 'var(--ink-2)', border: '1px solid ' + (!openDoor ? 'var(--ink)' : 'color-mix(in oklab, var(--ink), transparent 70%)') }}
          >
            Closed
          </button>
          <button
            onClick={() => setOpenDoor(true)}
            disabled={!model.open}
            className="chip"
            style={{ cursor: model.open ? 'pointer' : 'not-allowed', background: openDoor ? 'var(--ink)' : 'transparent', color: openDoor ? 'var(--field)' : 'var(--ink-2)', border: '1px solid ' + (openDoor ? 'var(--ink)' : 'color-mix(in oklab, var(--ink), transparent 70%)'), opacity: model.open ? 1 : 0.5 }}
          >
            Door open
          </button>
        </div>
      </div>

      <div style={{ padding: horizontal ? '24px 32px' : '0 16px', display: horizontal ? 'grid' : 'block', gridTemplateColumns: horizontal ? '1fr 1fr' : undefined, gap: horizontal ? 32 : 0 }}>
        <DimensionedKiln model={model} config={config} openDoor={openDoor} />

        <div style={{ padding: horizontal ? 0 : '0 24px 20px' }}>
          {/* Config summary string */}
          <div style={{
            margin: '4px 0 16px',
            padding: '12px 14px',
            background: 'var(--field)',
            border: '1px solid color-mix(in oklab, var(--ink), transparent 80%)',
            fontFamily: 'var(--font-mono)', fontSize: 11.5,
            color: 'var(--ink-2)', lineHeight: 1.55,
          }}>
            <span style={{ color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.1em', fontSize: 10 }}>[CONFIG] </span>
            <span style={{ color: 'var(--ink)' }}>{model.sku}</span> · {config.airflow} · {config.gas === 'lpg' ? 'propane' : 'natural gas'} · {config.insulation === 'b23' ? '2,300°F brick' : config.insulation === 'b26' ? '2,600°F brick' : 'fiber'} · {config.door}-hinge · {config.controls}-panel{config.doorStyle === 'guillotine' ? ' · guillotine' : ''}{config.cart === 'cart' ? ' · cart' : ''}
          </div>

          {/* Volume viz */}
          <VolumeViz model={model} item={volumeItem} />

          <div style={{ marginTop: 16 }}>
            <RunningTotal
              subtotal={price.subtotal}
              crating={price.crating}
              deposit={price.deposit}
              lead={lead}
              configured
            />
          </div>

          <button className="btn btn-accent btn-arrow" style={{ width: '100%', justifyContent: 'center', marginTop: 16 }} onClick={onNext}>
            Continue to fit check
          </button>
          <div className="mono" style={{ marginTop: 10, fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.08em', textAlign: 'center', textTransform: 'uppercase' }}>
            No payment yet. Deposit collected at checkout.
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────── StepByStep variant
function StepByStep({ optionGroups, config, setConfig, model, openDoor, setOpenDoor, price, lead, volumeItem, onNext }) {
  const [idx, setIdx] = useState(0);
  const groups = [...optionGroups, ['__upgrades__', { label: 'Upgrades' }]];
  const total = groups.length;
  const isUpgrade = groups[idx]?.[0] === '__upgrades__';
  const [gid, group] = groups[idx] || [];

  return (
    <section className="container" style={{ paddingBottom: 60 }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1.05fr 1fr', gap: 48, alignItems: 'start' }}>
        <div>
          {/* Step header */}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
            <div className="mono upper" style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.12em' }}>
              Decision {String(idx + 1).padStart(2, '0')} of {String(total).padStart(2, '0')}
            </div>
            <div style={{ display: 'flex', gap: 4 }}>
              {groups.map((_, i) => (
                <span key={i} style={{
                  width: 24, height: 3,
                  background: i <= idx ? 'var(--accent)' : 'color-mix(in oklab, var(--ink), transparent 80%)',
                }} />
              ))}
            </div>
          </div>

          <div style={{ minHeight: 480 }}>
            {isUpgrade ? (
              <UpgradesGroup config={config} setConfig={setConfig} />
            ) : (
              <OptionGroup
                gid={gid}
                group={group}
                selected={config[gid]}
                onSelect={(id) => setConfig({ [gid]: id })}
              />
            )}
          </div>

          <div className="rule" style={{ paddingTop: 16, display: 'flex', justifyContent: 'space-between' }}>
            <button className="btn btn-ghost" onClick={() => setIdx(Math.max(0, idx - 1))} disabled={idx === 0}>← Back</button>
            {idx < total - 1 ? (
              <button className="btn btn-primary btn-arrow" onClick={() => setIdx(idx + 1)}>Next decision</button>
            ) : (
              <button className="btn btn-accent btn-arrow" onClick={onNext}>Continue to fit check</button>
            )}
          </div>
        </div>

        <div style={{ position: 'sticky', top: 80 }}>
          <PreviewPanel
            model={model} config={config} openDoor={openDoor} setOpenDoor={setOpenDoor}
            price={price} lead={lead} volumeItem={volumeItem} onNext={onNext}
          />
        </div>
      </div>
    </section>
  );
}

window.Configurator = Configurator;
