// Inquiry.jsx — occasion-aware bulk / corporate / wedding / events enquiry
const TOPICS = ['Corporate gifting', 'Wedding favours', 'Events & parties', 'Diwali / festive bulk', 'Personal celebration', 'Press / collaboration', 'Something else'];

function Inquiry() {
  const [form, setForm] = React.useState({ name: '', company: '', email: '', phone: '', topic: 'Corporate gifting', qty: '', date: '', city: '', budget: 'Flexible', message: '' });
  const [sent, setSent] = React.useState(false);
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));
  const formRef = React.useRef(null);

  // listen for category cards / nav routing a topic in
  React.useEffect(() => {
    const onEnq = (e) => {
      const t = e.detail && e.detail.topic;
      if (t && TOPICS.includes(t)) setForm((f) => ({ ...f, topic: t }));
    };
    window.addEventListener('bb-enquire', onEnq);
    return () => window.removeEventListener('bb-enquire', onEnq);
  }, []);

  const inputStyle = { width: '100%', padding: '13px 15px', background: 'var(--bb-pearl)', border: '1px solid var(--line)', borderRadius: 8, fontFamily: 'var(--font-serif)', fontSize: 16, color: 'var(--bb-cocoa)', outline: 'none', transition: 'border-color 240ms, box-shadow 240ms' };
  const labelStyle = { fontFamily: 'var(--font-display)', fontSize: 9.5, letterSpacing: '0.28em', color: 'var(--bb-gold-deep)', textTransform: 'uppercase', marginBottom: 7, display: 'block' };
  const selectStyle = { ...inputStyle, appearance: 'none', backgroundImage: 'linear-gradient(45deg, transparent 50%, var(--bb-gold-deep) 50%), linear-gradient(135deg, var(--bb-gold-deep) 50%, transparent 50%)', backgroundPosition: 'calc(100% - 18px) 21px, calc(100% - 13px) 21px', backgroundSize: '5px 5px, 5px 5px', backgroundRepeat: 'no-repeat' };
  const onFocus = (e) => { e.target.style.borderColor = 'var(--bb-gold)'; e.target.style.boxShadow = '0 0 0 3px rgba(201,164,92,0.18)'; };
  const onBlur = (e) => { e.target.style.borderColor = 'var(--line)'; e.target.style.boxShadow = 'none'; };

  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState('');

  const submit = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    setError('');
    try {
      const res = await fetch('http://localhost:3001/api/enquiry', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      if (!res.ok) throw new Error('Server error');
      setSent(true);
      setTimeout(() => setSent(false), 5000);
      setForm({ name: '', company: '', email: '', phone: '', topic: form.topic, qty: '', date: '', city: '', budget: 'Flexible', message: '' });
    } catch {
      setError('Could not send — please call or WhatsApp us directly.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <section id="enquiry" style={{ background: 'var(--bb-cream)', padding: 'var(--s-9) 32px' }}>
      <div style={{ maxWidth: 1180, margin: '0 auto' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,0.85fr) minmax(0,1.15fr)', gap: 'var(--s-8)', alignItems: 'start' }} className="bb-enq-grid">
          {/* left — pitch + details */}
          <div className="bb-reveal">
            <div className="bb-eyebrow">★ TELL US YOUR OCCASION</div>
            <h2 style={{ marginTop: 16, marginBottom: 18, fontSize: 'clamp(34px, 4vw, 54px)', lineHeight: 1.04 }}>
              Made for the moments<br />
              <span style={{ fontFamily: 'var(--font-script)', fontSize: '1.4em', color: 'var(--bb-gold-deep)', letterSpacing: 0, fontWeight: 400, lineHeight: 0.85 }}>that matter most.</span>
            </h2>
            <p className="lede" style={{ marginBottom: 28, maxWidth: 420 }}>
              Diwali hampers for the team, a wedding tray for two hundred guests, or a single ribbon-tied box for a dear friend. Tell us what you're planning — we reply within one working day.
            </p>
            {(() => {
              const _co = (window.BB_CONTENT || {}).contact || {};
              const co = (k, d) => (_co[k] || d);
              return (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 18, padding: '24px', background: 'var(--bb-parchment)', border: '1px solid var(--line-gold)', borderRadius: 14 }}>
                  <Detail label="Direct line"    value={co('phone',    '+91 95572 84086')} />
                  <Detail label="Concierge email" value={co('email',    'hello@blissfulbites.in')} />
                  <Detail label="Lead time"       value={co('leadTime', 'Same-day · standard · 2 weeks · custom')} />
                  <Detail label="Minimum (bulk)"  value={co('minimum',  '25 boxes · pan-India delivery')} />
                </div>
              );
            })()}
          </div>

          {/* right — form */}
          <form ref={formRef} onSubmit={submit} className="bb-reveal" style={{ background: 'var(--bb-pearl)', padding: '34px', border: '1px solid var(--line-gold)', borderRadius: 22, boxShadow: 'var(--shadow-2)', display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }} className="bb-enq-row">
              <div>
                <label style={labelStyle}>Your name</label>
                <input style={inputStyle} type="text" required value={form.name} onChange={set('name')} onFocus={onFocus} onBlur={onBlur} placeholder="Aanya Mehta" />
              </div>
              <div>
                <label style={labelStyle}>Company / family <span style={{ color: 'var(--fg-3)', letterSpacing: 0 }}>(optional)</span></label>
                <input style={inputStyle} type="text" value={form.company} onChange={set('company')} onFocus={onFocus} onBlur={onBlur} placeholder="Acme Pvt. Ltd." />
              </div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }} className="bb-enq-row">
              <div>
                <label style={labelStyle}>Email</label>
                <input style={inputStyle} type="email" required value={form.email} onChange={set('email')} onFocus={onFocus} onBlur={onBlur} placeholder="you@company.com" />
              </div>
              <div>
                <label style={labelStyle}>Phone</label>
                <input style={inputStyle} type="tel" required value={form.phone} onChange={set('phone')} onFocus={onFocus} onBlur={onBlur} placeholder="+91 …" />
              </div>
            </div>
            <div>
              <label style={labelStyle}>What's the occasion?</label>
              <select style={selectStyle} value={form.topic} onChange={set('topic')} onFocus={onFocus} onBlur={onBlur}>
                {TOPICS.map((t) => <option key={t}>{t}</option>)}
              </select>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14 }} className="bb-enq-row3">
              <div>
                <label style={labelStyle}>Quantity</label>
                <input style={inputStyle} type="text" value={form.qty} onChange={set('qty')} onFocus={onFocus} onBlur={onBlur} placeholder="e.g. 250 boxes" />
              </div>
              <div>
                <label style={labelStyle}>Need-by date</label>
                <input style={inputStyle} type="date" value={form.date} onChange={set('date')} onFocus={onFocus} onBlur={onBlur} />
              </div>
              <div>
                <label style={labelStyle}>Delivery city</label>
                <input style={inputStyle} type="text" value={form.city} onChange={set('city')} onFocus={onFocus} onBlur={onBlur} placeholder="Mumbai" />
              </div>
            </div>
            <div>
              <label style={labelStyle}>Budget per box</label>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {['Under ₹500', '₹500 – ₹1,000', '₹1,000 – ₹2,500', '₹2,500+', 'Flexible'].map((b) => {
                  const active = form.budget === b;
                  return (
                    <button type="button" key={b} onClick={() => setForm((f) => ({ ...f, budget: b }))} style={{
                      fontFamily: 'var(--font-ui)', fontSize: 13, padding: '9px 14px', borderRadius: 999, cursor: 'pointer',
                      border: active ? '1px solid var(--bb-burgundy)' : '1px solid var(--line-strong)',
                      background: active ? 'var(--bb-burgundy)' : 'transparent', color: active ? 'var(--bb-ivory)' : 'var(--bb-cocoa)', transition: 'all 200ms'
                    }}>{b}</button>
                  );
                })}
              </div>
            </div>
            <div>
              <label style={labelStyle}>Tell us more</label>
              <textarea style={{ ...inputStyle, resize: 'vertical', minHeight: 100, lineHeight: 1.5 }} value={form.message} onChange={set('message')} onFocus={onFocus} onBlur={onBlur} placeholder="Palette, monogram, dietary notes, delivery addresses — anything you'd like us to know." />
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, marginTop: 4, flexWrap: 'wrap' }}>
              <p style={{ margin: 0, color: 'var(--fg-3)', fontStyle: 'italic', fontFamily: 'var(--font-serif)', fontSize: 13.5, flex: 1, minWidth: 200 }}>
                We reply within one working day. No newsletters, no resale of your details.
              </p>
              <button type="submit" className="btn btn-primary" style={{ padding: '16px 28px', whiteSpace: 'nowrap' }} disabled={submitting}>
                {sent ? 'Sent ✓' : submitting ? 'Sending…' : 'Send Enquiry →'}
              </button>
            </div>
            {sent && (
              <div style={{ padding: '14px 18px', background: 'rgba(79,107,58,0.10)', border: '1px solid rgba(79,107,58,0.35)', borderRadius: 10, color: '#3F5A2A', fontFamily: 'var(--font-serif)', fontSize: 16 }}>
                Thank you — your note is on its way. We'll write back shortly. <span style={{ fontFamily: 'var(--font-script)', fontSize: 22, color: 'var(--bb-gold-deep)' }}>— with care</span>
              </div>
            )}
            {error && (
              <div style={{ padding: '12px 16px', background: 'rgba(140,46,46,0.08)', border: '1px solid rgba(140,46,46,0.3)', borderRadius: 10, color: '#8C2E2E', fontFamily: 'var(--font-serif)', fontSize: 14 }}>
                {error}
              </div>
            )}
          </form>
        </div>
      </div>
      <style>{`
        @media (max-width: 900px) { .bb-enq-grid { grid-template-columns: 1fr !important; } }
        @media (max-width: 540px) { .bb-enq-row, .bb-enq-row3 { grid-template-columns: 1fr !important; } }
      `}</style>
    </section>
  );
}

function Detail({ label, value }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      <span className="bb-eyebrow" style={{ fontSize: 10, letterSpacing: '0.28em' }}>{label}</span>
      <span style={{ fontFamily: 'var(--font-serif)', fontSize: 18, color: 'var(--bb-burgundy-deep)' }}>{value}</span>
    </div>
  );
}

window.Inquiry = Inquiry;
