/* ============================================================
   Villa 44 Badulla — Luxury Reservation Component
   React 18 + Babel in-browser | No build tools required
   ============================================================ */

const { useState, useEffect, useMemo, useCallback, useRef } = React;

/* ── Constants ─────────────────────────────────────────────── */
const WHATSAPP_NUMBER = '94762128396';

const ACCOMMODATIONS = [
  { id: 'whole-villa', label: 'Whole Villa Buyout', sublabel: 'All 3 Rooms — up to 10 guests', rateGBP: 182, rateUSD: 230 },
  { id: 'room-443',    label: 'Room 443 — Family Room', sublabel: 'Private balcony & en-suite bath', rateGBP: 75, rateUSD: 95 },
  { id: 'room-441',    label: 'Room 441 — Double Room', sublabel: 'Attached private bathroom', rateGBP: 59, rateUSD: 75 },
  { id: 'room-442',    label: 'Room 442 — Double Room', sublabel: 'Dedicated private bathroom', rateGBP: 51, rateUSD: 65 },
];

const GUEST_OPTIONS = [
  { value: '1',  label: '1 Guest' },
  { value: '2',  label: '2 Guests' },
  { value: '3',  label: '3 Guests' },
  { value: '4+', label: '4+ Guests / Private Buyout' },
];

const MIN_NIGHTS = 2;
const MAX_NIGHTS = 14;

/* ── Helpers ────────────────────────────────────────────────── */
function toDateObj(str) {
  if (!str) return null;
  const [y, m, d] = str.split('-').map(Number);
  return new Date(y, m - 1, d);
}

function diffNights(checkin, checkout) {
  const a = toDateObj(checkin);
  const b = toDateObj(checkout);
  if (!a || !b) return 0;
  return Math.round((b - a) / 86400000);
}

function fmtDate(str) {
  if (!str) return '—';
  const d = toDateObj(str);
  return d.toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'long', year: 'numeric' });
}

function todayStr() {
  const d = new Date();
  return d.toISOString().split('T')[0];
}

function addDays(str, n) {
  const d = toDateObj(str);
  d.setDate(d.getDate() + n);
  return d.toISOString().split('T')[0];
}

/* ── Icons ──────────────────────────────────────────────────── */
const WhatsAppIcon = () => (
  <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
    <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>
  </svg>
);

const CalendarIcon = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden="true">
    <rect x="3" y="4" width="18" height="18" rx="3"/>
    <path d="M16 2v4M8 2v4M3 10h18"/>
  </svg>
);

const UserIcon = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden="true">
    <circle cx="12" cy="8" r="4"/>
    <path d="M4 20c0-4 3.582-7 8-7s8 3 8 7"/>
  </svg>
);

const ChevronRight = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" aria-hidden="true">
    <path d="M9 18l6-6-6-6"/>
  </svg>
);

const ChevronLeft = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" aria-hidden="true">
    <path d="M15 18l-6-6 6-6"/>
  </svg>
);

const CheckIcon = () => (
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" aria-hidden="true">
    <polyline points="20 6 9 17 4 12"/>
  </svg>
);

/* ── Step Indicator ─────────────────────────────────────────── */
function StepIndicator({ currentStep }) {
  const steps = [
    { num: 1, label: 'Dates' },
    { num: 2, label: 'Guests' },
    { num: 3, label: 'Summary' },
  ];

  return (
    <div className="rvc-steps" role="list" aria-label="Booking steps">
      {steps.map((s, i) => (
        <React.Fragment key={s.num}>
          <div
            className={"rvc-step" + (currentStep === s.num ? " rvc-step--active" : "") + (currentStep > s.num ? " rvc-step--done" : "")}
            role="listitem"
            aria-current={currentStep === s.num ? "step" : undefined}
          >
            <div className="rvc-step__bubble">
              {currentStep > s.num ? <CheckIcon /> : s.num}
            </div>
            <span className="rvc-step__label">{s.label}</span>
          </div>
          {i < steps.length - 1 && (
            <div className={"rvc-step__line" + (currentStep > s.num ? " rvc-step__line--done" : "")} aria-hidden="true" />
          )}
        </React.Fragment>
      ))}
    </div>
  );
}

