// ============================================================
// Made-to-order commission wizard - FreshWave Digital Studio
// ============================================================

const COMMISSION_STEPS = ['Category', 'Material', 'Finish', 'Scope', 'Details'];

function StepDots({ step }) {
  return (
    <div className="mb-10 flex items-center justify-center gap-2 sm:gap-3">
      {COMMISSION_STEPS.map((label, idx) => {
        const done = idx < step;
        const active = idx === step;
        return (
          <div key={label} className="flex items-center gap-2 sm:gap-3">
            <div className="flex items-center gap-2">
              <span
                className="flex h-8 w-8 items-center justify-center rounded-full font-mono text-xs transition-all"
                style={{
                  background: active ? 'hsl(var(--primary))' : done ? 'hsl(var(--cyan) / 0.2)' : 'hsl(var(--muted))',
                  color: active ? 'hsl(var(--primary-foreground))' : done ? 'hsl(var(--cyan))' : 'hsl(var(--muted-foreground))',
                  boxShadow: active ? '0 0 18px hsl(var(--cyan) / 0.72), 0 0 42px hsl(var(--cyan) / 0.28)' : done ? '0 0 18px hsl(var(--cyan) / 0.2)' : 'none',
                }}
              >
                {done ? <Icon name="check" className="h-4 w-4" /> : idx + 1}
              </span>
              <span className={`hidden font-heading text-[10px] uppercase tracking-wider sm:inline ${active ? 'text-primary' : 'text-muted-foreground'}`}>{label}</span>
            </div>
            {idx < COMMISSION_STEPS.length - 1 && <span className="h-px w-4 bg-border sm:w-8"></span>}
          </div>
        );
      })}
    </div>
  );
}

// Selectable card
function OptionCard({ selected, onClick, accent = 'cyan', title, note, swatch }) {
  return (
    <button
      onClick={onClick}
      onPointerDown={triggerButtonSparks}
      className="spark-button charged-panel group flex items-center gap-4 rounded-xl border bg-card p-5 text-left transition-all hover:-translate-y-0.5"
      style={{
        '--panel-accent': accentHsl(accent),
        borderColor: selected ? accentHsl(accent) : 'hsl(var(--border))',
        boxShadow: selected ? `0 0 28px ${accentHsl(accent, 0.38)}, inset 0 0 28px ${accentHsl(accent, 0.08)}` : `0 0 18px ${accentHsl(accent, 0.06)}`,
      }}
    >
      {swatch && (
        <span className="h-10 w-10 flex-shrink-0 rounded-lg" style={{ background: `radial-gradient(circle at 30% 30%, ${accentHsl(accent, 0.9)}, ${accentHsl(accent, 0.25)})` }}></span>
      )}
      <div className="flex-1">
        <div className="font-heading text-base tracking-wide">{title}</div>
        <div className="text-xs text-muted-foreground">{note}</div>
      </div>
      <span
        className="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full border transition-all"
        style={{ borderColor: selected ? accentHsl(accent) : 'hsl(var(--border))', background: selected ? accentHsl(accent) : 'transparent' }}
      >
        {selected && <Icon name="check" className="h-3.5 w-3.5" stroke={3} style={{ color: 'hsl(var(--primary-foreground))' }} />}
      </span>
    </button>
  );
}

const START_LANES = [
  {
    id: 'preloads',
    eyebrow: 'Sleeper upgrades',
    title: 'Sleeper Items',
    accent: 'cyan',
    body: 'Small quality-of-life prints people do not expect, but use every day once they have them.',
    points: ['Desk and shelf upgrades', 'Practical gift energy', 'Fastest quote path'],
    action: 'Browse sleeper items',
  },
  {
    id: 'custom',
    eyebrow: 'One of one',
    title: 'Custom Request',
    accent: 'magenta',
    body: 'Bring the sketch, screenshot, reference photo or half-formed idea. We will scope it by hand.',
    points: ['Original characters', 'Replicas and repairs', 'Odd ideas welcome'],
    action: 'Build a brief',
  },
];

