// Defined outside IntakeForm so React sees a stable component reference across renders
function DimInput({ label, axis, value, onChange, disabled, unit }) {
  const dispVal = React.useMemo(() => {
    const v = parseFloat(value);
    if (!v || isNaN(v)) return '';
    return unit === 'mm' ? String(Math.round(v * 25.4)) : value;
  }, [value, unit]);

  const handleChange = (e) => {
    const raw = e.target.value;
    if (unit === 'mm') {
      const mm = parseFloat(raw);
      onChange({ target: { value: isNaN(mm) ? '' : (mm / 25.4).toFixed(1) } });
    } else {
      onChange(e);
    }
  };

  return (
    <div style={{ opacity: disabled ? 0.45 : 1 }}>
      <div style={{ fontFamily: 'var(--font-text)', fontSize: '11px', color: 'var(--text-muted)', marginBottom: '6px', letterSpacing: '0.02em' }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'stretch', border: '1px solid var(--border-default)', background: 'var(--surface-card)' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: '38px', flexShrink: 0, fontFamily: 'var(--font-mono)', fontSize: 'var(--text-xs)', fontWeight: 500, color: 'var(--as-mist)', background: 'var(--as-slate)', letterSpacing: '0.04em' }}>{axis}</span>
        <input
          type="text"
          inputMode="numeric"
          pattern="[0-9]*"
          value={dispVal}
          onChange={handleChange}
          disabled={disabled}
          style={{ flex: 1, fontFamily: 'var(--font-mono)', fontSize: 'var(--text-sm)', color: 'var(--text-primary)', background: 'var(--surface-card)', border: 'none', outline: 'none', padding: '12px 8px 12px 12px', textAlign: 'right', minWidth: 0, cursor: disabled ? 'not-allowed' : 'text' }}
        />
        <span style={{ display: 'inline-flex', alignItems: 'center', paddingRight: '14px', fontFamily: 'var(--font-mono)', fontSize: 'var(--text-xs)', color: 'var(--text-muted)' }}>{unit === 'mm' ? 'mm' : 'in'}</span>
      </div>
    </div>
  );
}

// Group — section wrapper. Must live outside IntakeForm to stay stable across renders.
function Group({ n, title, desc, children, first }) {
  const blockSep = { borderTop: '1px solid var(--border-hairline)', paddingTop: '32px', marginTop: '32px' };
  const subhead   = { fontFamily: 'var(--font-display)', fontSize: 'var(--text-h4)', color: 'var(--text-primary)', margin: '0 0 4px' };
  const note      = { fontFamily: 'var(--font-text)', fontSize: 'var(--text-xs)', color: 'var(--text-muted)', margin: '0 0 20px', lineHeight: 1.5 };
  return (
    <div style={first ? {} : blockSep}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: '12px', marginBottom: '4px' }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: '22px', lineHeight: 1, color: 'var(--as-ochre-ink)' }}>{n}</span>
        <h3 style={subhead}>{title}</h3>
      </div>
      <p style={note}>{desc}</p>
      {children}
    </div>
  );
}