/* ── Step 1 — Dates ─────────────────────────────────────────── */
function StepDates({ checkin, checkout, onCheckinChange, onCheckoutChange, onNext, error }) {
  const today = todayStr();
  const minCheckout = checkin ? addDays(checkin, MIN_NIGHTS) : today;
  const maxCheckout = checkin ? addDays(checkin, MAX_NIGHTS) : '';
  const nights = useMemo(() => diffNights(checkin, checkout), [checkin, checkout]);

  return (
    <div className="rvc-panel rvc-panel--dates">
      <div className="rvc-panel__head">
        <h3 className="rvc-panel__title">
          <CalendarIcon />
          Select Your Dates
        </h3>
        <p className="rvc-panel__hint">Minimum stay: {MIN_NIGHTS} nights &middot; Maximum: {MAX_NIGHTS} nights</p>
      </div>

      <div className="rvc-fields">
        <div className="rvc-field">
          <label className="rvc-label" htmlFor="rvc-checkin">Check-In</label>
          <input
            id="rvc-checkin"
            type="date"
            className="rvc-input"
            value={checkin}
            min={today}
            onChange={e => onCheckinChange(e.target.value)}
          />
        </div>
        <div className="rvc-field">
          <label className="rvc-label" htmlFor="rvc-checkout">Check-Out</label>
          <input
            id="rvc-checkout"
            type="date"
            className="rvc-input"
            value={checkout}
            min={minCheckout}
            max={maxCheckout || undefined}
            onChange={e => onCheckoutChange(e.target.value)}
            disabled={!checkin}
          />
        </div>
      </div>

      {nights > 0 && (
        <div className="rvc-nights-pill" aria-live="polite">
          <span className="rvc-nights-pill__num">{nights}</span>
          <span className="rvc-nights-pill__text">{nights === 1 ? 'night' : 'nights'} selected</span>
        </div>
      )}

      {error && <p className="rvc-error" role="alert">{error}</p>}

      <button className="rvc-btn rvc-btn--primary" onClick={onNext} id="rvc-dates-next">
        Continue
        <ChevronRight />
      </button>
    </div>
  );
}

/* ── Step 2 — Guests ────────────────────────────────────────── */
function StepGuests({ accommodation, guests, onAccommChange, onGuestsChange, onBack, onNext }) {
  const acc = ACCOMMODATIONS.find(a => a.id === accommodation);

  return (
    <div className="rvc-panel rvc-panel--guests">
      <div className="rvc-panel__head">
        <h3 className="rvc-panel__title">
          <UserIcon />
          Guests &amp; Accommodation
        </h3>
      </div>

      <div className="rvc-fields">
        <div className="rvc-field rvc-field--full">
          <label className="rvc-label" htmlFor="rvc-room">Accommodation</label>
          <div className="rvc-select-wrap">
            <select
              id="rvc-room"
              className="rvc-select"
              value={accommodation}
              onChange={e => onAccommChange(e.target.value)}
            >
              {ACCOMMODATIONS.map(a => (
                <option key={a.id} value={a.id}>
                  {a.label} — £{a.rateGBP}/night
                </option>
              ))}
            </select>
          </div>
          {acc && <p className="rvc-field__hint">{acc.sublabel}</p>}
        </div>

        <div className="rvc-field rvc-field--full">
          <label className="rvc-label" htmlFor="rvc-guests">Number of Guests</label>
          <div className="rvc-select-wrap">
            <select
              id="rvc-guests"
              className="rvc-select"
              value={guests}
              onChange={e => onGuestsChange(e.target.value)}
            >
              {GUEST_OPTIONS.map(g => (
                <option key={g.value} value={g.value}>{g.label}</option>
              ))}
            </select>
          </div>
        </div>
      </div>

      <div className="rvc-nav">
        <button className="rvc-btn rvc-btn--ghost" onClick={onBack} id="rvc-guests-back">
          <ChevronLeft />
          Back
        </button>
        <button className="rvc-btn rvc-btn--primary" onClick={onNext} id="rvc-guests-next">
          Continue
          <ChevronRight />
        </button>
      </div>
    </div>
  );
}

