/* ============================================================
   CUSTOM ORDERS — open-ended bespoke intake flow
   Steps: Landing → Details → Brief + Links → Schedule → Draft
   Exports: CustomOrderPage
   ============================================================ */

function CustomOrderPage() {
  const [phase, setPhase] = useState('land'); // land | form | schedule | done
  const [formData, setFormData] = useState({
    eventType: '', eventDate: '', guests: '', budget: '',
    brief: '', urls: [''],
    inspiration: [], // catalogue product refs {id, name, img}
    scheduleMode: null, // 'async' | 'call'
  });
  const setF = (k, v) => setFormData(f => ({ ...f, [k]: v }));

  if (phase === 'land')     return <CoLanding     onStart={() => setPhase('form')} />;
  if (phase === 'form')     return <CoForm        data={formData} set={setF} onNext={() => setPhase('schedule')} onBack={() => setPhase('land')} />;
  if (phase === 'schedule') return <CoSchedule    data={formData} set={setF} onNext={() => setPhase('done')} onBack={() => setPhase('form')} />;
  if (phase === 'done')     return <CoDraft       data={formData} />;
  return null;
}

/* ── Landing ─────────────────────────────────────────────── */
function CoLanding({ onStart }) {
  const { nav } = useStore();
  return (
    <div>
      {/* Hero */}
      <div style={{ background: 'var(--ink)', padding: 'clamp(64px,10vw,110px) var(--gutter)', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(ellipse 80% 70% at 65% 50%, rgba(44,85,48,.22) 0%, transparent 65%), radial-gradient(ellipse 50% 60% at 15% 80%, rgba(122,37,53,.1) 0%, transparent 60%)', pointerEvents: 'none' }} />
        <div className="container wide" style={{ position: 'relative', zIndex: 1, display: 'grid', gridTemplateColumns: '1fr auto', gap: 48, alignItems: 'center' }}>
          <div>
            <p className="eyebrow" style={{ color: 'rgba(255,255,255,.5)' }}>Bespoke · Open-ended · No fixed menu</p>
            <h1 style={{ fontSize: 'clamp(48px,7vw,96px)', color: '#fff', margin: '14px 0 20px', lineHeight: .94 }}>
              Your vision,<br/>
              <em style={{ fontStyle: 'italic', background: 'linear-gradient(135deg,#4A6E4C 10%,#7A2535 90%)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>built for you.</em>
            </h1>
            <p style={{ fontSize: 'clamp(15px,1.5vw,18px)', color: 'rgba(255,255,255,.65)', maxWidth: 500, lineHeight: 1.72, marginBottom: 34 }}>
              Submit a brief describing exactly what you have in mind. Our team quotes personally, you approve, then we create.
            </p>
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
              <button className="btn btn-primary btn-lg" onClick={onStart}>
                <span>Start my brief</span>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 6l6 6-6 6" strokeLinecap="round" strokeLinejoin="round"/></svg>
              </button>
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {[['1,800+','Orders made'],['100%','Handcrafted'],['48h','Quote turnaround']].map(([n, l]) => (
              <div key={l} style={{ background: 'rgba(255,255,255,.07)', border: '1px solid rgba(255,255,255,.12)', borderRadius: 'var(--r-lg)', padding: '20px 28px', textAlign: 'center' }}>
                <div style={{ fontFamily: 'var(--serif)', fontSize: 32, color: '#fff', lineHeight: 1 }}>{n}</div>
                <div style={{ fontSize: 10, letterSpacing: '.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,.45)', marginTop: 5 }}>{l}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* How it works */}
      <div style={{ background: 'var(--cream-deep)', padding: 'clamp(56px,8vw,96px) var(--gutter)' }}>
        <div className="container wide">
          <div style={{ textAlign: 'center', marginBottom: 48 }}>
            <p className="eyebrow">The process</p>
            <h2 style={{ fontSize: 'clamp(32px,4.5vw,54px)', marginTop: 12 }}>From brief to <em style={{ fontStyle: 'italic' }}>doorstep</em></h2>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 22 }}>
            {[
              ['Submit brief', 'Describe your event, theme, quantities and any inspiration links. Takes under 5 minutes.'],
              ['We quote', 'Within 48 hours you receive a personalised, itemised proposal — no surprises.'],
              ['Approve & pay', 'Accept the quote and pay the 50% deposit. We get to work immediately.'],
              ['We deliver', 'Track your order live. Items arrive beautifully packed, on time.'],
            ].map(([t, d], i) => (
              <div key={t} style={{ position: 'relative' }}>
                <div style={{ width: 44, height: 44, borderRadius: '50%', background: 'linear-gradient(135deg,var(--gold-deep),var(--gold))', display: 'grid', placeItems: 'center', color: '#fff', fontFamily: 'var(--serif)', fontSize: 20, boxShadow: '0 4px 14px rgba(44,85,48,.25)', marginBottom: 16 }}>{i + 1}</div>
                <h3 style={{ fontSize: 20, marginBottom: 8 }}>{t}</h3>
                <p style={{ fontSize: 14.5, color: 'var(--ink-soft)', lineHeight: 1.65 }}>{d}</p>
              </div>
            ))}
          </div>
          <div style={{ textAlign: 'center', marginTop: 48 }}>
            <button className="btn btn-primary btn-lg" onClick={onStart}>
              <span>Start your brief</span>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 6l6 6-6 6" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ── Step 1: Event details + brief + links ────────────────── */
function CoForm({ data, set, onNext, onBack }) {
  const [urls, setUrls] = useState(data.urls.length ? data.urls : ['']);
  const updateUrl = (i, v) => { const u = [...urls]; u[i] = v; setUrls(u); set('urls', u); };
  const addUrl    = () => { const u = [...urls, '']; setUrls(u); set('urls', u); };
  const removeUrl = (i) => { const u = urls.filter((_, j) => j !== i); setUrls(u.length ? u : ['']); set('urls', u.length ? u : ['']); };
  const [inspoProducts, setInspoProducts] = useState(data.inspirationProductIds || []);
  const toggleInspoProduct = (id) => { const next = inspoProducts.includes(id) ? inspoProducts.filter(x => x !== id) : [...inspoProducts, id]; setInspoProducts(next); set('inspirationProductIds', next); };

  const [catalogueOpen, setCatalogueOpen] = useState(false);
  const inspiration = data.inspiration || [];
  const removeInspiration = (id) => set('inspiration', inspiration.filter(p => p.id !== id));

  const validate = () => {
    if (!data.eventType || !data.eventDate || !data.brief.trim()) {
      alert('Please fill in the event type, date and project brief.'); return false;
    }
    return true;
  };

  return (
    <div style={{ background: 'var(--cream)', minHeight: '80vh' }}>
      <CoProgressBar step={1} />
      <div className="container" style={{ maxWidth: 720, padding: 'clamp(36px,5vw,56px) var(--gutter)' }}>
        <div style={{ background: 'var(--ivory)', border: '1px solid var(--line)', borderRadius: 'var(--r-xl)', padding: 'clamp(28px,4vw,48px)' }}>
          <p className="eyebrow">Step 1 of 3</p>
          <h2 style={{ fontSize: 'clamp(28px,4vw,42px)', margin: '10px 0 6px' }}>Event & <em style={{ fontStyle: 'italic' }}>brief</em></h2>
          <p style={{ fontSize: 15, color: 'var(--ink-soft)', marginBottom: 28, lineHeight: 1.65 }}>The more detail you give us, the more accurate your quote will be.</p>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 18 }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
              <label style={{ fontSize: 11, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--ink-soft)', fontWeight: 500 }}>Event type <span style={{ color: 'var(--blush)' }}>*</span></label>
              <select className="input" value={data.eventType} onChange={e => set('eventType', e.target.value)}>
                <option value="" disabled>Select type</option>
                {['Birthday party (child)','Birthday party (adult)','Baby shower','Naming ceremony','Gender reveal','Wedding / engagement','Corporate event','Other'].map(o => <option key={o}>{o}</option>)}
              </select>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
              <label style={{ fontSize: 11, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--ink-soft)', fontWeight: 500 }}>Event date <span style={{ color: 'var(--blush)' }}>*</span></label>
              <input type="date" className="input" value={data.eventDate} onChange={e => set('eventDate', e.target.value)} min={new Date().toISOString().split('T')[0]} />
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 18 }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
              <label style={{ fontSize: 11, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--ink-soft)', fontWeight: 500 }}>Guest count</label>
              <select className="input" value={data.guests} onChange={e => set('guests', e.target.value)}>
                <option value="" disabled>Approximate</option>
                {['Under 20','20 – 50','50 – 100','100 – 200','200+'].map(o => <option key={o}>{o}</option>)}
              </select>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
              <label style={{ fontSize: 11, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--ink-soft)', fontWeight: 500 }}>Approximate budget</label>
              <select className="input" value={data.budget} onChange={e => set('budget', e.target.value)}>
                <option value="" disabled>Select range</option>
                {['Under $65','$65 – $160','$160 – $315','$315 – $625','$625+'].map(o => <option key={o}>{o}</option>)}
              </select>
            </div>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 7, marginBottom: 18 }}>
            <label style={{ fontSize: 11, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--ink-soft)', fontWeight: 500 }}>Project brief <span style={{ color: 'var(--blush)' }}>*</span></label>
            <textarea className="input" rows="5" value={data.brief} onChange={e => set('brief', e.target.value)}
              placeholder="Describe your theme, colours, quantities, any specific characters or motifs, and anything else we should know. The more detail the better." />
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 7, marginBottom: 24 }}>
            <label style={{ fontSize: 11, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--ink-soft)', fontWeight: 500 }}>Inspiration links <span style={{ fontSize: 10, color: 'var(--ink-faint)', textTransform: 'none', letterSpacing: 0, marginLeft: 6 }}>Pinterest, Instagram, TikTok…</span></label>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {urls.map((u, i) => (
                <div key={i} style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                  <input type="url" className="input" value={u} onChange={e => updateUrl(i, e.target.value)} placeholder="https://pinterest.com/…" style={{ flex: 1 }} />
                  {urls.length > 1 && <button onClick={() => removeUrl(i)} style={{ width: 32, height: 32, borderRadius: '50%', background: 'var(--cream-deep)', color: 'var(--ink-faint)', display: 'grid', placeItems: 'center', cursor: 'pointer', border: 'none', flexShrink: 0 }}>
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6 6 18M6 6l12 12"/></svg>
                  </button>}
                </div>
              ))}
            </div>
            <button onClick={addUrl} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--gold-deep)', fontWeight: 500, background: 'none', border: 'none', cursor: 'pointer', marginTop: 4, alignSelf: 'flex-start' }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M12 5v14M5 12h14"/></svg>
              Add another link
            </button>

            {typeof BB !== 'undefined' && BB.products && BB.products.length > 0 && (
              <div style={{ marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--line)' }}>
                <label style={{ fontSize: 11, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--ink-soft)', fontWeight: 500, display: 'block', marginBottom: 12 }}>
                  Or pick pieces from our collection as inspiration{inspoProducts.length > 0 ? ` (${inspoProducts.length} selected)` : ''}
                </label>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(100px, 1fr))', gap: 10, maxHeight: 320, overflowY: 'auto' }}>
                  {BB.products.map((p) => {
                    const on = inspoProducts.includes(p.id);
                    return (
                      <button key={p.id} type="button" onClick={() => toggleInspoProduct(p.id)} style={{ position: 'relative', display: 'flex', flexDirection: 'column', gap: 6, textAlign: 'left', border: on ? '1.5px solid var(--gold-deep)' : '1.5px solid transparent', borderRadius: 'var(--r-md)', padding: 4, background: on ? 'rgba(200,151,31,.08)' : 'none', cursor: 'pointer' }}>
                        <Ph src={p.img} label={p.name} variant={p.ph} style={{ aspectRatio: '1/1', borderRadius: 'var(--r-sm)' }} />
                        <span style={{ fontSize: 11.5, lineHeight: 1.3, color: on ? 'var(--ink)' : 'var(--ink-soft)' }}>{p.name}</span>
                        {on && <span style={{ position: 'absolute', top: 8, right: 8, width: 20, height: 20, borderRadius: '50%', background: 'var(--gold-deep)', color: '#fff', display: 'grid', placeItems: 'center', fontSize: 11 }}>✓</span>}
                      </button>
                    );
                  })}
                </div>
              </div>
            )}
          </div>

          {/* Inspiration from catalogue */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 7, marginBottom: 24 }}>
            <label style={{ fontSize: 11, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--ink-soft)', fontWeight: 500 }}>Inspiration <span style={{ fontSize: 10, color: 'var(--ink-faint)', textTransform: 'none', letterSpacing: 0, marginLeft: 6 }}>Pick pieces from our catalogue you love</span></label>

            {inspiration.length > 0 && (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 4 }}>
                {inspiration.map(p => (
                  <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'var(--ivory)', border: '1px solid var(--line)', borderRadius: 100, padding: '5px 10px 5px 5px' }}>
                    <Ph src={p.img} label="" variant={p.ph} style={{ width: 28, height: 28, borderRadius: '50%', flexShrink: 0 }} />
                    <span style={{ fontSize: 13, color: 'var(--ink)', maxWidth: 140, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.name}</span>
                    <button onClick={() => removeInspiration(p.id)} aria-label={`Remove ${p.name}`} style={{ width: 20, height: 20, borderRadius: '50%', background: 'var(--cream-deep)', color: 'var(--ink-faint)', display: 'grid', placeItems: 'center', cursor: 'pointer', border: 'none', flexShrink: 0 }}>
                      <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M18 6 6 18M6 6l12 12"/></svg>
                    </button>
                  </div>
                ))}
              </div>
            )}

            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <button onClick={() => setCatalogueOpen(true)} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--gold-deep)', fontWeight: 500, background: 'none', border: '1px solid var(--line)', borderRadius: 100, padding: '9px 16px', cursor: 'pointer' }}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M12 5v14M5 12h14"/></svg>
                Add from catalogue
              </button>
              <span style={{ fontSize: 11.5, color: 'var(--ink-faint)' }}>{inspiration.length ? `${inspiration.length}/3 selected` : 'Up to 3'}</span>
            </div>
          </div>

          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', paddingTop: 24, borderTop: '1px solid var(--line)' }}>
            <button className="btn btn-secondary" onClick={onBack} style={{ padding: '15px 24px', fontSize: 12 }}>← Back</button>
            <button className="btn btn-primary" onClick={() => validate() && onNext()}>
              <span>Continue</span>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 6l6 6-6 6" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </button>
          </div>
        </div>
      </div>

      {catalogueOpen && (
        <CatalogueModal
          selected={inspiration}
          onClose={() => setCatalogueOpen(false)}
          onToggle={(p) => {
            const exists = inspiration.some(x => x.id === p.id);
            if (!exists && inspiration.length >= 3) return;
            set('inspiration', exists ? inspiration.filter(x => x.id !== p.id) : [...inspiration, { id: p.id, name: p.name, img: p.img, ph: p.ph }]);
          }}
        />
      )}
    </div>
  );
}