function StartPieceGateway({ onChoose }) {
  return (
    <div className="scanlines">
      <section className="relative overflow-hidden py-16 md:py-24">
        <div className="absolute inset-0 grid-floor opacity-20"></div>
        <div
          className="pointer-events-none absolute left-1/2 top-20 h-72 w-[34rem] -translate-x-1/2 rounded-full blur-3xl"
          style={{ background: 'radial-gradient(circle, hsl(var(--magenta) / 0.22), hsl(var(--cyan) / 0.12), transparent 70%)' }}
        ></div>
        <div className="container relative mx-auto">
          <div className="mx-auto mb-12 max-w-3xl text-center">
            <Eyebrow accent="magenta"><span className="mx-auto">Start a piece</span></Eyebrow>
            <h1 className="crt-head mb-5 font-heading text-4xl md:text-5xl lg:text-6xl" style={{ letterSpacing: '-0.02em' }}>
              Choose your lane.
            </h1>
            <p className="mx-auto max-w-2xl text-lg leading-relaxed text-muted-foreground">
              Pick a sleeper item when you want a useful FreshWave upgrade with fast options. Go custom when the idea needs a sculpt, replica, remix or deeper quote.
            </p>
          </div>

          <div className="grid gap-6 lg:grid-cols-2">
            {START_LANES.map((lane) => (
              <LaneCard key={lane.id} lane={lane} onChoose={() => onChoose(lane.id)} />
            ))}
          </div>

          <BeforePrintPanel className="mt-8" />

          <div className="mx-auto mt-10 grid max-w-4xl gap-4 border-t border-border pt-8 text-sm text-muted-foreground md:grid-cols-3">
            <div>
              <div className="mb-1 font-mono text-[10px] uppercase tracking-[0.25em] text-primary">01 / Pick</div>
              Pick a sleeper item or describe the piece from scratch.
            </div>
            <div>
              <div className="mb-1 font-mono text-[10px] uppercase tracking-[0.25em] text-primary">02 / Scope</div>
              Choose material, finish, size and the notes that matter.
            </div>
            <div>
              <div className="mb-1 font-mono text-[10px] uppercase tracking-[0.25em] text-primary">03 / Quote</div>
              We confirm price, deadline and production details within 72 hours.
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

function LaneCard({ lane, onChoose }) {
  return (
    <button
      onClick={onChoose}
      onPointerDown={triggerButtonSparks}
      className="spark-button card-accent charged-panel group relative min-h-[28rem] overflow-hidden rounded-2xl border border-border bg-card p-7 text-left transition-all duration-300 hover:-translate-y-1 md:p-9"
      style={{ '--card-accent': accentHsl(lane.accent), '--panel-accent': accentHsl(lane.accent), boxShadow: `0 0 0 1px ${accentHsl(lane.accent, 0.24)}, 0 0 58px ${accentHsl(lane.accent, 0.18)}, inset 0 0 42px ${accentHsl(lane.accent, 0.07)}` }}
    >
      <div className="absolute inset-0 grid-floor opacity-10"></div>
      <div
        className="pointer-events-none absolute -right-20 -top-20 h-56 w-56 rounded-full blur-3xl transition-opacity duration-300 group-hover:opacity-100"
        style={{ background: `radial-gradient(circle, ${accentHsl(lane.accent, 0.45)}, transparent 70%)`, opacity: 0.65 }}
      ></div>
      <div className="relative flex h-full flex-col">
        <div className="mb-7 flex items-center justify-between gap-4">
          <span className="font-mono text-[10px] uppercase tracking-[0.28em] text-muted-foreground">{lane.eyebrow}</span>
          <span className="flex h-12 w-12 items-center justify-center rounded-full border" style={{ borderColor: accentHsl(lane.accent, 0.45), color: accentHsl(lane.accent) }}>
            <Icon name={lane.id === 'preloads' ? 'layers' : 'arrow-up-right'} className="h-5 w-5" />
          </span>
        </div>
        <h2 className="crt-head neon-text-soft mb-4 font-heading text-3xl md:text-4xl" style={{ color: accentHsl(lane.accent) }}>{lane.title}</h2>
        <p className="mb-8 max-w-xl text-base leading-relaxed text-muted-foreground">{lane.body}</p>
        <div className="mb-8 space-y-3">
          {lane.points.map((point) => (
            <div key={point} className="flex items-center gap-3 text-sm">
              <span className="flex h-5 w-5 items-center justify-center rounded-full" style={{ background: accentHsl(lane.accent, 0.16), color: accentHsl(lane.accent) }}>
                <Icon name="check" className="h-3 w-3" stroke={3} />
              </span>
              {point}
            </div>
          ))}
        </div>
        <div className="mt-auto flex items-center justify-between border-t border-border pt-6">
          <span className="font-heading text-xs uppercase tracking-wider" style={{ color: accentHsl(lane.accent) }}>{lane.action}</span>
          <Icon name="arrow-right" className="h-5 w-5 transition-transform group-hover:translate-x-1" style={{ color: accentHsl(lane.accent) }} />
        </div>
      </div>
    </button>
  );
}

function PreloadFlow({ onBack, backLabel = 'Start a Piece' }) {
  const [selectedId, setSelectedId] = useState(PRELOADS[0].id);
  const [finish, setFinish] = useState('white');
  const [size, setSize] = useState('standard');
  const [brief, setBrief] = useState({ name: '', email: '', notes: '' });
  const [sent, setSent] = useState(false);
  const [sending, setSending] = useState(false);
  const [fallbackMailto, setFallbackMailto] = useState('');
  const [ticket, setTicket] = useState('');
  const selected = PRELOADS.find((item) => item.id === selectedId) || PRELOADS[0];
  const selectedFinish = PRELOAD_FINISHES.find((item) => item.id === finish) || PRELOAD_FINISHES[0];
  const selectedSize = PRELOAD_SIZES.find((item) => item.id === size) || PRELOAD_SIZES[0];
  const sizeAdd = preloadSizeAdjustment(selected, selectedSize);
  const price = preloadEstimate(selected, selectedFinish, selectedSize);
  const setBriefValue = (key, value) => setBrief((current) => ({ ...current, [key]: value }));
  const canSend = brief.name.trim() && /\S+@\S+\.\S+/.test(brief.email);

  const submit = async (event) => {
    event.preventDefault();
    if (!canSend) return;
    setSending(true);
    setFallbackMailto('');
    setTicket('');

    const payload = {
      kind: 'preload',
      name: brief.name,
      email: brief.email,
      preload: selected.title,
      category: selected.category,
      finish: selectedFinish.label,
      size: selectedSize.label,
      estimate: `$${price}`,
      message: brief.notes || `Requesting ${selected.title} with ${selectedFinish.label} at ${selectedSize.label}.`,
      notes: brief.notes,
    };

    try {
      const result = await submitInquiry(payload);
      setTicket(result.ticket || '');
      setSent(true);
    } catch (error) {
      const mailto = buildInquiryMailto(payload);
      setFallbackMailto(mailto);
      window.location.href = mailto;
      setSent(true);
    } finally {
      setSending(false);
    }
  };

  if (sent) {
    return (
      <div className="scanlines">
        <div className="container mx-auto flex min-h-[70vh] flex-col items-center justify-center py-20 text-center">
          <div className="mb-8 flex h-20 w-20 items-center justify-center rounded-full bg-primary glow-cyan">
            <Icon name="check" className="h-9 w-9" stroke={3} style={{ color: 'hsl(var(--primary-foreground))' }} />
          </div>
          <h1 className="crt-head mb-4 font-heading text-3xl md:text-4xl">Sleeper item request queued.</h1>
          <p className="mx-auto mb-2 max-w-xl text-lg text-muted-foreground">
            Thanks {brief.name.split(' ')[0] || 'there'} - we logged the {selected.title} with {selectedFinish.label.toLowerCase()} at {selectedSize.label.toLowerCase()}.
          </p>
          <p className="lit-price quote-data mb-8 text-lg text-primary text-glow-cyan">Selected total: ${price}</p>
          {ticket && <p className="mb-6 font-mono text-xs uppercase tracking-[0.25em] text-primary">Ticket {ticket}</p>}
          {fallbackMailto && (
            <div className="mb-6 max-w-xl rounded-xl border border-border bg-card p-4 text-sm text-muted-foreground">
              The server form was unavailable, so we opened a backup email draft with your sleeper item details.
              <a href={fallbackMailto} className="mt-3 inline-flex font-heading text-xs uppercase tracking-wider text-primary hover:underline">Open email draft</a>
            </div>
          )}
          <div className="flex flex-col gap-3 sm:flex-row">
            <Button onClick={() => { setSent(false); setFallbackMailto(''); setTicket(''); setBrief({ name: '', email: '', notes: '' }); }}>Request another sleeper item</Button>
            <Button variant="outline" onClick={onBack}>Back to {backLabel}</Button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="scanlines">
      <section className="relative overflow-hidden py-16 md:py-20">
        <div className="absolute inset-0 grid-floor opacity-20"></div>
        <div className="container relative mx-auto">
          <button onClick={onBack} className="mb-8 flex items-center gap-2 font-heading text-xs uppercase tracking-wider text-muted-foreground transition-colors hover:text-primary">
            <Icon name="arrow-left" /> {backLabel}
          </button>
          <div className="mb-10 max-w-3xl">
            <Eyebrow accent="cyan">Sleeper items</Eyebrow>
            <h1 className="crt-head mb-4 font-heading text-4xl md:text-5xl" style={{ letterSpacing: '-0.02em' }}>Pick the useful one.</h1>
            <p className="max-w-2xl text-lg text-muted-foreground">
              Unexpected quality-of-life prints with known shapes, faster timelines and enough options to make them feel yours.
            </p>
          </div>

          <div className="grid gap-8 lg:grid-cols-[minmax(0,1fr)_24rem]">
            <div className="grid gap-4 md:grid-cols-2">
              {PRELOADS.map((item) => (
                <PreloadCard key={item.id} item={item} selected={item.id === selectedId} onSelect={() => setSelectedId(item.id)} />
              ))}
            </div>

            <form onSubmit={submit} className="reading-surface charged-panel rounded-2xl border border-border bg-card p-6 lg:sticky lg:top-24 lg:self-start" style={{ '--panel-accent': accentHsl(selected.accent) }}>
              <div className="mb-5 flex items-start justify-between gap-4">
                <div>
                  <div className="font-mono text-[10px] uppercase tracking-[0.25em] text-muted-foreground">Order brief</div>
                  <h2 className="mt-2 font-heading text-2xl tracking-wide">{selected.title}</h2>
                </div>
                <div className="text-right">
                  <div className="font-mono text-[10px] uppercase tracking-[0.25em] text-muted-foreground">Current total</div>
                  <div className="lit-price text-3xl text-primary text-glow-cyan">${price}</div>
                </div>
              </div>

              <div className="mb-6 rounded-xl border border-border bg-background/50 p-4 text-sm text-muted-foreground">
                {selected.description}
              </div>

              <div className="mb-6 border-y border-border py-4">
                <div className="mb-3 font-mono text-[10px] uppercase tracking-[0.24em] text-muted-foreground">Price check</div>
                <div className="space-y-2 text-sm">
                  <div className="flex items-center justify-between gap-4"><span>{selected.title}</span><span className="quote-data">${selected.price}</span></div>
                  <div className="flex items-center justify-between gap-4 text-muted-foreground"><span>{selectedSize.label}</span><span className="quote-data">{sizeAdd ? `+$${sizeAdd}` : 'included'}</span></div>
                  <div className="flex items-center justify-between gap-4 text-muted-foreground"><span>{selectedFinish.label}</span><span className="quote-data">{selectedFinish.price ? `+$${selectedFinish.price}` : 'included'}</span></div>
                </div>
              </div>

              <div className="space-y-6">
                <div>
                  <label className="mb-3 block font-heading text-xs uppercase tracking-wider text-muted-foreground">Size</label>
                  <div className="flex flex-wrap gap-2">
                    {PRELOAD_SIZES.map((item) => (
                      <Button key={item.id} type="button" size="sm" className="font-data text-sm tracking-[0.04em]" variant={size === item.id ? 'default' : 'outline'} onClick={() => setSize(item.id)}>
                        {item.label}{preloadSizeAdjustment(selected, item) ? ` +$${preloadSizeAdjustment(selected, item)}` : ''}
                      </Button>
                    ))}
                  </div>
                </div>

                <div>
                  <label className="mb-3 block font-heading text-xs uppercase tracking-wider text-muted-foreground">Finish</label>
                  <div className="grid grid-cols-1 gap-2">
                    {PRELOAD_FINISHES.map((item) => (
                      <button
                        key={item.id}
                        type="button"
                        onClick={() => setFinish(item.id)}
                        onPointerDown={triggerButtonSparks}
                        className="spark-button flex items-center justify-between rounded-lg border border-border px-4 py-3 text-left text-sm transition-all hover:border-primary"
                        style={{
                          borderColor: finish === item.id ? accentHsl(selected.accent) : 'hsl(var(--border))',
                          boxShadow: finish === item.id ? `0 0 18px ${accentHsl(selected.accent, 0.24)}, inset 0 0 18px ${accentHsl(selected.accent, 0.08)}` : 'none',
                        }}
                      >
                        <span>{item.label}</span>
                        <span className="quote-data text-sm text-muted-foreground">{item.price ? `+$${item.price}` : 'included'}</span>
                      </button>
                    ))}
                  </div>
                </div>

                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-1">
                  <Field label="Name *">
                    <input value={brief.name} onChange={(e) => setBriefValue('name', e.target.value)} placeholder="Maya Chen" className="fw-input" />
                  </Field>
                  <Field label="Email *">
                    <input type="email" value={brief.email} onChange={(e) => setBriefValue('email', e.target.value)} placeholder="maya@example.com" className="fw-input" />
                  </Field>
                </div>

                <Field label="Customization notes">
                  <textarea value={brief.notes} onChange={(e) => setBriefValue('notes', e.target.value)} rows={4} placeholder="Colors, character details, deadline, gift notes..." className="fw-input resize-none"></textarea>
                </Field>

                <Button type="submit" className="w-full" disabled={!canSend || sending}>
                  {sending ? (<><Icon name="spinner" /> Sending...</>) : (<>Request this sleeper item <Icon name="arrow-right" /></>)}
                </Button>
                <p className="font-mono text-[10px] uppercase tracking-[0.2em] text-muted-foreground">
                  No payment collected here. Final quote confirmed by hand.
                </p>
              </div>
            </form>
          </div>
        </div>
      </section>
    </div>
  );
}

function PreloadCard({ item, selected, onSelect }) {
  return (
    <button
      onClick={onSelect}
      onPointerDown={triggerButtonSparks}
      className="spark-button card-accent charged-panel group rounded-2xl border bg-card p-5 text-left transition-all hover:-translate-y-1"
      style={{
        '--card-accent': accentHsl(item.accent),
        '--panel-accent': accentHsl(item.accent),
        borderColor: selected ? accentHsl(item.accent) : 'hsl(var(--border))',
        boxShadow: selected ? `0 0 0 1px ${accentHsl(item.accent, 0.18)}, 0 0 44px ${accentHsl(item.accent, 0.28)}, inset 0 0 34px ${accentHsl(item.accent, 0.08)}` : `0 0 28px ${accentHsl(item.accent, 0.08)}`,
      }}
    >
      <div className="mb-5 flex items-start justify-between gap-4">
        <div>
          <div className="mb-2 font-mono text-[10px] uppercase tracking-[0.25em]" style={{ color: accentHsl(item.accent) }}>{item.tag}</div>
          <h3 className="font-heading text-xl tracking-wide">{item.title}</h3>
          <p className="mt-1 text-sm text-muted-foreground">{item.category}</p>
        </div>
        <div className="text-right">
          <div className="font-mono text-[10px] uppercase tracking-[0.2em] text-muted-foreground">From</div>
          <div className="lit-price text-2xl" style={{ color: accentHsl(item.accent) }}>${item.price}</div>
        </div>
      </div>
      <Placeholder label={item.title} accent={item.accent} glow className="mb-5 aspect-[4/3] rounded-xl" />
      <p className="mb-5 text-sm leading-relaxed text-muted-foreground">{item.description}</p>
      <div className="mb-5 flex flex-wrap gap-2 font-mono text-[10px] uppercase tracking-wider text-muted-foreground">
        <span className="rounded-full border border-border px-3 py-1">{item.size}</span>
        <span className="rounded-full border border-border px-3 py-1">{item.turnaround}</span>
      </div>
      <div className="space-y-2">
        {item.includes.map((line) => (
          <div key={line} className="flex items-center gap-2 text-xs">
            <Icon name="check" className="h-3.5 w-3.5" style={{ color: accentHsl(item.accent) }} />
            {line}
          </div>
        ))}
      </div>
    </button>
  );
}

function preloadEstimate(item, finish, size) {
  return item.price + finish.price + preloadSizeAdjustment(item, size);
}

function preloadSizeAdjustment(item, size) {
  return Math.max(0, Math.ceil(item.price * ((size.mult || 1) - 1)));
}

function CommissionPage() {
  const [mode, setMode] = useState('start');

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [mode]);

  if (mode === 'preloads') return <PreloadFlow onBack={() => setMode('start')} />;
  if (mode === 'custom') return <CustomRequestFlow onBack={() => setMode('start')} />;
  return <StartPieceGateway onChoose={setMode} />;
}

function SleepersPage() {
  const sleeperLane = {
    ...START_LANES.find((lane) => lane.id === 'preloads'),
    eyebrow: 'Fundamentals / quality of life',
    title: 'Sleeper Picks',
    body: 'The little prints that have made a surprisingly good difference in my own day-to-day setup. Easy to overlook at first, then hard to go without.',
    points: ['Everyday setup wins', 'Small details that help', 'Built for the daily rotation'],
    action: 'See the sleeper catalogue',
  };

  return (
    <div className="scanlines">
      <section className="relative overflow-hidden py-16 md:py-24">
        <div className="absolute inset-0 grid-floor opacity-20"></div>
        <div
          className="pointer-events-none absolute left-1/2 top-20 h-72 w-[34rem] -translate-x-1/2 rounded-full blur-3xl"
          style={{ background: 'radial-gradient(circle, hsl(var(--cyan) / 0.22), hsl(var(--magenta) / 0.12), transparent 70%)' }}
        ></div>
        <div className="container relative mx-auto">
          <div className="mx-auto mb-12 max-w-3xl text-center">
            <Eyebrow accent="cyan"><span className="mx-auto">Sleeper picks</span></Eyebrow>
            <h1 className="crt-head mb-5 font-heading text-4xl md:text-5xl lg:text-6xl" style={{ letterSpacing: '-0.02em' }}>
              Small upgrades.<br />Big everyday difference.
            </h1>
            <p className="mx-auto max-w-2xl text-lg leading-relaxed text-muted-foreground">
              These are the pieces that surprised me: the simple, reliable additions that make a desk, shelf or daily routine feel a little more dialed-in every time I use them.
            </p>
          </div>

          <div className="mx-auto mb-8 grid max-w-5xl gap-6 border-y border-border py-7 md:grid-cols-[1.15fr_0.85fr]">
            <div>
              <div className="mb-3 font-mono text-[10px] uppercase tracking-[0.28em] text-primary">The FreshWave read</div>
              <h2 className="font-heading text-xl leading-snug text-foreground md:text-2xl">The ones that quietly earn a place.</h2>
            </div>
            <p className="text-sm leading-relaxed text-muted-foreground md:text-base">
              Sleeper Picks are not trying to replace the big statement pieces. They are the low-key additions that have made my own everyday life smoother, more organized and just more enjoyable to use. Some work quietly in the background - like the Cable Comb Kit giving a crowded desk room to breathe - but that is exactly why they earn their place.
            </p>
          </div>

          <div className="mx-auto max-w-5xl">
            <LaneCard lane={sleeperLane} onChoose={() => go('/sleepers/catalogue')} />
          </div>
        </div>
      </section>
    </div>
  );
}

function SleepersCataloguePage() {
  return <PreloadFlow onBack={() => go('/sleepers')} backLabel="Sleeper Picks" />;
}

function CustomRequestFlow({ onBack }) {
  const [step, setStep] = useState(0);
  const stepCardRef = useRef(null);
  const didMountStepRef = useRef(false);
  const [data, setData] = useState({
    category: '', material: '', finish: '', qty: 1, size: 'Palm (≤3in)', notes: '', name: '', email: '',
  });
  const [done, setDone] = useState(false);
  const [sending, setSending] = useState(false);
  const [fallbackMailto, setFallbackMailto] = useState('');
  const [ticket, setTicket] = useState('');
  const set = (patch) => setData((d) => ({ ...d, ...patch }));

  const sizes = ['Palm (≤3in)', 'Desk (3-6in)', 'Shelf (6-9in)', 'Statue (up to 12in)'];

  useEffect(() => {
    if (!didMountStepRef.current) {
      didMountStepRef.current = true;
      return;
    }

    window.requestAnimationFrame(() => {
      if (!stepCardRef.current) return;
      const prefersReducedMotion = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
      const stickyHeaderOffset = 92;
      const top = stepCardRef.current.getBoundingClientRect().top + window.scrollY - stickyHeaderOffset;
      window.scrollTo({ top: Math.max(0, top), behavior: prefersReducedMotion ? 'auto' : 'smooth' });
    });
  }, [step]);

  const canNext = [
    () => !!data.category,
    () => !!data.material,
    () => !!data.finish,
    () => !!data.size && data.qty >= 1,
    () => data.name.trim() && /\S+@\S+\.\S+/.test(data.email),
  ][step];

  const next = async () => {
    if (step < COMMISSION_STEPS.length - 1) {
      setStep(step + 1);
      return;
    }
    if (!canNext()) return;

    const catLabel = (COMMISSION_CATEGORIES.find((c) => c.id === data.category) || {}).label || '';
    const matLabel = (COMMISSION_MATERIALS.find((m) => m.id === data.material) || {}).label || '';
    const finLabel = (COMMISSION_FINISHES.find((f) => f.id === data.finish) || {}).label || '';
    const estimate = estimateRange(data);
    const payload = {
      kind: 'custom',
      name: data.name,
      email: data.email,
      category: catLabel,
      material: matLabel,
      finish: finLabel,
      size: data.size,
      quantity: data.qty,
      estimate: estimate ? `$${estimate.low}-${estimate.high}` : '',
      message: data.notes || `Custom request for ${catLabel || 'a FreshWave piece'}.`,
      notes: data.notes,
    };

    setSending(true);
    setFallbackMailto('');
    setTicket('');
    try {
      const result = await submitInquiry(payload);
      setTicket(result.ticket || '');
      setDone(true);
    } catch (error) {
      const mailto = buildInquiryMailto(payload);
      setFallbackMailto(mailto);
      window.location.href = mailto;
      setDone(true);
    } finally {
      setSending(false);
    }
  };
  const back = () => { if (step > 0) setStep(step - 1); };

  if (done) {
    const catLabel = (COMMISSION_CATEGORIES.find((c) => c.id === data.category) || {}).label;
    const matLabel = (COMMISSION_MATERIALS.find((m) => m.id === data.material) || {}).label;
    return (
      <div className="scanlines">
        <div className="container mx-auto flex min-h-[70vh] flex-col items-center justify-center py-20 text-center">
          <div className="relative mb-8">
            <div className="pointer-events-none absolute left-1/2 top-1/2 h-48 w-48 -translate-x-1/2 -translate-y-1/2 rounded-full blur-3xl" style={{ background: 'radial-gradient(circle, hsl(var(--cyan) / 0.4), transparent 70%)' }}></div>
            <span className="relative flex h-20 w-20 items-center justify-center rounded-full bg-primary glow-cyan">
              <Icon name="check" className="h-9 w-9" stroke={3} style={{ color: 'hsl(var(--primary-foreground))' }} />
            </span>
          </div>
          <h1 className="crt-head mb-4 font-heading text-3xl md:text-4xl">Brief received.</h1>
          <p className="mx-auto mb-2 max-w-lg text-lg text-muted-foreground">
            Thanks {data.name.split(' ')[0]}. We've logged your {catLabel ? catLabel.toLowerCase() : 'piece'} in {matLabel || 'your chosen material'}. We'll come back within 72 hours with a firm quote and next steps.
          </p>
          {estimateRange(data) && (
            <p className="lit-price quote-data mb-2 text-lg text-primary text-glow-cyan">
              Working estimate: ${estimateRange(data).low} to ${estimateRange(data).high}
            </p>
          )}
          {ticket && <p className="mb-6 font-mono text-xs uppercase tracking-[0.25em] text-primary">Ticket {ticket}</p>}
          {fallbackMailto && (
            <div className="mb-6 max-w-xl rounded-xl border border-border bg-card p-4 text-sm text-muted-foreground">
              The server form was unavailable, so we opened a backup email draft with your custom request.
              <a href={fallbackMailto} className="mt-3 inline-flex font-heading text-xs uppercase tracking-wider text-primary hover:underline">Open email draft</a>
            </div>
          )}
          <div className="flex flex-col gap-3 sm:flex-row">
            <Button onClick={() => { setDone(false); setFallbackMailto(''); setTicket(''); setStep(0); set({ category: '', material: '', finish: '', qty: 1, size: 'Palm (≤3in)', notes: '', name: '', email: '' }); }}>Start another</Button>
            <Button variant="outline" onClick={onBack}>Back to Start a Piece</Button>
            <Button variant="outline" onClick={() => go('/work')}>Browse the work</Button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="scanlines">
      <div className="relative overflow-hidden">
        <div className="absolute inset-0 grid-floor opacity-20"></div>
        <div className="container relative mx-auto max-w-3xl py-16">
          <button onClick={onBack} className="mb-8 flex items-center gap-2 font-heading text-xs uppercase tracking-wider text-muted-foreground transition-colors hover:text-primary">
            <Icon name="arrow-left" /> Start a Piece
          </button>
          <div className="mb-10 text-center">
            <Eyebrow accent="magenta"><span className="mx-auto">Made to order</span></Eyebrow>
            <h1 className="crt-head mb-4 font-heading text-4xl md:text-5xl" style={{ letterSpacing: '-0.02em' }}>Custom request</h1>
            <p className="mx-auto max-w-xl text-lg text-muted-foreground">Five quick steps to a brief. No account, no commitment. Just enough for us to scope it and quote it.</p>
          </div>

          <StepDots step={step} />

          <div ref={stepCardRef} className="rounded-2xl border border-border bg-card p-6 md:p-10">
            {/* STEP 0 - category */}
            {step === 0 && (
              <div>
                <h2 className="crt-head mb-1 font-heading text-2xl tracking-wide">What are we making?</h2>
                <p className="mb-6 text-sm text-muted-foreground">Pick the closest fit. We'll figure out the details together.</p>
                <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                  {COMMISSION_CATEGORIES.map((c) => (
                    <OptionCard key={c.id} title={c.label} note={c.note} accent="cyan" selected={data.category === c.id} onClick={() => set({ category: c.id })} />
                  ))}
                </div>
              </div>
            )}

            {/* STEP 1 - material */}
            {step === 1 && (
              <div>
                <h2 className="crt-head mb-1 font-heading text-2xl tracking-wide">Pick a material</h2>
                <p className="mb-6 text-sm text-muted-foreground">Each one prints, feels and finishes differently. Not sure? Let us recommend.</p>
                <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                  {COMMISSION_MATERIALS.map((m) => (
                    <OptionCard key={m.id} title={m.label} note={m.note} accent={m.accent} swatch selected={data.material === m.id} onClick={() => set({ material: m.id })} />
                  ))}
                </div>
              </div>
            )}

            {/* STEP 2 - finish */}
            {step === 2 && (
              <div>
                <h2 className="crt-head mb-1 font-heading text-2xl tracking-wide">Choose a finish</h2>
                <p className="mb-6 text-sm text-muted-foreground">Keep it paintable, finish it in color, or add the FreshWave glow layer.</p>
                <div className="grid grid-cols-1 gap-3 md:grid-cols-3">
                  {COMMISSION_FINISHES.map((f) => (
                    <OptionCard key={f.id} title={f.label} note={f.note} accent="vapor-purple" selected={data.finish === f.id} onClick={() => set({ finish: f.id })} />
                  ))}
                </div>
              </div>
            )}

            {/* STEP 3 - scope */}
            {step === 3 && (
              <div>
                <h2 className="crt-head mb-1 font-heading text-2xl tracking-wide">Size & scope</h2>
                <p className="mb-6 text-sm text-muted-foreground">Rough is fine. It just helps us scope the print time.</p>
                <label className="mb-2 block font-heading text-xs uppercase tracking-wider text-muted-foreground">Approx. size</label>
                <div className="flex flex-wrap gap-3">
                  {sizes.map((s) => (
                    <Button key={s} size="sm" className="font-data text-sm tracking-[0.04em]" variant={data.size === s ? 'default' : 'outline'} onClick={() => set({ size: s })}>{s}</Button>
                  ))}
                </div>
                <label className="mb-2 mt-8 block font-heading text-xs uppercase tracking-wider text-muted-foreground">How many?</label>
                <div className="flex items-center gap-4">
                  <button onClick={() => set({ qty: Math.max(1, data.qty - 1) })} onPointerDown={triggerButtonSparks} className="spark-button flex h-12 w-12 items-center justify-center rounded-lg border border-border text-2xl hover:border-primary hover:text-primary">−</button>
                  <span className="quote-data w-16 text-center text-3xl text-primary">{data.qty}</span>
                  <button onClick={() => set({ qty: data.qty + 1 })} onPointerDown={triggerButtonSparks} className="spark-button flex h-12 w-12 items-center justify-center rounded-lg border border-border text-2xl hover:border-primary hover:text-primary">+</button>
                  <span className="ml-2 text-sm text-muted-foreground">{data.qty === 1 ? 'piece' : 'pieces'}</span>
                </div>
              </div>
            )}

            {/* STEP 4 - details */}
            {step === 4 && (
              <div>
                <h2 className="crt-head mb-1 font-heading text-2xl tracking-wide">Tell us about it</h2>
                <p className="mb-6 text-sm text-muted-foreground">A sentence or a spec sheet. Whatever you've got. Attach files later by email.</p>
                <div className="space-y-5">
                  <div className="grid gap-5 sm:grid-cols-2">
                    <Field label="Name *">
                      <input value={data.name} onChange={(e) => set({ name: e.target.value })} placeholder="Maya Chen" className="fw-input" />
                    </Field>
                    <Field label="Email *">
                      <input type="email" value={data.email} onChange={(e) => set({ email: e.target.value })} placeholder="maya@example.com" className="fw-input" />
                    </Field>
                  </div>
                  <Field label="The brief">
                    <textarea value={data.notes} onChange={(e) => set({ notes: e.target.value })} rows={5} placeholder="What is it, what's it for, any deadline or reference…" className="fw-input resize-none"></textarea>
                  </Field>
                  <CommissionSummary data={data} />
                </div>
              </div>
            )}

            {/* live estimate + nav */}
            <div className="mt-8 border-t border-border pt-6">
              {estimateRange(data) && (
                <div className="mb-5 flex flex-wrap items-center justify-between gap-3 rounded-xl border border-border bg-background/50 p-4" style={{ borderColor: accentHsl('cyan', 0.3) }}>
                  <div>
                    <div className="font-mono text-[10px] uppercase tracking-[0.25em] text-muted-foreground">Estimated range</div>
                    <div className="lit-price quote-data text-2xl text-primary text-glow-cyan">
                      ${estimateRange(data).low}<span className="px-1 text-muted-foreground">to</span>${estimateRange(data).high}
                    </div>
                  </div>
                  <div className="max-w-[16rem] text-right font-mono text-[10px] leading-relaxed text-muted-foreground">
                    Ballpark only. Final quote confirmed within 72h.
                  </div>
                </div>
              )}
              <div className="flex items-center justify-between gap-4">
                <button onClick={back} disabled={step === 0} className="flex items-center gap-2 font-heading text-xs uppercase tracking-wider text-muted-foreground transition-colors enabled:hover:text-primary disabled:opacity-30">
                  <Icon name="arrow-left" /> Back
                </button>
                <span className="hidden font-mono text-xs text-muted-foreground sm:inline">Step {step + 1} / {COMMISSION_STEPS.length}</span>
                <Button onClick={next} disabled={!canNext() || sending}>
                  {sending ? (<><Icon name="spinner" /> Sending...</>) : (<>{step === COMMISSION_STEPS.length - 1 ? 'Send brief' : 'Continue'} <Icon name="arrow-right" /></>)}
                </Button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Field({ label, children }) {
  return (
    <div className="space-y-2">
      <label className="block font-heading text-xs uppercase tracking-wider text-muted-foreground">{label}</label>
      {children}
    </div>
  );
}

function CommissionSummary({ data }) {
  const cat = (COMMISSION_CATEGORIES.find((c) => c.id === data.category) || {}).label || 'Not selected';
  const mat = (COMMISSION_MATERIALS.find((m) => m.id === data.material) || {}).label || 'Not selected';
  const fin = (COMMISSION_FINISHES.find((f) => f.id === data.finish) || {}).label || 'Not selected';
  const rows = [['Category', cat], ['Material', mat], ['Finish', fin], ['Size', data.size], ['Quantity', String(data.qty)]];
  return (
    <div className="rounded-xl border border-border bg-background/50 p-5">
      <div className="mb-3 font-mono text-[10px] uppercase tracking-[0.25em] text-muted-foreground">Your brief so far</div>
      <div className="grid grid-cols-2 gap-x-6 gap-y-2 sm:grid-cols-3">
        {rows.map(([k, v]) => (
          <div key={k}>
            <div className="font-mono text-[10px] uppercase tracking-wider text-muted-foreground">{k}</div>
            <div className="text-sm">{v}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { CommissionPage, SleepersPage, SleepersCataloguePage, Field });
