/* ============================================================
   CUSTOMIZED ADIRE — made-to-order request flow
   Landing → Request form → On-site confirmation
   Exports: CustomOrderPage
   ============================================================ */

function CustomOrderPage() {
  const [phase, setPhase] = useState('land'); // land | form | done
  const [data, setData] = useState({
    type: '', qty: '', mark: '', colour: '', date: '', budget: '', brief: '',
  });
  const set = (k, v) => setData(d => ({ ...d, [k]: v }));

  if (phase === 'land') return <CoLanding onStart={() => setPhase('form')} />;
  if (phase === 'form') return <CoForm data={data} set={set} onNext={() => setPhase('done')} onBack={() => setPhase('land')} />;
  return <CoDone data={data} />;
}

/* ── Landing ─────────────────────────────────────────────── */
function CoLanding({ onStart }) {
  const { nav } = useStore();
  return (
    <div>
      {/* Hero */}
      <div style={{ background: 'linear-gradient(160deg, var(--gold-soft), var(--cream))', padding: 'clamp(64px,10vw,110px) var(--gutter)', position: 'relative', overflow: 'hidden', borderBottom: '1px solid var(--line)' }}>
        <div className="container wide" style={{ position: 'relative', zIndex: 1, display: 'grid', gridTemplateColumns: '1fr auto', gap: 48, alignItems: 'center' }}>
          <div>
            <p className="eyebrow" style={{ color: 'var(--gold-deep)' }}>Customized · Made to order</p>
            <h1 style={{ fontSize: 'clamp(46px,7vw,92px)', color: 'var(--ink)', margin: '14px 0 20px', lineHeight: .94 }}>
              Your name,<br/>
              <em style={{ fontStyle: 'italic', background: 'linear-gradient(120deg,var(--gold-deep),var(--gold) 45%,var(--blush))', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>dyed into the cloth.</em>
            </h1>
            <p style={{ fontSize: 'clamp(15px,1.5vw,18px)', color: 'var(--ink-soft)', maxWidth: 520, lineHeight: 1.72, marginBottom: 34 }}>
              Names, monograms and brand marks resist-dyed by hand into your own adire — for families, couples, celebrants, aso-ebi and businesses. Tell us your idea and we'll send you a quote.
            </p>
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
              <button className="btn btn-primary btn-lg" onClick={onStart}>
                <span>Start my request</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>
              <button className="btn btn-outline btn-lg" onClick={() => nav('shop')}>Browse the shop</button>
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {[['Any name', 'or monogram'], ['Any mark', 'logos & brands'], ['100%', 'soft cotton']].map(([n, l]) => (
              <div key={l} style={{ background: 'var(--ivory)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', padding: '20px 28px', textAlign: 'center', boxShadow: 'var(--shadow-sm)' }}>
                <div style={{ fontFamily: 'var(--serif)', fontSize: 30, color: 'var(--ink)', lineHeight: 1 }}>{n}</div>
                <div style={{ fontSize: 10, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--ink-faint)', 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 idea to <em style={{ fontStyle: 'italic' }}>doorstep</em></h2>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 22 }}>
            {[
              ['Share your idea', 'Tell us the name, mark or design you want and how much cloth you need.'],
              ['We quote', 'We reply with a price and timing for your customized adire.'],
              ['We dye by hand', 'Once confirmed, your cloth is resist-dyed by hand — no two pieces alike.'],
              ['Delivered', 'Your finished adire is dispatched to you, nationwide.'],
            ].map(([t, d], i) => (
              <div key={t}>
                <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,76,142,.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 my request</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>
            <p style={{ fontSize: 13, color: 'var(--ink-soft)', marginTop: 14 }}>Ask about current offers when you send your request.</p>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ── Request form ─────────────────────────────────────────── */
function CoForm({ data, set, onNext, onBack }) {
  const validate = () => {
    if (!data.type || !data.brief.trim()) { alert('Please choose a request type and describe what you would like.'); 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 2</p>
          <h2 style={{ fontSize: 'clamp(28px,4vw,42px)', margin: '10px 0 6px' }}>Your <em style={{ fontStyle: 'italic' }}>request</em></h2>
          <p style={{ fontSize: 15, color: 'var(--ink-soft)', marginBottom: 28, lineHeight: 1.65 }}>The more detail you share, 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 }}>Request type <span style={{ color: 'var(--blush)' }}>*</span></label>
              <select className="input" value={data.type} onChange={e => set('type', e.target.value)}>
                <option value="" disabled>Select type</option>
                {['Customized name / monogram', 'Brand mark / logo (bulk)', 'Aso-ebi / family set', 'Traditional design', 'Wholesale / reseller', '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 }}>Quantity</label>
              <select className="input" value={data.qty} onChange={e => set('qty', e.target.value)}>
                <option value="" disabled>How much cloth?</option>
                {['1 bundle (4.5–5 yd)', '2–4 bundles', '5+ bundles (wholesale)', 'A few pieces', 'Not sure yet'].map(o => <option key={o}>{o}</option>)}
              </select>
            </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 }}>Name / mark to dye in</label>
              <input className="input" value={data.mark} onChange={e => set('mark', e.target.value)} placeholder="e.g. “Adewale ’25” or a logo" />
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
              <label style={{ fontSize: 11, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--ink-soft)', fontWeight: 500 }}>When do you need it?</label>
              <input type="date" className="input" value={data.date} onChange={e => set('date', 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 }}>Colour preference</label>
              <select className="input" value={data.colour} onChange={e => set('colour', e.target.value)}>
                <option value="" disabled>Select</option>
                {['Classic indigo', 'Deep navy', 'Indigo & white', 'Open to suggestions'].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 }}>Approx. budget</label>
              <select className="input" value={data.budget} onChange={e => set('budget', e.target.value)}>
                <option value="" disabled>Select range</option>
                {['Under ₦20,000', '₦20,000 – ₦50,000', '₦50,000 – ₦100,000', '₦100,000 – ₦250,000', '₦250,000+'].map(o => <option key={o}>{o}</option>)}
              </select>
            </div>
          </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 }}>Describe your request <span style={{ color: 'var(--blush)' }}>*</span></label>
            <textarea className="input" rows="5" value={data.brief} onChange={e => set('brief', e.target.value)}
              placeholder="Tell us about the design, the occasion, any pattern you love (oniko, eleko, alabere…), and anything else we should know." />
          </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>Review & send</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>
  );
}

/* ── Done: on-site confirmation ── */
function CoDone({ data }) {
  const { nav } = useStore();
  const ref = React.useMemo(() => BB.BRAND.orderPrefix + '-' + Math.floor(100000 + Math.random() * 900000), []);

  return (
    <div style={{ background: 'var(--cream)', minHeight: '80vh' }}>
      <CoProgressBar step={2} />
      <div className="container" style={{ maxWidth: 680, padding: 'clamp(40px,7vw,80px) var(--gutter)', textAlign: 'center' }}>
        <div style={{ width: 76, height: 76, borderRadius: '50%', background: 'linear-gradient(135deg,var(--gold-deep),var(--gold))', display: 'grid', placeItems: 'center', color: '#fff', margin: '0 auto 24px', boxShadow: '0 10px 36px rgba(44,76,142,.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>
        <p className="eyebrow" style={{ color: 'var(--gold-deep)', marginBottom: 10 }}>Request received</p>
        <h2 style={{ fontSize: 'clamp(36px,5vw,56px)', marginBottom: 14 }}>Thank <em style={{ fontStyle: 'italic' }}>you</em></h2>
        <p style={{ fontSize: 16, color: 'var(--ink-soft)', lineHeight: 1.75, maxWidth: 480, margin: '0 auto 24px' }}>
          Your customized adire request has been sent to our team. We'll get back to you with a price and timing for your piece.
        </p>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10, background: 'var(--ivory)', border: '1px solid var(--line)', borderRadius: 100, padding: '10px 22px', marginBottom: 28 }}>
          <span style={{ fontSize: 13, color: 'var(--ink-soft)' }}>Reference</span>
          <strong style={{ color: 'var(--gold-deep)' }}>{ref}</strong>
        </div>
        <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
          <button className="btn btn-gold btn-lg" onClick={() => nav('shop')}>Browse the shop</button>
          <button className="btn btn-outline btn-lg" onClick={() => nav('home')}>Back home</button>
        </div>
        <p style={{ fontSize: 12.5, color: 'var(--ink-faint)', marginTop: 20 }}>Payment details are shared when your order is confirmed.</p>
      </div>
    </div>
  );
}

/* ── Shared progress bar ─────────────────────────────────── */
function CoProgressBar({ step }) {
  const labels = ['Your request', 'Send'];
  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 < labels.length - 1 && <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 });