/* ── Catalogue inspiration picker modal ──────────────────── */
function CatalogueModal({ selected, onClose, onToggle }) {
  const [q, setQ] = useState('');
  const selectedIds = new Set(selected.map(p => p.id));
  const list = (q.trim() ? BB.products.filter(p => (p.name + ' ' + p.short).toLowerCase().includes(q.toLowerCase())) : BB.products);

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 220 }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(42,17,51,.38)', backdropFilter: 'blur(3px)' }} />
      <aside style={{ position: 'absolute', top: 0, right: 0, height: '100%', width: 'min(480px, 100vw)', background: 'var(--cream)', boxShadow: 'var(--shadow-lg)', display: 'flex', flexDirection: 'column' }}>
        <header style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '24px 28px', borderBottom: '1px solid var(--line)' }}>
          <div>
            <h3 style={{ fontSize: 22 }}>Add from catalogue</h3>
            <p style={{ fontSize: 13, color: 'var(--ink-soft)', marginTop: 4 }}>Select pieces you'd like us to use as inspiration. <strong>{selected.length >= 3 ? `Max 3 selected (${selected.length}/3)` : 'Up to 3'}</strong></p>
          </div>
          <button onClick={onClose} aria-label="Close" style={{ width: 34, height: 34, borderRadius: '50%', background: 'var(--cream-deep)', display: 'grid', placeItems: 'center', border: 'none', cursor: 'pointer', flexShrink: 0 }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6 6 18M6 6l12 12"/></svg>
          </button>
        </header>

        <div style={{ padding: '16px 28px 0' }}>
          <input value={q} onChange={e => setQ(e.target.value)} className="input" placeholder="Search the catalogue…" style={{ width: '100%' }} />
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: '16px 28px 28px', display: 'flex', flexDirection: 'column', gap: 6 }}>
          {list.map(p => {
            const isSel = selectedIds.has(p.id);
            const atCap = selected.length >= 3 && !isSel;
            return (
              <button key={p.id} onClick={() => onToggle(p)} disabled={atCap} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: 10, borderRadius: 'var(--r-md)', textAlign: 'left', border: '1.5px solid', borderColor: isSel ? 'var(--gold)' : 'transparent', background: isSel ? 'var(--gold-soft)' : 'transparent', cursor: atCap ? 'not-allowed' : 'pointer', opacity: atCap ? .4 : 1, transition: 'all .2s' }}>
                <Ph src={p.img} label="" variant={p.ph} style={{ width: 52, height: 62, borderRadius: 'var(--r-sm)', flexShrink: 0 }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: 'var(--serif)', fontSize: 18 }}>{p.name}</div>
                  <div style={{ fontSize: 12.5, color: 'var(--ink-soft)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.short}</div>
                </div>
                <div style={{ width: 24, height: 24, borderRadius: '50%', display: 'grid', placeItems: 'center', flexShrink: 0, background: isSel ? 'var(--gold)' : 'var(--cream-deep)', color: isSel ? '#fff' : 'var(--ink-faint)' }}>
                  {isSel && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="m5 13 4 4 10-11" strokeLinecap="round" strokeLinejoin="round"/></svg>}
                </div>
              </button>
            );
          })}
          {list.length === 0 && <p className="muted" style={{ padding: 12 }}>No matches.</p>}
        </div>

        <footer style={{ padding: '16px 28px', borderTop: '1px solid var(--line)' }}>
          <button className="btn btn-primary" onClick={onClose} style={{ width: '100%', justifyContent: 'center' }}>
            <span>Done{selected.length ? ` · ${selected.length} selected` : ''}</span>
          </button>
        </footer>
      </aside>
    </div>
  );
}