// AlignSpace landing — Parametric Intake Form
function IntakeForm() {
  const DS = window.AlignSpaceDesignSystem_d3d6d6;
  const { SectionLabel, Field, Input, RadioGroup, Checkbox, Button, SpecRow, Badge } = DS;

  const [roomLocked,  setRoomLocked]  = React.useState(false);
  const [lockedDims,  setLockedDims]  = React.useState(null);
  const [unit,        setUnit]        = React.useState('in');

  const lockRoom = () => {
    const l = parseFloat(f.length);
    const w = parseFloat(f.width);
    if (l > 0 && w > 0) { setLockedDims({ l, w }); setRoomLocked(true); }
  };
  const unlockRoom = () => {
    setRoomLocked(false); setLockedDims(null);
  };
  // length/width/ceiling/upperClear are stored in inches; cabDepth is stored in mm (RadioGroup option values)
  const [f, setF] = React.useState({
    length: '144', width: '120', ceiling: '108',
    cabDepth: '610', upperClear: '18', widthPref: 'balanced', spiceCab: false, island: false,
    notes: '', drawingsLink: '', name: '', email: '', city: '', pdf: true,
  });
  const set = (k) => (v) => setF((s) => ({ ...s, [k]: v && v.target ? v.target.value : v }));
  const [sent, setSent] = React.useState(false);
  const [errors, setErrors] = React.useState({});

  const validate = () => {
    const e = {};
    if (!f.name.trim())  e.name  = 'Name is required.';
    if (!f.email.trim()) e.email = 'Email is required.';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f.email.trim())) e.email = 'Enter a valid email address.';
    setErrors(e);
    return Object.keys(e).length === 0;
  };
  return (
    <React.Fragment>
    <section id="intake" style={{ background: 'var(--surface-raised)', padding: 'var(--section-y) 0' }}>
      <div className="as-wrap">
        <div style={{ maxWidth: '56ch', marginBottom: '48px' }}>
          <SectionLabel>Free Parametric Layout Audit</SectionLabel>
          <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-h2)', color: 'var(--text-primary)', margin: '16px 0 12px' }}>
            Tell us about the room.
          </h2>
          <p style={{ fontSize: 'var(--text-sm)', lineHeight: 'var(--leading-relaxed)', color: 'var(--text-muted)' }}>
            The more precise the inputs, the tighter the model. Approximate measurements are fine for the audit — we confirm everything on site or in your session.
          </p>
        </div>

        <div className="as-intake-grid">
          {/* ---- form column ---- */}
          <div className="as-intake-form-panel" style={{ background: 'var(--surface-card)' }}>

            <Group n="A" title="Room Dimensions" desc="Interior clear dimensions. Enter length and width, then draw the room." first>
              <div className="as-grid-3">
                <DimInput label="Length"  axis="L" value={f.length}  onChange={set('length')}  disabled={roomLocked} unit={unit} />
                <DimInput label="Width"   axis="W" value={f.width}   onChange={set('width')}   disabled={roomLocked} unit={unit} />
                <DimInput label="Ceiling" axis="H" value={f.ceiling} onChange={set('ceiling')} disabled={roomLocked} unit={unit} />
              </div>
              <div style={{ margin: '8px 0 0', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '12px' }}>
                <p style={{ margin: 0, fontFamily: 'var(--font-mono)', fontSize: '9.5px', color: 'var(--text-muted)', letterSpacing: '0.04em' }}>
                  {unit === 'in' ? 'Feet-inches — 10 ft = 120, 12 ft = 144' : 'Millimetres — 3000 mm ≈ 118 in'}
                </p>
                <div style={{ display: 'flex', flexShrink: 0, border: '1px solid var(--border-default)', overflow: 'hidden' }}>
                  {['in', 'mm'].map(u => (
                    <button key={u} onClick={() => setUnit(u)} style={{
                      padding: '4px 10px',
                      fontFamily: 'var(--font-mono)', fontSize: '10px', letterSpacing: '0.06em',
                      background: unit === u ? 'var(--as-navy)' : 'transparent',
                      color: unit === u ? 'var(--as-mist)' : 'var(--text-muted)',
                      border: 'none', cursor: 'pointer',
                    }}>{u}</button>
                  ))}
                </div>
              </div>
              {!roomLocked && (
                <div style={{ marginTop: '16px' }}>
                  <button
                    onClick={lockRoom}
                    disabled={!(parseFloat(f.length) > 0 && parseFloat(f.width) > 0)}
                    style={{
                      fontFamily: 'var(--font-text)', fontSize: 'var(--text-sm)', letterSpacing: '0.04em',
                      background: 'var(--as-navy)', color: 'var(--as-mist)',
                      border: 'none', padding: '10px 22px', cursor: 'pointer', opacity: (parseFloat(f.length) > 0 && parseFloat(f.width) > 0) ? 1 : 0.4,
                    }}>
                    Draw Room →
                  </button>
                </div>
              )}

              {roomLocked && lockedDims && (
                <div style={{ marginTop: '24px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '12px' }}>
                    <span style={{ fontFamily: 'var(--font-mono)', fontSize: '10px', color: 'var(--text-muted)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>
                      {unit === 'mm'
                        ? `${Math.round(lockedDims.l * 25.4)} × ${Math.round(lockedDims.w * 25.4)} mm`
                        : `${lockedDims.l}" × ${lockedDims.w}"`}
                    </span>
                    <button onClick={unlockRoom} style={{
                      fontFamily: 'var(--font-mono)', fontSize: '10px', letterSpacing: '0.08em',
                      background: 'transparent', color: 'var(--text-muted)',
                      border: '1px solid var(--border-default)', padding: '4px 10px', cursor: 'pointer',
                    }}>Edit Dimensions</button>
                  </div>
                  <RoomCanvas
                    lengthIn={lockedDims.l}
                    widthIn={lockedDims.w}
                    unit={unit}
                    onComplete={(base, upper, openings, appliances) => {
                      setF(s => ({ ...s, baseBoundary: base, upperBoundary: upper, openings, appliances }));
                    }}
                  />
                </div>
              )}
            </Group>

            <Group n="B" title="Design Preferences" desc="The constraints we optimise the layout against.">
              <Field label="Cabinet depth (lowers)" style={{ marginBottom: '18px' }}>
                <RadioGroup value={f.cabDepth} onChange={set('cabDepth')} options={
                  unit === 'mm'
                    ? [
                        { value: '560', label: '560 mm', sub: 'shallow' },
                        { value: '610', label: '610 mm', sub: 'standard' },
                        { value: '660', label: '660 mm', sub: 'deep' },
                      ]
                    : [
                        { value: '560', label: '22 in', sub: 'shallow' },
                        { value: '610', label: '24 in', sub: 'standard' },
                        { value: '660', label: '26 in', sub: 'deep' },
                      ]
                } />
              </Field>
              <Field label="Upper cabinet clearance (from countertop)" style={{ marginBottom: '18px' }}>
                <RadioGroup value={f.upperClear} onChange={set('upperClear')} options={
                  unit === 'mm'
                    ? [
                        { value: '16', label: '406 mm', sub: 'low' },
                        { value: '18', label: '457 mm', sub: 'standard' },
                        { value: '20', label: '508 mm', sub: 'tall' },
                      ]
                    : [
                        { value: '16', label: '16 in', sub: 'low' },
                        { value: '18', label: '18 in', sub: 'standard' },
                        { value: '20', label: '20 in', sub: 'tall' },
                      ]
                } />
              </Field>
              <Field label="Cabinet width preference" style={{ marginBottom: '18px' }}>
                <RadioGroup value={f.widthPref} onChange={set('widthPref')} options={[
                  { value: 'narrow', label: 'Narrow', sub: 'more modules' },
                  { value: 'balanced', label: 'Mixed', sub: 'varied' },
                  { value: 'wide', label: 'Wide', sub: 'fewer doors' },
                ]} />
              </Field>
              <Field label="Extras">
                <Checkbox checked={f.spiceCab} onChange={set('spiceCab')} label="Spice cabinet" hint="Dedicated narrow pull-out or door-mounted spice storage." />
                <div style={{ marginTop: '12px' }}>
                  <Checkbox checked={f.island} onChange={set('island')} label="Island (if space allows)" hint="We'll flag whether your room has enough clearance during the audit." />
                </div>
              </Field>
            </Group>

            <Group n="C" title="Notes &amp; Drawings" desc="Optional — any context that doesn't fit the form above.">
              <Field label="Notes" htmlFor="nt" style={{ marginBottom: '18px' }}>
                <Input id="nt" as="textarea" value={f.notes} onChange={set('notes')} placeholder="Existing constraints, style references, budget ballpark, anything relevant..." rows={4} />
              </Field>
              <Field label="Drawings / files" htmlFor="dl">
                <Input id="dl" value={f.drawingsLink} onChange={set('drawingsLink')} placeholder="Google Drive, Dropbox, or WeTransfer link (optional)" />
              </Field>
            </Group>

            <Group n="D" title="Where to Send It" desc="We return your 1-page layout PDF within 48 hours.">
              <div className="as-grid-2">
                <Field label="Name" htmlFor="nm" required error={errors.name}><Input id="nm" value={f.name} onChange={set('name')} placeholder="Sarah Klein" /></Field>
                <Field label="Email" htmlFor="em" required error={errors.email}><Input id="em" type="email" value={f.email} onChange={set('email')} placeholder="you@studio.ca" /></Field>
              </div>
              <div style={{ marginTop: '18px' }}>
                <Field label="City / Area" htmlFor="ct"><Input id="ct" value={f.city} onChange={set('city')} placeholder="Richmond Hill, ON" /></Field>
              </div>
              <div style={{ marginTop: '20px' }}>
                <Checkbox checked={f.pdf} onChange={set('pdf')} label="Email me the 1-page parametric layout PDF" hint="The audit deliverable only — no marketing." />
              </div>
            </Group>

            <div style={{ marginTop: '32px', display: 'flex', alignItems: 'center', gap: '20px' }}>
              <Button variant="accent" size="lg" disabled={sent} onClick={() => { if (validate()) setSent(true); }} iconRight={<i data-lucide="arrow-right" style={{ width: 16, height: 16 }}></i>}>
                {sent ? 'Brief Received' : 'Submit for Free Audit'}
              </Button>
              {sent
                ? <span style={{ fontFamily: 'var(--font-mono)', fontSize: 'var(--text-xs)', color: 'var(--as-success)' }}>✓ We'll be in touch within 48 hours.</span>
                : <span style={{ fontFamily: 'var(--font-mono)', fontSize: 'var(--text-2xs)', color: 'var(--text-muted)' }}>No payment. No obligation.</span>}
            </div>
          </div>

          {/* ---- live spec titleblock ---- */}
          <aside className="as-intake-aside" style={{ background: 'var(--as-navy)', padding: '32px', position: 'sticky', top: '92px' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '20px' }}>
              <SectionLabel onDark tick={false}>Layout Brief</SectionLabel>
              <Badge tone="ochre">Live</Badge>
            </div>
            <div style={{ marginBottom: '8px' }}>
              <SpecRow onDark label="Footprint" value={
                unit === 'mm'
                  ? `${Math.round(f.length * 25.4)} \u00d7 ${Math.round(f.width * 25.4)} mm`
                  : `${f.length} \u00d7 ${f.width} in`
              } />
              <SpecRow onDark label="Ceiling" value={
                unit === 'mm'
                  ? `${Math.round(f.ceiling * 25.4)} mm`
                  : `${f.ceiling} in`
              } />
              <SpecRow onDark label="Floor area" value={
                unit === 'mm'
                  ? `${(f.length * f.width * 0.000645).toFixed(2)} m\u00b2`
                  : `${(f.length * f.width / 144).toFixed(1)} ft\u00b2`
              } />
              <SpecRow onDark label="Cab depth" value={
                unit === 'mm'
                  ? `${f.cabDepth} mm`
                  : `${Math.round(parseFloat(f.cabDepth) / 25.4)} in`
              } />
              <SpecRow onDark label="Upper Clear." value={
                unit === 'mm'
                  ? `${Math.round(parseFloat(f.upperClear) * 25.4)} mm`
                  : `${f.upperClear} in`
              } />
              <SpecRow onDark label="Width pref." value={f.widthPref} />
              <SpecRow onDark label="Spice cab." value={f.spiceCab ? 'yes' : '—'} />
              <SpecRow onDark label="Island" value={f.island ? 'requested' : '—'} divider={false} />
            </div>
            <p style={{ fontFamily: 'var(--font-text)', fontSize: 'var(--text-xs)', color: 'var(--text-on-dark-muted)', lineHeight: 1.6, marginTop: '20px', paddingTop: '20px', borderTop: '1px solid var(--border-on-dark)' }}>
              This is the brief our model receives. It updates as you fill the form — the same titleblock appears on your returned PDF.
            </p>
          </aside>
        </div>
      </div>
    </section>
    {sent && <PdfPreview f={f} unit={unit} />}
    </React.Fragment>
  );
}
window.IntakeForm = IntakeForm;
