// contact.jsx — Contact form + About page

const MONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December'];
const WEEKDAYS = ['Su','Mo','Tu','We','Th','Fr','Sa'];

const DateRangePicker = ({ value, onChange }) => {
  const today = React.useMemo(() => { const d = new Date(); d.setHours(0,0,0,0); return d; }, []);
  const [open, setOpen] = React.useState(false);
  const [hovered, setHovered] = React.useState(null);
  const [view, setView] = React.useState({ year: today.getFullYear(), month: today.getMonth() });
  const ref = React.useRef(null);
  const { start, end } = value;

  React.useEffect(() => {
    if (!open) return;
    const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [open]);

  const getDays = (year, month) => {
    const firstDay = new Date(year, month, 1).getDay();
    const total = new Date(year, month + 1, 0).getDate();
    const cells = [];
    for (let i = 0; i < firstDay; i++) cells.push(null);
    for (let d = 1; d <= total; d++) cells.push(new Date(year, month, d));
    return cells;
  };

  const select = (date) => {
    if (!start || (start && end)) {
      onChange({ start: date, end: null });
    } else {
      if (date.toDateString() === start.toDateString()) {
        onChange({ start: date, end: null });
      } else if (date < start) {
        onChange({ start: date, end: start });
        setOpen(false);
      } else {
        onChange({ start, end: date });
        setOpen(false);
      }
    }
  };

  const fmt = (d) => d.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
  const displayValue = start && end ? `${fmt(start)} – ${fmt(end)}` : start ? fmt(start) : '';

  const rangeEnd = end || hovered;
  const isStart = (d) => d && start && d.toDateString() === start.toDateString();
  const isEnd = (d) => d && end && d.toDateString() === end.toDateString();
  const inRange = (d) => {
    if (!d || !start || !rangeEnd) return false;
    const s = start < rangeEnd ? start : rangeEnd;
    const e = start < rangeEnd ? rangeEnd : start;
    return d > s && d < e;
  };

  const prevMonth = () => setView(v => { const d = new Date(v.year, v.month - 1); return { year: d.getFullYear(), month: d.getMonth() }; });
  const nextMonth = () => setView(v => { const d = new Date(v.year, v.month + 1); return { year: d.getFullYear(), month: d.getMonth() }; });

  const cells = getDays(view.year, view.month);

  return (
    <div ref={ref} className="drp">
      <button
        type="button"
        className={`drp__trigger${open ? ' drp__trigger--open' : ''}`}
        onClick={() => setOpen(o => !o)}
      >
        <span className={displayValue ? 'drp__value' : 'drp__placeholder'}>
          {displayValue || 'Select travel dates'}
        </span>
        <svg className={`drp__chevron${open ? ' drp__chevron--up' : ''}`} width="10" height="6" viewBox="0 0 10 6" fill="none">
          <path d="M1 1L5 5L9 1" stroke="#C6A96B" strokeWidth="1.2"/>
        </svg>
      </button>

      {open && (
        <div className="drp__panel">
          <div className="drp__nav-row">
            <button type="button" className="drp__nav" onClick={prevMonth}>←</button>
            <span className="drp__month-label">{MONTHS[view.month]} {view.year}</span>
            <button type="button" className="drp__nav" onClick={nextMonth}>→</button>
          </div>

          <div className="drp__weekdays">
            {WEEKDAYS.map(w => <span key={w} className="drp__wd">{w}</span>)}
          </div>

          <div className="drp__grid">
            {cells.map((date, i) => {
              if (!date) return <span key={`e${i}`} className="drp__cell" />;
              const past = date < today;
              const sel = isStart(date) || isEnd(date);
              const mid = inRange(date);
              const tod = date.toDateString() === today.toDateString();
              return (
                <button
                  key={date.toDateString()}
                  type="button"
                  disabled={past}
                  className={[
                    'drp__cell drp__cell--day',
                    sel  ? 'drp__cell--sel'   : '',
                    mid  ? 'drp__cell--mid'   : '',
                    tod  ? 'drp__cell--today' : '',
                    past ? 'drp__cell--past'  : '',
                    isStart(date) ? 'drp__cell--sel-start' : '',
                    isEnd(date)   ? 'drp__cell--sel-end'   : '',
                  ].join(' ').trim()}
                  onClick={() => select(date)}
                  onMouseEnter={() => start && !end && setHovered(date)}
                  onMouseLeave={() => setHovered(null)}
                >
                  {date.getDate()}
                </button>
              );
            })}
          </div>

          <div className="drp__footer">
            {start && !end && <span className="drp__hint">Select your return date</span>}
            {start && end && (
              <button type="button" className="drp__clear" onClick={() => { onChange({ start: null, end: null }); setHovered(null); }}>
                Clear dates
              </button>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

const INTERESTS = ['Honeymoon', 'Wildlife', 'Culture', 'Beach', 'Adventure', 'Wellness', 'Family'];
const TIERS = [
  { value: 'five-star',      label: 'Five star & luxury boutiques only' },
  { value: 'four-star-plus', label: '4 star and above' },
  { value: 'four-star',      label: '4 star only' },
];

const ContactPage = () => {
  const [form, setForm] = React.useState({
    name: '', email: '', country: '', travellers: 2,
    dateRange: { start: null, end: null }, tier: '', interests: [], notes: '', agreed: false,
    company: '', turnstileToken: '',
  });
  const [errors, setErrors] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting]   = React.useState(false);
  const [submitError, setSubmitError] = React.useState('');

  const turnstileRef = React.useRef(null);
  const widgetIdRef = React.useRef(null);

  React.useEffect(() => {
    let cancelled = false;
    let interval = null;

    const handleSuccess = (token) => setForm((f) => ({ ...f, turnstileToken: token }));
    const handleExpired = () => setForm((f) => ({ ...f, turnstileToken: '' }));

    // Explicit render: Turnstile's auto-scan only runs once on script load, so SPA-mounted widgets are missed.
    const tryRender = () => {
      if (cancelled || widgetIdRef.current !== null) return true;
      if (!turnstileRef.current || !window.turnstile) return false;
      widgetIdRef.current = window.turnstile.render(turnstileRef.current, {
        sitekey: '0x4AAAAAADXiKWEmkoE8GDh3',
        callback: handleSuccess,
        'expired-callback': handleExpired,
      });
      return true;
    };

    if (!tryRender()) {
      interval = setInterval(() => {
        if (tryRender()) { clearInterval(interval); interval = null; }
      }, 100);
    }

    return () => {
      cancelled = true;
      if (interval) clearInterval(interval);
      if (widgetIdRef.current !== null && window.turnstile) {
        try { window.turnstile.remove(widgetIdRef.current); } catch {}
        widgetIdRef.current = null;
      }
    };
  }, []);

  const set = (k) => (e) => setForm(f => ({
    ...f,
    [k]: e.target
      ? e.target.type === 'checkbox'
        ? e.target.checked
        : e.target.type === 'number'
          ? (e.target.value === '' ? '' : Number(e.target.value))
          : e.target.value
      : e,
  }));
  const toggle = (v) => setForm(f => ({
    ...f,
    interests: f.interests.includes(v) ? f.interests.filter(x => x !== v) : [...f.interests, v]
  }));

  const validate = () => {
    const errs = {};
    if (!form.name.trim()) errs.name = 'Please tell us your name.';
    if (!form.email.trim() || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) errs.email = 'A valid email, please.';
    if (!form.country.trim()) errs.country = 'Where are you travelling from?';
    if (!form.travellers || form.travellers < 1) errs.travellers = 'Please enter the number of travellers.';
    if (!form.tier) errs.tier = 'Please select a tier.';
    if (!form.dateRange.start) errs.dateRange = 'Please select your travel dates.';
    if (!form.agreed) errs.agreed = 'Please agree to continue.';
    setErrors(errs);
    return Object.keys(errs).length === 0;
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!validate()) return;
    if (!form.turnstileToken) {
      setSubmitError('Please complete the security check before submitting.');
      return;
    }
    setSubmitting(true);
    setSubmitError('');
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...form,
          dateRange: {
            start: form.dateRange.start ? form.dateRange.start.toISOString() : null,
            end:   form.dateRange.end   ? form.dateRange.end.toISOString()   : null,
          },
        }),
      });
      if (!res.ok) {
        if (res.status === 429) {
          setSubmitError("You've submitted recently — please try again in a little while, or email us at hello@serendria.com.");
        } else if (res.status === 403) {
          setSubmitError('Please complete the security check and try again.');
          if (window.turnstile && widgetIdRef.current !== null) window.turnstile.reset(widgetIdRef.current);
          setForm((f) => ({ ...f, turnstileToken: '' }));
        } else {
          setSubmitError('Something went wrong — please email us directly at hello@serendria.com.');
        }
        return;
      }
      setSubmitted(true);
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } catch {
      setSubmitError('Something went wrong — please email us directly at hello@serendria.com.');
    } finally {
      setSubmitting(false);
    }
  };

  if (submitted) {
    return (
      <section className="contact wrap">
        <Reveal>
          <div className="contact__success">
            <div className="contact__success-rule"></div>
            <span className="eyebrow">Received · Thank you, {form.name.split(' ')[0]}</span>
            <h1 className="contact__success-title">Your journey is <em>being designed.</em></h1>
            <p className="contact__success-body">A senior designer will write to you personally within two working days. In the meantime, expect a short note from our concierge to confirm a time to speak.</p>
            <div style={{marginTop: 40}}>
              <button className="btn btn--gold btn--lg" onClick={() => window.__nav('home')}>Return Home</button>
            </div>
          </div>
        </Reveal>
      </section>
    );
  }

  return (
    <section className="contact wrap" aria-labelledby="contact-heading">
      <div className="contact__head">
        <div>
          <span className="eyebrow">N° 06 · Begin</span>
          <h1 className="contact__title" id="contact-heading">Design my <em>journey.</em></h1>
        </div>
        <p className="contact__intro">A few details — the more you tell us, the more thoughtful the proposal. There is no fee to enquire and no obligation to travel. A senior designer will reply personally within two working days.</p>
      </div>

      <div className="contact__layout">
        <div>
          <div className="contact__media">
            <img src={IMG.contact} alt="Sri Lanka tea estate" {...dim(IMG.contact)} />
          </div>
          <div className="contact__media-caption">
            <i>N° 27</i>Galle Face · Colombo 03
          </div>
        </div>

        <form className="form" onSubmit={submit} noValidate>
          {/* Honeypot — bots fill all fields; real users never see this. Do not remove. */}
          <input
            type="text"
            name="company"
            tabIndex={-1}
            autoComplete="off"
            value={form.company}
            onChange={set('company')}
            aria-hidden="true"
            style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }}
          />
          <div className="form__section">
            <div className="form__section-label">I · About you</div>
            <div className="form__row">
              <div className="field">
                <label className="field__lbl" htmlFor="contact-name">Full name</label>
                <input
                  id="contact-name"
                  className="field__input"
                  value={form.name}
                  onChange={set('name')}
                  placeholder="Charlotte Williams"
                />
                <div className="field__error">{errors.name || ''}</div>
              </div>
              <div className="field">
                <label className="field__lbl" htmlFor="contact-email">Email</label>
                <input
                  id="contact-email"
                  className="field__input"
                  type="email"
                  value={form.email}
                  onChange={set('email')}
                  placeholder="charlotte@email.com"
                />
                <div className="field__error">{errors.email || ''}</div>
              </div>
            </div>
            <div className="form__row">
              <div className="field">
                <label className="field__lbl" htmlFor="contact-country">Country of residence</label>
                <input
                  id="contact-country"
                  className="field__input"
                  value={form.country}
                  onChange={set('country')}
                  placeholder="United Kingdom"
                />
                <div className="field__error">{errors.country || ''}</div>
              </div>
              <div className="field">
                <label className="field__lbl" htmlFor="contact-travellers">Travellers</label>
                <input
                  id="contact-travellers"
                  className="field__input"
                  type="number"
                  min="1"
                  max="99"
                  value={form.travellers}
                  onChange={set('travellers')}
                />
                <div className="field__error">{errors.travellers || ''}</div>
              </div>
            </div>
          </div>

          <div className="form__section">
            <div className="form__section-label">II · Your journey</div>
            <div className="form__row">
              <div className="field">
                <label className="field__lbl" id="contact-dates-label">Approximate dates</label>
                <DateRangePicker
                  aria-labelledby="contact-dates-label"
                  value={form.dateRange}
                  onChange={(v) => setForm(f => ({ ...f, dateRange: v }))}
                />
                <div className="field__error">{errors.dateRange || ''}</div>
              </div>
              <div className="field">
                <label className="field__lbl" htmlFor="contact-tier">Tier</label>
                <select id="contact-tier" className="field__select" value={form.tier} onChange={set('tier')}>
                  <option value="">Select a tier</option>
                  {TIERS.map(t => <option key={t.value} value={t.value}>{t.label}</option>)}
                </select>
                <div className="field__error">{errors.tier || ''}</div>
              </div>
            </div>

            <div className="field" style={{marginTop: 20}}>
              <label className="field__lbl" id="contact-interests-label">Interests · Select all that apply</label>
              <div className="chip-group" role="group" aria-labelledby="contact-interests-label" style={{marginTop: 6}}>
                {INTERESTS.map(i => (
                  <button
                    type="button"
                    key={i}
                    className={`chip ${form.interests.includes(i) ? 'chip--active' : ''}`}
                    onClick={() => toggle(i)}
                  >
                    {i}
                  </button>
                ))}
              </div>
            </div>

            <div className="field" style={{marginTop: 24}}>
              <label className="field__lbl" htmlFor="contact-notes">Tell us more</label>
              <textarea
                id="contact-notes"
                className="field__textarea"
                value={form.notes}
                onChange={set('notes')}
                placeholder="Anniversary trip, allergies, a particular hotel you've dreamt of…"
                rows="4"
              ></textarea>
              <div className="field__error"></div>
            </div>
          </div>

          <div className="field" style={{marginTop: 24}}>
            <label className="form__agree">
              <input
                type="checkbox"
                checked={form.agreed}
                onChange={set('agreed')}
              />
              <span>
                I agree to the{' '}
                <a
                  className="form__submit-link"
                  href="/terms"
                  onClick={(e) => { e.preventDefault(); window.__nav('terms'); }}
                >Terms of Service</a>
                {' '}and{' '}
                <a
                  className="form__submit-link"
                  href="/privacy"
                  onClick={(e) => { e.preventDefault(); window.__nav('privacy'); }}
                >Privacy Policy</a>.
              </span>
            </label>
            <div className="field__error">{errors.agreed || ''}</div>
          </div>

          <div ref={turnstileRef} style={{ marginTop: 24 }} />

          <div className="form__submit">
            <p className="form__submit-note">We reply to every enquiry, personally, within two working days.</p>
            {submitError && <p className="field__error" style={{marginBottom: 12}}>{submitError}</p>}
            <button className="btn btn--gold btn--lg" type="submit" disabled={submitting}>
              {submitting ? 'Sending…' : <>Design My Journey <span className="btn__arrow">→</span></>}
            </button>
          </div>
        </form>
      </div>
    </section>
  );
};