/* ── Step 2: Scheduling preference ───────────────────────── */
function CoSchedule({ data, set, onNext, onBack }) {
  const [mode, setMode] = useState(data.scheduleMode);
  const choose = (m) => { setMode(m); set('scheduleMode', m); };

  return (
    <div style={{ background: 'var(--cream)', minHeight: '80vh' }}>
      <CoProgressBar step={2} />
      <div className="container" style={{ maxWidth: 720, padding: 'clamp(36px,5vw,56px) var(--gutter)' }}>
        <div style={{ background: 'var(--ivory)', border: '1px solid var(--line)', borderRadius: 'var(--r-xl)', padding: 'clamp(28px,4vw,48px)' }}>
          <p className="eyebrow">Step 2 of 3</p>
          <h2 style={{ fontSize: 'clamp(28px,4vw,42px)', margin: '10px 0 6px' }}>How shall we <em style={{ fontStyle: 'italic' }}>respond?</em></h2>
          <p style={{ fontSize: 15, color: 'var(--ink-soft)', marginBottom: 28, lineHeight: 1.65 }}>Choose how you'd like us to get back to you with your personalised quote.</p>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 24 }}>
            {[
              ['async', 'Async review', 'We\'ll review your brief and email a detailed quote within 48 hours. No call needed.', 'mail'],
              ['call', 'Book a call', 'Prefer to talk it through? Choose a slot and we\'ll discuss your vision together.', 'calendar'],
            ].map(([m, t, d, icon]) => (
              <button key={m} onClick={() => choose(m)} style={{ textAlign: 'left', padding: '20px 22px', borderRadius: 'var(--r-lg)', border: '1.5px solid', cursor: 'pointer', transition: 'all .25s',
                borderColor: mode === m ? 'var(--gold)' : 'var(--line)',
                background: mode === m ? 'var(--gold-soft)' : 'var(--cream)' }}>
                <div style={{ width: 38, height: 38, borderRadius: 'var(--r-sm)', background: mode === m ? 'var(--gold)' : 'var(--cream-deep)', display: 'grid', placeItems: 'center', color: mode === m ? '#fff' : 'var(--ink-soft)', marginBottom: 12, transition: 'all .25s' }}>
                  {icon === 'mail' && <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>}
                  {icon === 'calendar' && <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>}
                </div>
                <div style={{ fontWeight: 500, fontSize: 15, marginBottom: 6, color: 'var(--ink)' }}>{t}</div>
                <div style={{ fontSize: 13.5, color: 'var(--ink-soft)', lineHeight: 1.6 }}>{d}</div>
              </button>
            ))}
          </div>

          {/* Async message */}
          {mode === 'async' && (
            <div style={{ background: 'var(--sage-soft)', border: '1px solid var(--line)', borderLeft: '3px solid var(--sage)', borderRadius: 'var(--r-md)', padding: '18px 22px', marginBottom: 24 }}>
              <p style={{ fontSize: 14.5, color: 'var(--ink)', lineHeight: 1.65 }}>
                Our team will review your brief and send a personalised proposal within <strong>48 hours</strong>. You'll receive a detailed quote with an itemised breakdown and a secure link to review and pay.
              </p>
            </div>
          )}

          {/* Booking widget */}
          {mode === 'call' && (
            <div style={{ background: 'var(--cream-deep)', borderRadius: 'var(--r-lg)', marginBottom: 24, overflow: 'hidden', border: '1px solid var(--line)' }}>
              <BookingWidget onConfirm={(details) => { set('booking', details); }} compact={true} />
            </div>
          )}

          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', paddingTop: 24, borderTop: '1px solid var(--line)' }}>
            <button className="btn btn-secondary" onClick={onBack} style={{ padding: '15px 24px', fontSize: 12 }}>← Back</button>
            <button className="btn btn-primary" onClick={onNext} disabled={!mode} style={{ opacity: mode ? 1 : .45 }}>
              <span>Submit brief</span>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m5 13 4 4 10-11" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ── Step 3: Draft confirmation ───────────────────────────── */
function CoDraft({ data }) {
  const { nav } = useStore();
  const ref = 'DRF-' + Math.floor(100000 + Math.random() * 900000);
  const [copied, setCopied] = useState(false);
  const copy = () => { navigator.clipboard.writeText(ref).catch(() => {}); setCopied(true); setTimeout(() => setCopied(false), 2000); };

  return (
    <div style={{ background: 'var(--cream)', minHeight: '80vh' }}>
      <CoProgressBar step={3} />
      <div className="container" style={{ maxWidth: 680, padding: 'clamp(40px,7vw,80px) var(--gutter)', textAlign: 'center' }}>
        {/* Icon */}
        <div style={{ position: 'relative', display: 'inline-flex', marginBottom: 28 }}>
          <div style={{ position: 'absolute', inset: -10, borderRadius: '50%', border: '1.5px solid rgba(44,85,48,.2)', animation: 'ringPop .6s .15s ease forwards', opacity: 0, transform: 'scale(.7)' }} />
          <div style={{ width: 76, height: 76, borderRadius: '50%', background: 'linear-gradient(135deg,var(--gold-deep),var(--gold))', display: 'grid', placeItems: 'center', color: '#fff', boxShadow: '0 10px 36px rgba(44,85,48,.3)' }}>
            <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m5 13 4 4 10-11" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </div>
        </div>

        <p className="eyebrow" style={{ color: 'var(--gold-deep)', marginBottom: 10 }}>Brief received</p>
        <h2 style={{ fontSize: 'clamp(38px,5.5vw,60px)', marginBottom: 14 }}>You're <em style={{ fontStyle: 'italic' }}>all set!</em></h2>
        <p style={{ fontSize: 16, color: 'var(--ink-soft)', lineHeight: 1.75, maxWidth: 480, margin: '0 auto 28px' }}>
          {data.scheduleMode === 'call'
            ? "Your brief and consultation slot are both confirmed. We\u2019ll send a full personalised proposal after the call."
            : "Your brief has been saved. Our team will review it and send a personalised proposal within 48 hours."}
        </p>

        {/* Reference */}
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 12, background: 'var(--ivory)', border: '1px solid var(--line)', borderRadius: 100, padding: '10px 22px', marginBottom: 36 }}>
          <span style={{ fontSize: 13, color: 'var(--ink-soft)' }}>Reference</span>
          <strong style={{ color: 'var(--gold-deep)', letterSpacing: '.06em' }}>{ref}</strong>
          <button onClick={copy} style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, letterSpacing: '.1em', textTransform: 'uppercase', color: copied ? 'var(--sage)' : 'var(--ink-faint)', background: 'none', border: 'none', cursor: 'pointer' }}>
            {copied ? '✓ Copied' : 'Copy'}
          </button>
        </div>

        {/* Next steps */}
        <div style={{ background: 'var(--ivory)', border: '1px solid var(--line)', borderRadius: 'var(--r-xl)', padding: '28px 32px', textAlign: 'left', marginBottom: 32 }}>
          <h3 style={{ fontSize: 22, marginBottom: 20 }}>What happens <em style={{ fontStyle: 'italic' }}>next</em></h3>
          {[
            ['✓', 'Brief submitted', 'Your project details are saved and being reviewed.', 'done'],
            ['→', data.scheduleMode === 'call' ? 'Consultation call' : 'Team review', data.scheduleMode === 'call' ? "We\u2019ll discuss your brief on the call and finalise details." : 'Our team reviews your brief within 24 hours.', 'active'],
            ['○', 'Personalised proposal', 'Itemised quote sent to your inbox with a secure payment link.', 'pending'],
            ['○', 'Order confirmed', '50% deposit locks in your slot. Balance due on delivery.', 'pending'],
          ].map(([icon, t, d, state]) => (
            <div key={t} style={{ display: 'flex', gap: 14, marginBottom: 18 }}>
              <div style={{ width: 28, height: 28, borderRadius: '50%', display: 'grid', placeItems: 'center', fontSize: 13, flexShrink: 0, marginTop: 2,
                background: state === 'done' ? 'var(--gold)' : state === 'active' ? 'var(--gold-soft)' : 'var(--cream-deep)',
                color: state === 'done' ? '#fff' : state === 'active' ? 'var(--gold-deep)' : 'var(--ink-faint)' }}>{icon}</div>
              <div>
                <div style={{ fontWeight: 500, fontSize: 14.5, color: state === 'pending' ? 'var(--ink-faint)' : 'var(--ink)' }}>{t}</div>
                <div style={{ fontSize: 13, color: 'var(--ink-soft)', marginTop: 2 }}>{d}</div>
              </div>
            </div>
          ))}
        </div>

        <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
          <button className="btn btn-primary" onClick={() => nav('home')}>
            <span>Back to store</span>
          </button>
          <button className="btn btn-secondary" onClick={() => nav('packages')}>Browse packages</button>
        </div>
      </div>
    </div>
  );
}

