/* ============================================================
   CONTACT — WhatsApp-first booking enquiry
   ============================================================ */
const { useState, useEffect, useRef } = React;
function ContactPage({ go }) {
  const trips = DATA.tripOrder.map(k => DATA.trips[k]);
  const [form, setForm] = useState({ trip: 'snorkeling', date: '', adults: '2', children: '0', hotel: '', name: '', phone: '', email: '', message: '' });
  const [submitting, setSubmitting] = useState(false); // false | 'whatsapp' | 'email'
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));
  const t = DATA.trips[form.trip];
  const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

  const buildMsg = () => {
    const lines = [
      window.t('wa.greeting'),
      ``,
      window.t('wa.tripOption', { name: window.tt(t, 'name') }),
      window.t('wa.date', { date: form.date || '' }),
      window.t('wa.hotelPickup', { hotel: form.hotel || '' }),
      window.t('wa.adults', { n: form.adults }),
      window.t('wa.children', { n: form.children }),
      window.t('wa.transferQ'),
      form.name ? window.t('wa.name', { name: form.name }) : null,
      form.phone ? window.t('wa.phone', { phone: form.phone }) : null,
      form.email ? window.t('wa.email', { email: form.email }) : null,
      form.message ? window.t('wa.message', { message: form.message }) : null,
    ].filter(Boolean);
    return lines.join('\n');
  };

  // One payload builder for both actions. source_page + lang are extra context;
  // the API ignores unknown fields, so this is safe.
  const buildPayload = (waMsg) => ({
    trip_key:       form.trip,
    date:           form.date,
    adults:         form.adults,
    children:       form.children,
    hotel:          form.hotel,
    name:           form.name,
    customer_phone: form.phone,
    customer_email: form.email,
    message:        form.message,
    wa_message:     waMsg,
    source_page:    '/book-now',
    lang:           (window.I18N && window.I18N.lang) || 'en',
  });

  // Single handler for both actions. 'whatsapp' saves then opens WhatsApp;
  // 'email' requires a valid email, saves, then shows a success message.
  // DB save is the source of truth; email sending happens server-side and never
  // blocks this flow. Guarded against double-submit via the `submitting` state.
  const submit = async (action) => {
    if (submitting) return;
    setError(''); setSuccess('');
    if (action === 'email' && !EMAIL_RE.test((form.email || '').trim())) {
      setError(window.t('ct.emailRequired'));
      return;
    }
    const waMsg = buildMsg();
    if (typeof window.dhTrack === 'function') {
      window.dhTrack('booking_form_submit', {
        trip_key: form.trip, adults: form.adults, children: form.children,
        preferred_date_present: !!form.date, action,
      });
    }
    setSubmitting(action);
    let savedOk = false;
    try {
      const r = await fetch('/api/enquiries', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(buildPayload(waMsg)),
      });
      savedOk = !!(r && r.ok);
    } catch (err) {
      console.warn('[contact] Enquiry POST failed (non-blocking):', err.message);
    }
    if (action === 'whatsapp') {
      // Always allow the WhatsApp fallback, even if the save failed.
      window.open(DATA.waLink(waMsg), '_blank', 'noopener');
      if (!savedOk) setError(window.t('ct.waFallback'));
    } else {
      if (savedOk) setSuccess(window.t('ct.emailSuccess'));
      else setError(window.t('ct.emailFail'));
    }
    setSubmitting(false);
  };

  const inputStyle = { width: '100%', padding: '13px 15px', borderRadius: 12, border: '1.5px solid var(--line)', background: '#fff', fontFamily: 'var(--body)', fontSize: 15.5, color: 'var(--ink)' };
  const labelStyle = { display: 'block', fontSize: 13, fontWeight: 700, color: 'var(--teal-800)', marginBottom: 7, letterSpacing: '.01em' };

  return (
    <main>
      <PageHero kicker={window.t('ct.heroKicker')} title={window.t('ct.heroTitle')} label="Friendly local crew waving from the boat"
        imgSrc="/Images/Hero/Hurghada%20Dolphin%20House%20%20(6).webp" alt="Book a Dolphin House Hurghada boat trip"
        lead={window.t('ct.heroLead')}/>

      <section className="bg-ivory sec-sm">
        <div className="wrap contact-grid" style={{ display: 'grid', gridTemplateColumns: '1.1fr 0.9fr', gap: 48, alignItems: 'start' }}>
          {/* form */}
          <div className="surface" style={{ padding: 30, boxShadow: 'var(--shadow-md)' }}>
            <h2 className="h-3" style={{ marginBottom: 4 }}>{window.t('ct.formTitle')}</h2>
            <p style={{ color: 'var(--ink-mute)', fontSize: 14.5, marginBottom: 22 }}>{window.t('ct.formSub')}</p>

            <div style={{ marginBottom: 18 }}>
              <span style={labelStyle}>{window.t('ct.whichTrip')}</span>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 9 }} className="trip-select">
                {trips.map(tr => (
                  <button key={tr.key} onClick={() => setForm(f => ({ ...f, trip: tr.key }))}
                    style={{ textAlign: 'left', padding: '12px 13px', borderRadius: 13, border: form.trip === tr.key ? '2px solid var(--turq)' : '1.5px solid var(--line)', background: form.trip === tr.key ? 'rgba(16,182,205,.07)' : '#fff', transition: '.15s' }}>
                    <span style={{ display: 'block', fontFamily: 'var(--display)', fontWeight: 700, fontSize: 14.5, color: 'var(--ink)', lineHeight: 1.15 }}>{window.tt(tr, 'name')}</span>
                    <span style={{ display: 'block', fontSize: 12.5, color: 'var(--turq-deep)', fontWeight: 600, marginTop: 4 }}>{DATA.priceLabel(tr).main} {DATA.priceLabel(tr).note} · {window.tt(tr, 'duration')}</span>
                  </button>
                ))}
              </div>
            </div>

            <div className="form-fields-2col" style={{ display: 'grid', gap: 16, marginBottom: 18 }}>
              <div><span style={labelStyle}>{window.t('ct.preferredDate')}</span><input type="date" style={inputStyle} value={form.date} onChange={set('date')}/></div>
              <div><span style={labelStyle}>{window.t('ct.yourName')}</span><input type="text" placeholder={window.t('ct.namePlaceholder')} style={inputStyle} value={form.name} onChange={set('name')}/></div>
            </div>

            <div className="form-fields-2col" style={{ display: 'grid', gap: 16, marginBottom: 18 }}>
              <div><span style={labelStyle}>{window.t('ct.phoneLabel')} <span style={{ fontWeight: 400, color: 'var(--ink-mute)' }}>{window.t('ct.optional')}</span></span><input type="tel" placeholder={window.t('ct.phonePlaceholder')} style={inputStyle} value={form.phone} onChange={set('phone')}/></div>
              <div><span style={labelStyle}>{window.t('ct.emailLabel')} <span style={{ fontWeight: 400, color: 'var(--ink-mute)' }}>{window.t('ct.optional')}</span></span><input type="email" placeholder={window.t('ct.emailPlaceholder')} style={inputStyle} value={form.email} onChange={set('email')}/></div>
            </div>

            <div className="form-fields-2col" style={{ display: 'grid', gap: 16, marginBottom: 18 }}>
              <div><span style={labelStyle}>{window.t('ct.adults')}</span>
                <select style={inputStyle} value={form.adults} onChange={set('adults')}>{[1,2,3,4,5,6,7,8,9,10,'10+'].map(n => <option key={n}>{n}</option>)}</select>
              </div>
              <div><span style={labelStyle}>{window.t('ct.children')}</span>
                <select style={inputStyle} value={form.children} onChange={set('children')}>{[0,1,2,3,4,5,'5+'].map(n => <option key={n}>{n}</option>)}</select>
              </div>
            </div>

            <div style={{ marginBottom: 18 }}><span style={labelStyle}>{window.t('ct.hotelLabel')}</span><input type="text" placeholder={window.t('ct.hotelPlaceholder')} style={inputStyle} value={form.hotel} onChange={set('hotel')}/></div>
            <div style={{ marginBottom: 22 }}><span style={labelStyle}>{window.t('ct.anythingElse')}</span><textarea rows="3" placeholder={window.t('ct.messagePlaceholder')} style={{ ...inputStyle, resize: 'vertical' }} value={form.message} onChange={set('message')}/></div>

            <p style={{ textAlign: 'center', fontSize: 13, color: 'var(--ink-mute)', margin: '0 0 14px' }}>{window.t('ct.chooseHelper')}</p>

            {error && <div className="form-msg form-msg-err">{error}</div>}
            {success && <div className="form-msg form-msg-ok">{success}</div>}

            <div className="bk-actions">
              <button type="button" className="btn btn-wa bk-btn" disabled={!!submitting}
                aria-label={window.t('ct.sendEnquiry') + ' — ' + window.t('ct.waNote')}
                onClick={() => submit('whatsapp')}>
                <Ic.wa width="18" height="18"/> {submitting === 'whatsapp' ? window.t('ct.saving') : window.t('ct.sendEnquiry')}
              </button>
              <button type="button" className="btn btn-email bk-btn" disabled={!!submitting}
                aria-label={window.t('ct.bookByEmail') + ' — ' + window.t('ct.emailNote')}
                onClick={() => submit('email')}>
                <Ic.mail width="18" height="18"/> {submitting === 'email' ? window.t('ct.saving') : window.t('ct.bookByEmail')}
              </button>
            </div>
            <p style={{ textAlign: 'center', fontSize: 12.5, color: 'var(--ink-mute)', marginTop: 13 }}>{window.t('ct.noPayNote')}</p>
          </div>

          {/* side: direct WA + trust */}
          <div className="contact-side" style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
            <div style={{ background: 'linear-gradient(150deg, var(--teal-700), var(--teal-950))', color: '#fff', borderRadius: 'var(--r-md)', padding: 28 }}>
              <span style={{ width: 52, height: 52, borderRadius: 14, background: 'var(--wa)', color: '#06351a', display: 'grid', placeItems: 'center', marginBottom: 16 }}><Ic.wa width="28" height="28"/></span>
              <h3 style={{ color: '#fff', fontSize: 23, marginBottom: 8 }}>{window.t('ct.preferMessage')}</h3>
              <p style={{ color: 'rgba(234,246,247,.85)', fontSize: 15, marginBottom: 18 }}>{window.t('ct.tapTrip')}</p>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {trips.map(tr => (
                  <a key={tr.key} href={DATA.waLink(window.t('wa.bookTripDate', { name: window.tt(tr, 'name'), price: DATA.priceLabel(tr).main, note: DATA.priceLabel(tr).note }))} target="_blank" rel="noopener"
                    style={{ display: 'flex', alignItems: 'center', gap: 12, background: 'rgba(255,255,255,.08)', border: '1px solid rgba(255,255,255,.16)', borderRadius: 13, padding: '13px 15px', transition: '.15s' }}
                    onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,.14)'} onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,.08)'}>
                    <span style={{ flex: 1 }}><span style={{ display: 'block', fontFamily: 'var(--display)', fontWeight: 700, fontSize: 15.5, color: '#fff' }}>{window.tt(tr, 'name')}</span><span style={{ fontSize: 13, color: 'rgba(234,246,247,.7)' }}>{DATA.priceLabel(tr).main} {DATA.priceLabel(tr).note}</span></span>
                    <Ic.wa width="22" height="22" style={{ color: 'var(--wa)' }}/>
                  </a>
                ))}
              </div>
            </div>

            <div className="surface" style={{ padding: 24 }}>
              <h3 style={{ fontSize: 18, marginBottom: 14 }}>{window.t('ct.whatExpect')}</h3>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
                {[['chat', window.t('ct.fastReply.t'), window.t('ct.fastReply.d')],
                  ['check', window.t('ct.noPay.t'), window.t('ct.noPay.d')],
                  ['van', window.t('ct.pickup.t'), window.t('ct.pickup.d')],
                  ['shield', window.t('ct.honest.t'), window.t('ct.honest.d')]].map(([ic, t2, d], i) => (
                  <div key={i} style={{ display: 'flex', gap: 13 }}>
                    <span style={{ width: 38, height: 38, borderRadius: 10, flex: 'none', background: 'var(--ivory-2)', color: 'var(--turq-deep)', display: 'grid', placeItems: 'center' }}>{React.createElement(Ic[ic], { width: 19, height: 19 })}</span>
                    <span><b style={{ fontFamily: 'var(--display)', fontSize: 15 }}>{t2}</b><br/><span style={{ fontSize: 13.5, color: 'var(--ink-soft)' }}>{d}</span></span>
                  </div>
                ))}
              </div>
            </div>

            <div className="surface" style={{ padding: 22, display: 'flex', flexDirection: 'column', gap: 11 }}>
              <span style={{ display: 'flex', gap: 10, alignItems: 'center', fontSize: 14.5, color: 'var(--ink-soft)' }}><Ic.wa width="18" height="18" style={{ color: 'var(--wa-dark)' }}/> +20 100 084 3745</span>
              <span style={{ display: 'flex', gap: 10, alignItems: 'center', fontSize: 14.5, color: 'var(--ink-soft)' }}><Ic.pin width="18" height="18" style={{ color: 'var(--turq-deep)' }}/> Marina, Hurghada, Egypt</span>
              <span style={{ display: 'flex', gap: 10, alignItems: 'center', fontSize: 14.5, color: 'var(--ink-soft)' }}><Ic.clock width="18" height="18" style={{ color: 'var(--turq-deep)' }}/> Daily · 8:00–20:00</span>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { ContactPage });