const AboutPage = () => {
  const heroRef = React.useRef(null);
  const y = useParallax(heroRef);
  const mediaT = `translate3d(0, ${y * 0.38}px, 0) scale(1.06)`;
  const contentT = `translate3d(0, ${y * 0.18}px, 0)`;
  const contentOp = Math.max(0, 1 - y / 600);

  return (
    <>
      <section ref={heroRef} className="tours-hero" style={{height: '60vh', minHeight: 460}}>
        <div className="tours-hero__media" style={{ transform: mediaT, willChange: 'transform' }}>
          <picture>
            <source media="(min-width: 881px)" srcSet="images/samples/image24.webp" />
            <img src="images/samples/image24.webp" alt="Sri Lanka — Colombo skyline" style={{objectPosition: 'bottom'}} {...dim("images/samples/image24.webp")} />
          </picture>
        </div>
        <div className="tours-hero__veil"></div>
        <div className="wrap tours-hero__content" style={{ transform: contentT, opacity: contentOp, willChange: 'transform, opacity' }}>
          <span className="eyebrow" style={{color: '#C6A96B'}}>The Studio</span>
          <h1 className="tours-hero__title">An island, <em>privately.</em></h1>
        </div>
      </section>

    <section className="wrap">
      <Reveal>
        <div className="overview">
          <div className="overview__head">
            <div className="overview__label">I · Our story</div>
            <h2 className="overview__title">A studio in Colombo.</h2>
          </div>
          <div className="overview__body">
            <p>Serendria was founded in 2026 by two friends from Colombo — one from technology, the other from hospitality — who shared the same conviction: that Sri Lanka, for all its press, was still profoundly under-travelled at the top end of the market.</p>
            <p>A year on, we are a small studio working out of a quiet office in Kottawa. The core team is three. Our network of chauffeurs, naturalists, cultural guides and trusted property partners is far larger, built carefully over time with the people who have spent decades doing this well.</p>
            <p>We design private journeys across the full breadth of the island — cultural tours of the ancient capitals, slow weeks in tea country, honeymoons that move between heritage bungalows and tented camps, multi-park safaris, quiet Ayurveda residencies, family weeks on the southern coast. We work in the four- and five-star bracket and the curated boutique addresses we have personally verified.</p>
            <p>Our guests come to us in all manner of ways — by introduction, by reading, by writing in. We answer the phone, ourselves, on the first ring.</p>
          </div>
        </div>
      </Reveal>
    </section>

    <section className="about-strip">
      <div className="about-strip__media"><img src="images/samples/image21.webp" alt="" loading="lazy" {...dim("images/samples/image21.webp")} /></div>
      <Reveal className="about-strip__body">
        <span className="eyebrow">II · Philosophy</span>
        <h2 className="display" style={{fontSize: 'clamp(28px, 3.4vw, 44px)', margin: '18px 0 24px', textWrap: 'balance'}}>
          We believe travel is a <em>quiet act</em> — best practiced slowly, between people who already know each other a little.
        </h2>
        <p className="body-lg" style={{maxWidth: '46ch', color: 'var(--muted)'}}>
          We don't design "Sri Lanka in 7 days." We don't tick lists. We don't ferry strangers between attractions. We build relationships — with you, with our drivers, with the families who run our favourite estates — and we let those relationships do the work that no algorithm can.
        </p>
      </Reveal>
    </section>

    <FinalCTA />
  </>
  );
};

Object.assign(window, { ContactPage, AboutPage });
