/* Fit check — will the configured kiln fit your studio? */

function FitCheck({ config, setConfig, onBack, onNext }) {
  const model = window.LE200.MODELS.find(m => m.id === config.size);
  const studio = config.studio || {};
  const setStudio = (patch) => setConfig({ studio: { ...studio, ...patch } });

  const [w, d, h] = model.footprint;
  const downDraft = config.airflow === 'downdraft';
  const depth = downDraft ? d + 6 : d;
  const minGas = config.gas === 'ng' ? 6 : 14;

  // Checks
  const checks = [
    {
      id: 'ceiling',
      label: 'Ceiling height',
      ok: (studio.ceiling || 0) >= h + 24,
      need: `Need ${h + 24}" above floor (kiln ${h}" + 24" vent clearance)`,
      have: studio.ceiling ? studio.ceiling + '"' : '—',
    },
    {
      id: 'doorway',
      label: 'Delivery doorway',
      ok: (studio.doorway || 0) >= w + 4,
      need: `Need ${w + 4}" min for delivery (kiln ${w}" + 4" pallet jack)`,
      have: studio.doorway ? studio.doorway + '"' : '—',
    },
    {
      id: 'wallL',
      label: 'Left wall clearance',
      ok: (studio.wallL || 0) >= 18,
      need: `18" minimum for service access`,
      have: studio.wallL ? studio.wallL + '"' : '—',
    },
    {
      id: 'wallR',
      label: 'Right wall clearance',
      ok: (studio.wallR || 0) >= (config.controls === 'right' ? 24 : 18),
      need: `${config.controls === 'right' ? 24 : 18}" minimum (${config.controls === 'right' ? 'panel + gas valves on this side' : 'service access'})`,
      have: studio.wallR ? studio.wallR + '"' : '—',
    },
    {
      id: 'wallB',
      label: 'Wall behind',
      ok: (studio.wallB || 0) >= 12,
      need: `12" minimum from back of kiln`,
      have: studio.wallB ? studio.wallB + '"' : '—',
    },
    {
      id: 'swing',
      label: 'Door swing',
      ok: (config.door === 'left' ? (studio.wallL || 0) : (studio.wallR || 0)) >= w * 0.85,
      need: `${Math.round(w * 0.85)}" door swing radius on the ${config.door} side`,
      have: (config.door === 'left' ? studio.wallL : studio.wallR) ? (config.door === 'left' ? studio.wallL : studio.wallR) + '"' : '—',
    },
    {
      id: 'gas',
      label: `Gas supply (${config.gas === 'ng' ? 'natural gas' : 'propane'})`,
      ok: (studio.gasPressure || 0) >= minGas,
      need: `Min ${minGas}" WC at the burner manifold`,
      have: studio.gasPressure ? studio.gasPressure + '" WC' : '—',
    },
    {
      id: 'power',
      label: 'Power for ignition & controls',
      ok: studio.power === '120v' || studio.power === '240v',
      need: '120V outlet within 6 ft of control panel',
      have: studio.power ? studio.power : '—',
    },
  ];
  const passing = checks.filter(c => c.ok).length;
  const failing = checks.filter(c => !c.ok).length;
  const allClear = passing === checks.length;

  return (
    <div className="page">
      <main>
        <section className="container" style={{ paddingTop: 32, paddingBottom: 16 }}>
          <SectionHeader
            tag="[03] · Step 3 of 4 · Fit check"
            title="Will it work in your studio?"
            sub="Punch in the dimensions of where the kiln will live. We'll flag conflicts before you commit. None of these answers are stored — they're for the floor plan."
            action={<button className="btn btn-ghost" onClick={onBack}>← Back to configure</button>}
          />
        </section>

        <section className="container" style={{ paddingBottom: 60 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 48, alignItems: 'start' }}>
            {/* LEFT — inputs */}
            <div>
              <div style={{
                padding: 24,
                border: '1px solid var(--rule)',
                background: 'var(--field-2)',
                position: 'relative',
              }}>
                <Crosshairs />

                <div className="mono upper" style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.12em', marginBottom: 4 }}>
                  [Space] Studio dimensions
                </div>
                <h3 className="display" style={{ margin: '0 0 20px', fontSize: 22 }}>Tell us about the install spot</h3>

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                  <Field label="Ceiling height" unit="in" v={studio.ceiling} onChange={(v) => setStudio({ ceiling: v })} suggest={h + 30} />
                  <Field label="Delivery doorway" unit="in" v={studio.doorway} onChange={(v) => setStudio({ doorway: v })} suggest={w + 8} />
                  <Field label="Left wall clearance" unit="in" v={studio.wallL} onChange={(v) => setStudio({ wallL: v })} suggest={config.door === 'left' ? 48 : 24} />
                  <Field label="Right wall clearance" unit="in" v={studio.wallR} onChange={(v) => setStudio({ wallR: v })} suggest={config.door === 'right' ? 48 : 24} />
                  <Field label="Wall behind" unit="in" v={studio.wallB} onChange={(v) => setStudio({ wallB: v })} suggest={18} />
                  <Field label="Gas pressure at manifold" unit={'"WC'} v={studio.gasPressure} onChange={(v) => setStudio({ gasPressure: v })} suggest={minGas + 2} />
                </div>

                <div style={{ marginTop: 24 }}>
                  <label className="mono upper" style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.12em' }}>Power available</label>
                  <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
                    {[
                      { id: '120v', label: '120V standard outlet' },
                      { id: '240v', label: '240V available too' },
                      { id: 'none', label: 'No power within 6 ft' },
                    ].map(o => (
                      <button
                        key={o.id}
                        onClick={() => setStudio({ power: o.id })}
                        className="chip"
                        style={{
                          cursor: 'pointer',
                          background: studio.power === o.id ? 'var(--ink)' : 'transparent',
                          color: studio.power === o.id ? 'var(--field)' : 'var(--ink-2)',
                          borderColor: studio.power === o.id ? 'var(--ink)' : 'color-mix(in oklab, var(--ink), transparent 70%)',
                        }}
                      >
                        {o.label}
                      </button>
                    ))}
                  </div>
                </div>

                <div style={{ marginTop: 24, padding: 14, background: 'var(--field)', border: '1px dashed color-mix(in oklab, var(--ink), transparent 70%)', fontFamily: 'var(--font-mono)', fontSize: 11.5, color: 'var(--ink-2)', lineHeight: 1.5 }}>
                  <strong style={{ color: 'var(--ink)' }}>Kiln dimensions:</strong> W {w}" × D {depth}"{downDraft && ' (downdraft +6")'} × H {h}"<br />
                  <strong style={{ color: 'var(--ink)' }}>Recommended footprint:</strong> {w + 36}" × {depth + 30}" of clear floor.<br />
                  <strong style={{ color: 'var(--ink)' }}>Ship weight:</strong> {model.shipWeight.toLocaleString()} lb (plus {config.upgrades?.furniture ? '~290 lb furniture' : 'no furniture kit'}).
                </div>
              </div>

              {/* Checks */}
              <div style={{
                marginTop: 24,
                border: '1px solid var(--rule)',
                background: 'var(--field)',
                padding: 24,
                position: 'relative',
              }}>
                <Crosshairs />
                <div className="flex between items-baseline" style={{ marginBottom: 16 }}>
                  <div>
                    <div className="mono upper" style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.12em' }}>[Result] Pre-install checklist</div>
                    <h3 className="display" style={{ margin: '4px 0 0', fontSize: 22 }}>
                      {passing} of {checks.length} clear
                    </h3>
                  </div>
                  <div className={`chip ${allClear ? 'ok' : failing > 0 ? 'warn' : ''}`} style={{ fontSize: 12, padding: '8px 12px' }}>
                    {allClear ? '✓ Ready to install' : failing > 0 ? `${failing} need attention` : 'Awaiting input'}
                  </div>
                </div>
                <div className="col gap-2">
                  {checks.map(c => (
                    <div key={c.id} style={{
                      display: 'grid',
                      gridTemplateColumns: '20px 1fr auto',
                      gap: 12, alignItems: 'baseline',
                      padding: '10px 0',
                      borderBottom: '1px dashed color-mix(in oklab, var(--ink), transparent 80%)',
                    }}>
                      <span style={{
                        width: 14, height: 14,
                        border: '1px solid ' + (c.ok ? 'var(--accent-deep)' : c.have === '—' ? 'color-mix(in oklab, var(--ink), transparent 60%)' : 'var(--warn)'),
                        background: c.ok ? 'var(--accent)' : 'transparent',
                        display: 'inline-block',
                        marginTop: 4,
                      }} />
                      <div>
                        <div style={{ fontWeight: 600, fontSize: 13 }}>{c.label}</div>
                        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-3)' }}>{c.need}</div>
                      </div>
                      <span className="mono" style={{ fontSize: 12, color: c.ok ? 'var(--accent-deep)' : c.have === '—' ? 'var(--ink-3)' : 'var(--warn)' }}>
                        {c.have}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* RIGHT — floor plan + tips */}
            <div style={{ position: 'sticky', top: 80 }}>
              <div style={{
                border: '1px solid var(--rule)',
                background: 'var(--field-2)',
                padding: 24,
                position: 'relative',
              }}>
                <Crosshairs />
                <div className="flex between items-baseline" style={{ marginBottom: 16 }}>
                  <div>
                    <div className="mono upper" style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.12em' }}>Fig. 03</div>
                    <h3 className="display" style={{ margin: '4px 0 0', fontSize: 22 }}>Floor plan · top down</h3>
                  </div>
                  <span className="mono" style={{ fontSize: 10, color: 'var(--ink-4)', letterSpacing: '0.1em' }}>1:36</span>
                </div>
                <FootprintPlan model={model} config={config} studio={{
                  wallL: studio.wallL || 36,
                  wallR: studio.wallR || 36,
                  wallB: studio.wallB || 24,
                }} />
                <div className="mono" style={{ marginTop: 16, fontSize: 10, color: 'var(--ink-4)', letterSpacing: '0.08em', lineHeight: 1.6 }}>
                  Hatched edges = walls.<br />
                  Cyan dashed arc = {config.door} door swing.<br />
                  Cyan stripe on kiln face = door (front).<br />
                  Small box on {config.controls} = control panel.<br />
                  Adjust the inputs to the left to update.
                </div>
              </div>

              <div style={{ marginTop: 16, fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.55 }}>
                <strong style={{ color: 'var(--ink)' }}>Note:</strong> Final install spacing depends on your local building code and ventilation. The clearances above are Laguna's minimums. A Laguna tech will walk through your space with you on a call before fabrication starts.
              </div>
            </div>
          </div>
        </section>

        <section className="container" style={{ paddingBottom: 80 }}>
          <div className="rule" style={{ paddingTop: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16 }}>
            <div>
              <div className="mono upper" style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.12em' }}>Fit summary</div>
              <div className="display" style={{ fontSize: 28, marginTop: 6 }}>
                {allClear ? "All clear — ready to order" : failing > 0 ? `${failing} item${failing > 1 ? 's' : ''} flagged · proceed anyway?` : 'Fill in your studio above'}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 12 }}>
              <button className="btn btn-ghost" onClick={onBack}>← Adjust config</button>
              <button className="btn btn-accent btn-arrow" onClick={onNext}>
                Continue to review
              </button>
            </div>
          </div>
        </section>
      </main>
      <Footer />
    </div>
  );
}

function Field({ label, unit, v, onChange, suggest }) {
  return (
    <label style={{ display: 'block' }}>
      <span className="mono upper" style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.12em' }}>{label}</span>
      <div style={{ position: 'relative', marginTop: 6 }}>
        <input
          type="number"
          value={v ?? ''}
          onChange={(e) => onChange(e.target.value ? Number(e.target.value) : undefined)}
          placeholder={suggest ? `e.g. ${suggest}` : ''}
          style={{
            width: '100%',
            padding: '12px 50px 12px 14px',
            border: '1px solid color-mix(in oklab, var(--ink), transparent 70%)',
            background: 'var(--field)',
            fontFamily: 'var(--font-mono)',
            fontSize: 14,
            color: 'var(--ink)',
            fontVariantNumeric: 'tabular-nums',
          }}
        />
        <span style={{
          position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)',
          fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-3)', letterSpacing: '0.08em', textTransform: 'uppercase',
        }}>
          {unit}
        </span>
      </div>
    </label>
  );
}

window.FitCheck = FitCheck;
