const VEHICLES = ['Small / hatchback', 'Saloon / estate', 'SUV / 4x4', 'Van / large', 'Other'];
const fieldStyle = {
  width: '100%', background: '#0c0c0c', border: '1px solid #2a2a2a', color: '#fff',
  padding: '14px 16px', fontFamily: 'var(--font-body)', fontSize: 15, borderRadius: 0, outline: 'none',
  transition: 'border-color .2s ease',
};
const labelStyle = { display: 'block', fontFamily: 'var(--font-display)', fontSize: 11, letterSpacing: 1.4, textTransform: 'uppercase', color: 'var(--ash)', marginBottom: 9 };

function Field({ label, children, span }) {
  return <div style={{ gridColumn: span ? '1 / -1' : 'auto' }}><label style={labelStyle}>{label}</label>{children}</div>;
}
function FInput(props) {
  const [f, setF] = React.useState(false);
  return <input {...props} onFocus={() => setF(true)} onBlur={() => setF(false)} style={{ ...fieldStyle, borderColor: f ? 'var(--lambo-gold)' : '#2a2a2a' }} />;
}

function BookingForm() {
  const [data, setData] = React.useState({ name: '', email: '', phone: '', service: 'Silver — Full Valet', vehicle: VEHICLES[1], make: '', date: '', postcode: '', notes: '' });
  const [selectedAddons, setSelectedAddons] = React.useState(['none']);
  const [errors, setErrors] = React.useState({});
  const [sent, setSent] = React.useState(false);
  const set = (k) => (e) => setData(d => ({ ...d, [k]: e.target.value }));

  const BOOKING_ADDONS = [
    { id: 'none', label: 'No Add-Ons Required', price: '' },
    ...ADDONS.map((a, i) => ({ id: 'addon-' + i, label: a.name, price: a.price })),
    { id: 'addon-fabric-shampoo', label: 'Fabric seat shampoo & extraction', price: 'POA' },
    { id: 'addon-pet-hair', label: 'Pet hair removal', price: '£20 – £80' },
    { id: 'addon-heavy-stain', label: 'Heavy stain removal', price: 'POA' },
    { id: 'addon-child-seat-deep', label: 'Child seat deep clean', price: '£30' },
  ];

  const toggleAddon = (id) => {
    if (id === 'none') {
      setSelectedAddons(['none']);
    } else {
      setSelectedAddons(prev => {
        const without = prev.filter(x => x !== 'none');
        if (without.includes(id)) {
          const next = without.filter(x => x !== id);
          return next.length === 0 ? ['none'] : next;
        }
        return [...without, id];
      });
    }
  };

  const validate = () => {
    const er = {};
    if (!data.name.trim()) er.name = 'Please enter your name';
    if (!/^[^@]+@[^@]+\.[^@]+$/.test(data.email)) er.email = 'Enter a valid email';
    if (data.phone.replace(/\D/g, '').length < 7) er.phone = 'Enter a valid phone number';
    if (!data.postcode.trim()) er.postcode = 'We need your area / postcode';
    if (selectedAddons.length === 0) er.addons = 'Please select at least one option';
    setErrors(er); return Object.keys(er).length === 0;
  };

  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState('');

  /* Show the success screen when FormSubmit returns the customer here. */
  React.useEffect(() => {
    try {
      if (new URLSearchParams(window.location.search).get('sent') === '1') setSent(true);
    } catch (err) { /* ignore */ }
  }, []);

  /* Native browser submission — see the note on the contact form. */
  const submit = (e) => {
    if (!validate()) { e.preventDefault(); return; }
    if (!FORM_KEY) {
      e.preventDefault();
      setError('The form is not configured yet — please contact us on WhatsApp or by phone.');
      return;
    }
    setSending(true);
    // no preventDefault — the browser posts the form from here
  };

  const waBook = () => {
    const msg = `Hi MVH, I'd like to book a detail.%0AName: ${data.name}%0AService: ${data.service}%0AVehicle: ${data.vehicle} ${data.make}%0APreferred date: ${data.date}%0AArea: ${data.postcode}`;
    return `https://wa.me/${MVH.wa}?text=${msg}`;
  };

  if (sent) {
    return (
      <div className="card" style={{ padding: '48px 40px', textAlign: 'center' }}>
        <div style={{ width: 72, height: 72, borderRadius: '50%', background: 'var(--gold-metal)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 24px' }}>
          <Icon name="check" size={36} color="#161616" stroke={2.4} />
        </div>
        <h2 className="display h-2" style={{ textTransform: 'uppercase' }}>Request received</h2>
        <p className="lede" style={{ margin: '14px auto 0' }}>Thank you, {data.name.split(' ')[0] || 'there'}. Your booking request has been sent directly to us. We'll confirm availability and your exact price by phone or WhatsApp shortly.</p>
        <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginTop: 30, flexWrap: 'wrap' }}>
          <Button href="/" variant="gold">Back to home</Button>
          <Button href={waBook()} target="_blank" variant="ghost" icon="whatsapp">Also message on WhatsApp</Button>
        </div>
      </div>
    );
  }

  return (
    <form
      className="card"
      style={{ padding: 'clamp(24px, 4vw, 40px)' }}
      action="https://api.web3forms.com/submit"
      method="POST"
      onSubmit={submit}
      noValidate
    >
      <input type="hidden" name="Name" value={data.name} readOnly />
      <input type="hidden" name="Phone" value={data.phone} readOnly />
      <input type="hidden" name="Email" value={data.email} readOnly />
      <input type="hidden" name="Service" value={data.service} readOnly />
      <input type="hidden" name="Vehicle" value={`${data.vehicle} — ${data.make || 'not specified'}`} readOnly />
      <input type="hidden" name="Preferred Date" value={data.date || 'Flexible'} readOnly />
      <input type="hidden" name="Add-Ons" value={selectedAddons.includes('none') ? 'None' : selectedAddons.map(id => { const a = BOOKING_ADDONS.find(x => x.id === id); return a ? a.label : id; }).join(', ')} readOnly />
      <input type="hidden" name="Postcode / Area" value={data.postcode} readOnly />
      <input type="hidden" name="Notes" value={data.notes || '—'} readOnly />
      <input type="hidden" name="subject" value={`Booking request — ${data.name || 'MVH website'}`} readOnly />
      <input type="hidden" name="access_key" value={FORM_KEY} readOnly />
      <input type="hidden" name="from_name" value="MVH Mobile Detailing Website" readOnly />
      
      <input type="hidden" name="redirect" value={typeof window !== 'undefined' ? `${window.location.origin}${window.location.pathname}?sent=1` : ''} readOnly />
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 22 }}>
        <Field label="Full name"><FInput value={data.name} onChange={set('name')} placeholder="Jane Smith" />{errors.name && <Err msg={errors.name} />}</Field>
        <Field label="Phone"><FInput value={data.phone} onChange={set('phone')} placeholder="07…" />{errors.phone && <Err msg={errors.phone} />}</Field>
        <Field label="Email" span><FInput type="email" value={data.email} onChange={set('email')} placeholder="you@email.com" />{errors.email && <Err msg={errors.email} />}</Field>
        <Field label="Service">
          <div style={{ position: 'relative' }}>
            <select value={data.service} onChange={set('service')} style={{ ...fieldStyle, appearance: 'none', cursor: 'pointer' }}>
              <option>Bronze — Maintenance Detail</option>
              <option>Silver — Full Valet</option>
              <option>Gold — Enhancement Detail</option>
              <option>Platinum — Showroom Detail</option>
              <option>Diamond — Ultimate Detail</option>
              <option>Interior Reset Detail</option>
              <option>Ceramic Coating</option>
              <option>Not sure — advise me</option>
            </select>
            <Caret />
          </div>
        </Field>
        <Field label="Vehicle type">
          <div style={{ position: 'relative' }}>
            <select value={data.vehicle} onChange={set('vehicle')} style={{ ...fieldStyle, appearance: 'none', cursor: 'pointer' }}>
              {VEHICLES.map(v => <option key={v}>{v}</option>)}
            </select>
            <Caret />
          </div>
        </Field>
        <Field label="Make & model (optional)"><FInput value={data.make} onChange={set('make')} placeholder="e.g. BMW 3 Series" /></Field>
        <Field label="Preferred date"><FInput type="date" value={data.date} onChange={set('date')} /></Field>
        <Field label="Postcode / area" span><FInput value={data.postcode} onChange={set('postcode')} placeholder="e.g. WS11, Cannock" />{errors.postcode && <Err msg={errors.postcode} />}</Field>

        {/* Add-On Services */}
        <div style={{ gridColumn: '1 / -1' }}>
          <label style={labelStyle}>Add-On Services</label>
          <p style={{ color: 'var(--smoke)', fontSize: 13.5, lineHeight: 1.55, margin: '0 0 14px', fontWeight: 300 }}>
            Please select any additional services you would like to add to your booking. Multiple add-ons can be selected. If no additional services are required, select 'No Add-Ons Required'.
          </p>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
            <div style={{ padding: '4px 10px', border: '1px solid rgba(212,175,55,0.35)', background: 'rgba(212,175,55,0.06)' }}>
              <span style={{ fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: 1.6, textTransform: 'uppercase', color: 'var(--lambo-gold-text)', fontWeight: 600 }}>Multiple selections allowed</span>
            </div>
          </div>
          <div style={{ border: '1px solid #2a2a2a', background: '#0c0c0c', maxHeight: 280, overflowY: 'auto' }}>
            {BOOKING_ADDONS.map((addon) => {
              const isSelected = selectedAddons.includes(addon.id);
              const isNone = addon.id === 'none';
              return (
                <button
                  key={addon.id}
                  type="button"
                  onClick={() => toggleAddon(addon.id)}
                  style={{
                    display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 14, width: '100%',
                    padding: '13px 16px', background: isSelected ? 'rgba(212,175,55,0.08)' : 'transparent',
                    border: 'none', borderBottom: '1px solid #1a1a1a', cursor: 'pointer', textAlign: 'left',
                    transition: 'background .15s ease',
                  }}
                >
                  <span style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                    <span style={{
                      width: 20, height: 20, flexShrink: 0, border: isSelected ? '1px solid var(--lambo-gold)' : '1px solid #3a3a3a',
                      background: isSelected ? 'var(--lambo-gold)' : 'transparent',
                      display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'all .15s ease',
                    }}>
                      {isSelected && <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#0a0a0a" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg>}
                    </span>
                    <span style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: isSelected ? '#fff' : 'var(--smoke)', fontWeight: isNone ? 500 : 300 }}>{addon.label}</span>
                  </span>
                  {addon.price && <span style={{ fontFamily: 'var(--font-display)', fontSize: 13, color: 'var(--lambo-gold-text)', whiteSpace: 'nowrap', fontWeight: 500 }}>{addon.price}</span>}
                </button>
              );
            })}
          </div>
          {errors.addons && <Err msg={errors.addons} />}
        </div>

        <Field label="Anything else? (optional)" span>
          <textarea value={data.notes} onChange={set('notes')} rows={4} placeholder="Condition, specific concerns, add-ons you'd like…" style={{ ...fieldStyle, resize: 'vertical' }}></textarea>
        </Field>
      </div>
      <div style={{ display: 'flex', gap: 14, marginTop: 26, flexWrap: 'wrap' }}>
        <Button variant="gold" size="lg" icon="arrowUpRight">{sending ? 'Sending…' : 'Request Booking'}</Button>
        {error && <div style={{ color: '#e06a5a', fontSize: 13, marginTop: 8, display: 'flex', alignItems: 'center', gap: 8 }}><Icon name="close" size={16} />{error}</div>}
        <Button href={waBook()} target="_blank" variant="ghost" size="lg" icon="whatsapp">Book via WhatsApp</Button>
      </div>
      <p style={{ color: 'var(--ash)', fontSize: 12.5, marginTop: 18 }}>No payment taken now — we'll confirm availability and your exact price first.</p>
    </form>
  );
}
function Err({ msg }) { return <div style={{ color: '#e06a5a', fontSize: 12.5, marginTop: 7 }}>{msg}</div>; }
function Caret() { return <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--lambo-gold)" strokeWidth="2" style={{ position: 'absolute', right: 16, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }}><polyline points="6 9 12 15 18 9"/></svg>; }