/* ── Shared progress bar ─────────────────────────────────── */
function CoProgressBar({ step }) {
  const labels = ['Details', 'Schedule', 'Confirmed'];
  return (
    <div style={{ background: 'var(--cream-deep)', borderBottom: '1px solid var(--line)', padding: '14px var(--gutter)' }}>
      <div className="container" style={{ maxWidth: 720, display: 'flex', alignItems: 'center' }}>
        {labels.map((l, i) => (
          <React.Fragment key={i}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{ width: 28, height: 28, borderRadius: '50%', display: 'grid', placeItems: 'center', fontSize: 12, transition: 'all .3s',
                background: step > i + 1 ? 'var(--sage)' : step === i + 1 ? 'var(--gold)' : 'var(--line)',
                color: step >= i + 1 ? '#fff' : 'var(--ink-faint)' }}>
                {step > i + 1 ? <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="m5 13 4 4 10-11" strokeLinecap="round" strokeLinejoin="round"/></svg> : i + 1}
              </div>
              <span style={{ fontSize: 11, letterSpacing: '.1em', textTransform: 'uppercase', fontWeight: step === i + 1 ? 500 : 400, color: step === i + 1 ? 'var(--gold-deep)' : 'var(--ink-faint)' }}>{l}</span>
            </div>
            {i < 2 && <div style={{ flex: 1, height: 1, background: step > i + 1 ? 'var(--sage)' : 'var(--line)', margin: '0 12px', transition: 'background .4s' }} />}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { CustomOrderPage });