/* ── Step 3 — Summary ───────────────────────────────────────── */
function StepSummary({ checkin, checkout, accommodation, guests, onBack, onWhatsApp }) {
  const acc = ACCOMMODATIONS.find(a => a.id === accommodation) || ACCOMMODATIONS[0];
  const nights = useMemo(() => diffNights(checkin, checkout), [checkin, checkout]);
  const totalGBP = useMemo(() => acc.rateGBP * nights, [acc, nights]);

  const guestLabel = guests === '4+' ? '4+ Guests / Private Buyout' : (guests + ' Guest' + (guests === '1' ? '' : 's'));

  const rows = [
    { label: 'Accommodation', value: acc.label },
    { label: 'Check-In',      value: fmtDate(checkin) },
    { label: 'Check-Out',     value: fmtDate(checkout) },
    { label: 'Duration',      value: nights + (nights === 1 ? ' night' : ' nights') },
    { label: 'Guests',        value: guestLabel },
    { label: 'Rate per night',value: '£' + acc.rateGBP },
  ];

  return (
    <div className="rvc-panel rvc-panel--summary">
      <div className="rvc-panel__head">
        <h3 className="rvc-panel__title">Booking Summary</h3>
      </div>

      <div className="rvc-summary">
        {rows.map(r => (
          <div key={r.label} className="rvc-summary__row">
            <span className="rvc-summary__label">{r.label}</span>
            <span className="rvc-summary__value">{r.value}</span>
          </div>
        ))}
        <div className="rvc-summary__row rvc-summary__row--total">
          <span className="rvc-summary__label">Estimated Total</span>
          <span className="rvc-summary__value rvc-summary__value--total">{'£' + totalGBP.toLocaleString()}</span>
        </div>
      </div>

      <p className="rvc-summary__note">
        Includes Shared Garden, Dining Lounge, high-speed WiFi, air conditioning, hot water, and all in-room amenities. Final price confirmed on enquiry.
      </p>

      <div className="rvc-nav">
        <button className="rvc-btn rvc-btn--ghost" onClick={onBack} id="rvc-summary-back">
          <ChevronLeft />
          Back
        </button>
        <button className="rvc-btn rvc-btn--whatsapp" onClick={onWhatsApp} id="rvc-whatsapp-submit">
          <WhatsAppIcon />
          Book via WhatsApp
        </button>
      </div>
    </div>
  );
}