function Aside() {
  const steps = [
    ['Tell us what you need', 'Pick a package and date, or ask us to recommend one.'],
    ['We confirm & quote', "We'll reply by phone or WhatsApp with availability and your exact price."],
    ['We come to you', 'We arrive fully equipped and transform your vehicle on your driveway.'],
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 26 }}>
      <div className="card" style={{ padding: '28px 26px' }}>
        <Eyebrow>What Happens Next</Eyebrow>
        <div style={{ marginTop: 22 }}>
          {steps.map((s, i) => (
            <div key={i} style={{ display: 'flex', gap: 16, paddingBottom: i === steps.length - 1 ? 0 : 22 }}>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                <div style={{ width: 34, height: 34, flexShrink: 0, borderRadius: '50%', border: '1px solid var(--lambo-gold)', color: 'var(--lambo-gold-text)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14 }}>{i + 1}</div>
                {i !== steps.length - 1 && <div style={{ width: 1, flex: 1, background: '#262626', marginTop: 4 }}></div>}
              </div>
              <div>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 16, letterSpacing: 0.3 }}>{s[0]}</div>
                <p style={{ color: 'var(--ash)', fontSize: 13.5, lineHeight: 1.55, marginTop: 5, fontWeight: 300 }}>{s[1]}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
      <div className="card" style={{ padding: '26px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}><Stars size={16} /><span style={{ fontFamily: 'var(--font-display)', fontWeight: 600 }}>4.9</span><span className="muted" style={{ fontSize: 12.5 }}>· {REVIEW_STATS.count} reviews</span></div>
      </div>
      <a className="card" href={`tel:${MVH.tel}`} style={{ padding: '22px 26px', display: 'flex', alignItems: 'center', gap: 16 }}>
        <Icon name="phone" size={26} color="var(--lambo-gold)" />
        <div>
          <div style={{ fontSize: 12, color: 'var(--ash)', textTransform: 'uppercase', letterSpacing: 1 }}>Prefer to call?</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 600, color: 'var(--lambo-gold-text)' }}>{MVH.phoneDisplay}</div>
        </div>
      </a>
    </div>
  );
}

function App() {
  return (
    <div>
      <Nav active="Book" />
      <section style={{ paddingTop: 130, paddingBottom: 30 }} data-screen-label="Booking Hero">
        <div className="shell">
          <Eyebrow>Online Booking</Eyebrow>
          <h1 className="display h-hero" style={{ marginTop: 16 }}>Book your detail</h1>
          <p className="lede" style={{ marginTop: 16 }}>Tell us what your vehicle needs and when. We'll confirm availability and your exact price — no deposit required.</p>
        </div>
      </section>
      <section style={{ paddingBottom: 96 }} data-screen-label="Booking Form">
        <div className="shell">
          <div className="grid" style={{ gridTemplateColumns: '1.7fr 1fr', gap: 36, alignItems: 'start' }} id="book-grid">
            <BookingForm />
            <Aside />
          </div>
        </div>
      </section>
      <Footer />
      <StickyActions />
      <style>{`@media (max-width: 900px){ #book-grid{grid-template-columns:1fr!important} } @media (max-width: 560px){ #book-grid form > div{grid-template-columns:1fr!important} }`}</style>
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