/* ── Main Component ─────────────────────────────────────────── */
function ReservationCard() {
  const [step, setStep]            = useState(1);
  const [checkin, setCheckin]      = useState('');
  const [checkout, setCheckout]    = useState('');
  const [accommodation, setAccomm] = useState('whole-villa');
  const [guests, setGuests]        = useState('2');
  const [dateError, setDateError]  = useState('');
  const cardRef                    = useRef(null);
  const [visible, setVisible]      = useState(false);

  /* Scroll reveal */
  useEffect(() => {
    const el = cardRef.current;
    if (!el) return;
    const obs = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) { setVisible(true); obs.disconnect(); } },
      { threshold: 0.12 }
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, []);

  /* Listen for room selection from accommodations section */
  useEffect(() => {
    const handleRoomSelected = (e) => {
      if (e.detail && e.detail.roomId) {
        setAccomm(e.detail.roomId);
      }
    };
    window.addEventListener('villaRoomSelected', handleRoomSelected);
    return () => window.removeEventListener('villaRoomSelected', handleRoomSelected);
  }, []);

  const handleCheckinChange = useCallback((val) => {
    setCheckin(val);
    setDateError('');
    if (checkout && val) {
      const n = diffNights(val, checkout);
      if (n < MIN_NIGHTS || n > MAX_NIGHTS) setCheckout('');
    }
  }, [checkout]);

  const handleCheckoutChange = useCallback((val) => {
    setCheckout(val);
    setDateError('');
  }, []);

  const handleDatesNext = useCallback(() => {
    if (!checkin || !checkout) {
      setDateError('Please select both check-in and check-out dates.');
      return;
    }
    const n = diffNights(checkin, checkout);
    if (n < MIN_NIGHTS) { setDateError('Minimum stay is ' + MIN_NIGHTS + ' nights.'); return; }
    if (n > MAX_NIGHTS) { setDateError('Maximum stay is ' + MAX_NIGHTS + ' nights.'); return; }
    setDateError('');
    setStep(2);
  }, [checkin, checkout]);

  const handleWhatsApp = useCallback(() => {
    const acc    = ACCOMMODATIONS.find(a => a.id === accommodation) || ACCOMMODATIONS[0];
    const nights = diffNights(checkin, checkout);
    const total  = acc.rateGBP * nights;
    const guestLabel = guests === '4+' ? '4+ Guests / Private Buyout' : (guests + ' Guest' + (guests === '1' ? '' : 's'));

    const msg = [
      '\uD83C\uDFE1 *Villa 44 Badulla \u2014 Booking Enquiry*',
      '',
      '\uD83D\uDCC5 *Check-In:* ' + fmtDate(checkin),
      '\uD83D\uDCC5 *Check-Out:* ' + fmtDate(checkout),
      '\uD83C\uDF19 *Duration:* ' + nights + (nights === 1 ? ' night' : ' nights'),
      '\uD83D\uDECF\uFE0F *Accommodation:* ' + acc.label,
      '\uD83D\uDC65 *Guests:* ' + guestLabel,
      '\uD83D\uDCB7 *Rate per night:* \u00A3' + acc.rateGBP,
      '\uD83D\uDCB0 *Estimated Total:* \u00A3' + total.toLocaleString(),
      '',
      'I would like to confirm availability and receive a bespoke proposal. Thank you!',
    ].join('\n');

    const url = 'https://wa.me/' + WHATSAPP_NUMBER + '?text=' + encodeURIComponent(msg);
    window.open(url, '_blank', 'noopener,noreferrer');
  }, [checkin, checkout, accommodation, guests]);

  const cardClass = 'rvc-card' + (visible ? ' rvc-card--visible' : '');

  return (
    <div ref={cardRef} className={cardClass} role="form" aria-label="Villa reservation form">
      <div className="rvc-card__topbar" aria-hidden="true">
        <span className="rvc-card__topbar-line" />
        <span className="rvc-card__topbar-diamond">&loz;</span>
        <span className="rvc-card__topbar-line" />
      </div>

      <StepIndicator currentStep={step} />

      <div className="rvc-card__body">
        {step === 1 && (
          <StepDates
            checkin={checkin}
            checkout={checkout}
            onCheckinChange={handleCheckinChange}
            onCheckoutChange={handleCheckoutChange}
            onNext={handleDatesNext}
            error={dateError}
          />
        )}
        {step === 2 && (
          <StepGuests
            accommodation={accommodation}
            guests={guests}
            onAccommChange={setAccomm}
            onGuestsChange={setGuests}
            onBack={() => setStep(1)}
            onNext={() => setStep(3)}
          />
        )}
        {step === 3 && (
          <StepSummary
            checkin={checkin}
            checkout={checkout}
            accommodation={accommodation}
            guests={guests}
            onBack={() => setStep(2)}
            onWhatsApp={handleWhatsApp}
          />
        )}
      </div>

      <div className="rvc-card__footer">
        <span className="rvc-trust">&nbsp;Secure &middot; Instant WhatsApp Confirmation &middot; Zero Booking Fees</span>
      </div>
    </div>
  );
}

/* ── Mount ──────────────────────────────────────────────────── */
const rootEl = document.getElementById('reservation-root');
if (rootEl) {
  ReactDOM.createRoot(rootEl).render(React.createElement(ReservationCard));
}
