// Multi-step booking flow:
//   1. Pick cottage    →    2. Dates    →    3. Guests + dogs    →    4. Confirm / "go to Airbnb"
//
// User answer was: open a date picker modal and submit OUT to an external host (Airbnb / Vrbo).
// So the final step is a soft handoff — "Continue to Airbnb to confirm."

const BookingModal = ({ open, onClose, prefillCottage }) => {
  const [step, setStep] = React.useState(0);
  const [cottage, setCottage] = React.useState(prefillCottage || 'buttercup');
  const [checkIn, setCheckIn] = React.useState(null);
  const [checkOut, setCheckOut] = React.useState(null);
  const [guests, setGuests] = React.useState(2);
  const [dogs, setDogs] = React.useState(0);

  // Real availability — fetched once per page-load when the modal first opens.
  // Shape: { buttercup: ["YYYY-MM-DD", ...], countryside: [...], updatedAt, errors? }
  const [avail, setAvail] = React.useState(null);
  const [availLoading, setAvailLoading] = React.useState(false);
  const [availError, setAvailError] = React.useState(null);

  React.useEffect(() => {
    if (!open || avail) return;
    setAvailLoading(true);
    fetch('/api/availability')
      .then((r) => (r.ok ? r.json() : Promise.reject(new Error('HTTP ' + r.status))))
      .then((data) => { setAvail(data); setAvailError(null); })
      .catch((e) => setAvailError(e.message || String(e)))
      .finally(() => setAvailLoading(false));
  }, [open, avail]);

  // Reset when opened with a fresh prefill
  React.useEffect(() => {
    if (open) {
      setStep(0);
      setCottage(prefillCottage || 'buttercup');
      setCheckIn(null); setCheckOut(null);
      setGuests(2); setDogs(0);
    }
  }, [open, prefillCottage]);

  // ESC to close
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  const c = window.COTTAGES[cottage];
  const nights = checkIn && checkOut ? Math.max(0, Math.round((checkOut - checkIn) / 86400000)) : 0;
  const subtotal = nights * c.pricePerNight;
  const cleaning = nights > 0 ? 65 : 0;
  const dogFee = dogs * 30;
  const total = subtotal + cleaning + dogFee;

  const canAdvance =
    step === 0 ? !!cottage :
    step === 1 ? nights >= c.minNights :
    step === 2 ? guests >= 1 && guests <= c.sleeps :
    true;

  const labels = ['Cottage', 'Dates', 'Guests', 'Confirm'];

  return (
    <div className="slf-modal-overlay" onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 200,
      background: 'rgba(46, 42, 38, 0.55)', backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
      animation: 'slf-fadein 200ms var(--ease-out) both',
    }}>
      <div className="slf-modal-shell" onClick={(e) => e.stopPropagation()} style={{
        width: 'min(900px, 100%)', maxHeight: '92vh',
        background: 'var(--bg)', borderRadius: 'var(--radius-lg)',
        boxShadow: 'var(--shadow-frame)', overflow: 'hidden',
        display: 'flex', flexDirection: 'column',
        animation: 'slf-rise 280ms var(--ease-out) both',
      }}>
        {/* Header / progress */}
        <header style={{
          padding: '20px 28px', borderBottom: '1px solid var(--border)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
          background: 'var(--bg-2)',
        }}>
          <div className="eyebrow">Stay with us · Step {step + 1} of {labels.length}</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            {labels.map((lab, i) => (
              <div key={lab} style={{
                fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 600,
                letterSpacing: '0.16em', textTransform: 'uppercase',
                color: i === step ? c.accentDeep : i < step ? 'var(--fg-2)' : 'var(--fg-3)',
                opacity: i === step ? 1 : 0.62,
                display: 'flex', alignItems: 'center', gap: 8,
              }}>
                <span style={{
                  width: 18, height: 18, borderRadius: 999,
                  background: i <= step ? c.accent : 'transparent',
                  border: `1px solid ${i <= step ? c.accent : 'var(--border-strong)'}`,
                  color: 'var(--cream)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 10, fontWeight: 700,
                }}>{i < step ? '✓' : i + 1}</span>
                {lab}
              </div>
            ))}
            <button onClick={onClose} aria-label="Close" style={{
              border: 0, background: 'transparent', cursor: 'pointer',
              fontSize: 20, color: 'var(--fg-3)', marginLeft: 8, lineHeight: 1,
            }}>×</button>
          </div>
        </header>

        {/* Body */}
        <div className="slf-modal-body" style={{ padding: '32px 36px', overflowY: 'auto', flex: 1 }}>
          {step === 0 && (
            <StepCottage cottage={cottage} setCottage={setCottage}/>
          )}
          {step === 1 && (
            <StepDates
              cottage={c}
              checkIn={checkIn} setCheckIn={setCheckIn}
              checkOut={checkOut} setCheckOut={setCheckOut}
              unavailableDays={(avail && avail[cottage]) || []}
              availLoading={availLoading}
              availError={availError}
            />
          )}
          {step === 2 && (
            <StepGuests cottage={c} guests={guests} setGuests={setGuests} dogs={dogs} setDogs={setDogs}/>
          )}
          {step === 3 && (
            <StepConfirm cottage={c} checkIn={checkIn} checkOut={checkOut} nights={nights} guests={guests} dogs={dogs}
              subtotal={subtotal} cleaning={cleaning} dogFee={dogFee} total={total}/>
          )}
        </div>

        {/* Footer */}
        <footer className="slf-modal-footer" style={{
          padding: '18px 28px', borderTop: '1px solid var(--border)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
          background: 'var(--bg-2)',
        }}>
          <div className="slf-modal-total" style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--fg-3)' }}>
            {nights > 0 ? (
              <>{c.name} · <strong style={{ color: 'var(--fg)' }}>{nights} nights</strong> · £{total} total</>
            ) : (
              <>{c.name} · from £{c.pricePerNight}/night</>
            )}
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            {step > 0 && (
              <button onClick={() => setStep(step - 1)} className="slf-btn slf-btn-ghost">← Back</button>
            )}
            {step < 3 ? (
              <button disabled={!canAdvance} onClick={() => setStep(step + 1)}
                className="slf-btn"
                style={{
                  background: canAdvance ? c.accent : 'var(--border-strong)',
                  color: 'var(--cream)', padding: '12px 22px', fontSize: 14,
                  cursor: canAdvance ? 'pointer' : 'not-allowed',
                  opacity: canAdvance ? 1 : 0.7,
                }}>Continue →</button>
            ) : (
              <a href={c.bookingUrl} target="_blank" rel="noopener noreferrer"
                className="slf-btn"
                style={{
                  background: c.accent, color: 'var(--cream)',
                  padding: '12px 22px', fontSize: 14, textDecoration: 'none',
                }}>Continue on Airbnb →</a>
            )}
          </div>
        </footer>
      </div>

      <style>{`
        @keyframes slf-fadein { from { opacity: 0 } to { opacity: 1 } }
      `}</style>
    </div>
  );
};

// ============== STEP 1: COTTAGE ===============
const StepCottage = ({ cottage, setCottage }) => {
  const cards = [window.COTTAGES.buttercup, window.COTTAGES.countryside];
  return (
    <div>
      <h3 style={{ fontFamily: 'var(--font-serif)', fontSize: 30, fontWeight: 500, color: 'var(--fg)', margin: 0 }}>
        Which cottage?
      </h3>
      <p style={{ fontFamily: 'var(--font-sans)', fontSize: 14, color: 'var(--fg-3)', marginTop: 6 }}>
        Both sleep two. They share the same hill.
      </p>
      <div className="slf-modal-cottages" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 24 }}>
        {cards.map((c) => {
          const sel = cottage === c.id;
          return (
            <button key={c.id} onClick={() => setCottage(c.id)} style={{
              padding: 0, cursor: 'pointer', textAlign: 'left',
              background: 'var(--bg-2)',
              border: sel ? `2px solid ${c.accent}` : '2px solid transparent',
              outline: sel ? 'none' : '1px solid var(--border)',
              borderRadius: 'var(--radius-md)', overflow: 'hidden',
              transition: 'border-color var(--dur-mid) var(--ease-out)',
              display: 'flex', flexDirection: 'column',
            }}>
              <div style={{ aspectRatio: '4 / 3', overflow: 'hidden' }}>
                <img src={c.hero} alt={c.name} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}/>
              </div>
              <div style={{ padding: '16px 18px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                  <span style={{ width: 8, height: 8, borderRadius: 999, background: c.accent }}/>
                  <span className="eyebrow" style={{ color: c.accentDeep }}>{c.eyebrow}</span>
                </div>
                <div style={{ fontFamily: 'var(--font-serif)', fontSize: 22, fontWeight: 500, color: c.accentDeep }}>
                  {c.name}
                </div>
                <div style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--fg-3)', marginTop: 4 }}>
                  Sleeps {c.sleeps} · from £{c.pricePerNight}/night
                </div>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
};

// ============== STEP 2: DATES ==============
const StepDates = ({ cottage, checkIn, setCheckIn, checkOut, setCheckOut, unavailableDays, availLoading, availError }) => {
  // Render a rolling 2-month calendar from today.
  const today = new Date();
  today.setHours(0,0,0,0);
  const [monthOffset, setMonthOffset] = React.useState(0);

  const monthA = addMonths(today, monthOffset);
  const monthB = addMonths(today, monthOffset + 1);

  // Real per-cottage unavailability — Set keyed by toDateString() so the
  // existing Month/isUnav consumer needs no further change.
  const unavailable = React.useMemo(() => {
    const out = new Set();
    for (const ymd of (unavailableDays || [])) {
      const [y, m, d] = ymd.split('-').map(Number);
      if (!y || !m || !d) continue;
      out.add(new Date(y, m - 1, d).toDateString());
    }
    return out;
  }, [unavailableDays]);

  const onPick = (d) => {
    if (unavailable.has(d.toDateString())) return;
    if (!checkIn || (checkIn && checkOut)) {
      setCheckIn(d); setCheckOut(null);
    } else if (d <= checkIn) {
      setCheckIn(d);
    } else {
      setCheckOut(d);
    }
  };

  const nights = checkIn && checkOut ? Math.round((checkOut - checkIn) / 86400000) : 0;
  const minMet = nights >= cottage.minNights;

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <div>
          <h3 style={{ fontFamily: 'var(--font-serif)', fontSize: 30, fontWeight: 500, color: 'var(--fg)', margin: 0 }}>
            When?
          </h3>
          <p style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--fg-3)', marginTop: 6 }}>
            {cottage.minNights}-night minimum · faded dates aren't available
            {availLoading && <span style={{ fontStyle: 'italic' }}> · loading availability…</span>}
            {availError && <span style={{ color: 'var(--terracotta-deep)', fontStyle: 'italic' }}> · couldn't load availability — please confirm dates on Airbnb</span>}
          </p>
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          <button onClick={() => setMonthOffset(Math.max(0, monthOffset - 1))} className="slf-btn slf-btn-ghost" style={{ padding: '8px 14px', fontSize: 13 }}>←</button>
          <button onClick={() => setMonthOffset(monthOffset + 1)} className="slf-btn slf-btn-ghost" style={{ padding: '8px 14px', fontSize: 13 }}>→</button>
        </div>
      </div>

      <div className="slf-modal-months" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32, marginTop: 24 }}>
        <Month month={monthA} onPick={onPick} checkIn={checkIn} checkOut={checkOut} unavailable={unavailable} cottage={cottage}/>
        <Month month={monthB} onPick={onPick} checkIn={checkIn} checkOut={checkOut} unavailable={unavailable} cottage={cottage}/>
      </div>

      <div style={{
        marginTop: 24, padding: '16px 18px',
        background: nights > 0 ? cottage.accentSoft : 'var(--bg-2)',
        borderRadius: 'var(--radius-md)',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        fontFamily: 'var(--font-sans)', fontSize: 14, color: 'var(--fg-2)',
      }}>
        <span>
          {checkIn ? <>From <strong style={{ color: 'var(--fg)' }}>{fmt(checkIn)}</strong></> : 'Pick a check-in date'}
          {checkOut && <> &nbsp;→&nbsp; <strong style={{ color: 'var(--fg)' }}>{fmt(checkOut)}</strong></>}
        </span>
        {nights > 0 && (
          <span style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', color: minMet ? cottage.accentDeep : 'var(--terracotta-deep)' }}>
            {nights} {nights === 1 ? 'night' : 'nights'}
            {!minMet && <> &nbsp;·&nbsp; (minimum {cottage.minNights})</>}
          </span>
        )}
      </div>
    </div>
  );
};

const Month = ({ month, onPick, checkIn, checkOut, unavailable, cottage }) => {
  const y = month.getFullYear();
  const m = month.getMonth();
  const first = new Date(y, m, 1);
  const daysInMonth = new Date(y, m + 1, 0).getDate();
  const startDay = (first.getDay() + 6) % 7; // Mon-first

  const cells = [];
  for (let i = 0; i < startDay; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(new Date(y, m, d));

  return (
    <div>
      <div style={{
        fontFamily: 'var(--font-serif)', fontSize: 18, fontWeight: 500,
        color: 'var(--fg)', textAlign: 'center', marginBottom: 12,
      }}>
        {month.toLocaleDateString('en-GB', { month: 'long', year: 'numeric' })}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 2 }}>
        {['Mo','Tu','We','Th','Fr','Sa','Su'].map((d) => (
          <div key={d} style={{
            fontFamily: 'var(--font-sans)', fontSize: 10, fontWeight: 700,
            letterSpacing: '0.14em', textTransform: 'uppercase',
            color: 'var(--fg-3)', textAlign: 'center', padding: '6px 0',
          }}>{d}</div>
        ))}
        {cells.map((d, i) => {
          if (!d) return <div key={i}/>;
          const isUnav = unavailable.has(d.toDateString());
          const isCheckIn = checkIn && d.toDateString() === checkIn.toDateString();
          const isCheckOut = checkOut && d.toDateString() === checkOut.toDateString();
          const isInRange = checkIn && checkOut && d > checkIn && d < checkOut;
          const isSelected = isCheckIn || isCheckOut;
          const past = d < new Date(new Date().setHours(0,0,0,0));
          const disabled = isUnav || past;
          return (
            <button key={i} disabled={disabled} onClick={() => onPick(d)} style={{
              aspectRatio: '1 / 1', border: 0, cursor: disabled ? 'not-allowed' : 'pointer',
              fontFamily: 'var(--font-sans)', fontSize: 13,
              borderRadius: 6,
              background: isSelected ? cottage.accent : isInRange ? cottage.accentSoft : 'transparent',
              color: isSelected ? 'var(--cream)' : disabled ? 'var(--fg-3)' : 'var(--fg)',
              opacity: disabled ? 0.35 : 1,
              textDecoration: isUnav && !past ? 'line-through' : 'none',
              fontWeight: isSelected ? 700 : 400,
              transition: 'background var(--dur-fast) var(--ease-out)',
            }}>{d.getDate()}</button>
          );
        })}
      </div>
    </div>
  );
};

// ============== STEP 3: GUESTS ==============
const StepGuests = ({ cottage, guests, setGuests, dogs, setDogs }) => (
  <div>
    <h3 style={{ fontFamily: 'var(--font-serif)', fontSize: 30, fontWeight: 500, color: 'var(--fg)', margin: 0 }}>
      Who's coming?
    </h3>
    <p style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--fg-3)', marginTop: 6 }}>
      {cottage.name} sleeps {cottage.sleeps}.
    </p>

    <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 28 }}>
      <Counter
        title="Guests" sub="Adults & children" min={1} max={cottage.sleeps}
        value={guests} setValue={setGuests} accent={cottage.accent}
      />
      <Counter
        title="Dogs" sub="£30 per dog · per night" min={0} max={3}
        value={dogs} setValue={setDogs} accent={cottage.accent}
      />
    </div>

    <p style={{
      fontFamily: 'var(--font-serif)', fontStyle: 'italic',
      fontSize: 16, color: 'var(--fg-3)', marginTop: 32,
      paddingTop: 20, borderTop: '1px dashed var(--border)',
    }}>
      Travelling with more than four? Drop us a line — we sometimes let both cottages together.
    </p>
  </div>
);

const Counter = ({ title, sub, value, setValue, min, max, accent }) => (
  <div style={{
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    padding: '18px 22px', background: 'var(--bg-2)',
    border: '1px solid var(--border)', borderRadius: 'var(--radius-md)',
  }}>
    <div>
      <div style={{ fontFamily: 'var(--font-serif)', fontSize: 22, fontWeight: 500, color: 'var(--fg)' }}>{title}</div>
      <div style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--fg-3)', marginTop: 2 }}>{sub}</div>
    </div>
    <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
      <button onClick={() => setValue(Math.max(min, value - 1))} disabled={value <= min} style={counterBtnStyle(accent, value <= min)}>−</button>
      <span style={{ fontFamily: 'var(--font-serif)', fontSize: 24, fontWeight: 500, minWidth: 28, textAlign: 'center', color: 'var(--fg)' }}>{value}</span>
      <button onClick={() => setValue(Math.min(max, value + 1))} disabled={value >= max} style={counterBtnStyle(accent, value >= max)}>+</button>
    </div>
  </div>
);

const counterBtnStyle = (accent, disabled) => ({
  width: 36, height: 36, borderRadius: 999, cursor: disabled ? 'not-allowed' : 'pointer',
  border: '1px solid var(--border-strong)', background: 'var(--bg)',
  color: disabled ? 'var(--fg-3)' : accent,
  fontSize: 18, fontWeight: 600, lineHeight: 1, opacity: disabled ? 0.4 : 1,
});

// ============== STEP 4: CONFIRM ==============
const StepConfirm = ({ cottage, checkIn, checkOut, nights, guests, dogs, subtotal, cleaning, dogFee, total }) => (
  <div>
    <h3 style={{ fontFamily: 'var(--font-serif)', fontSize: 30, fontWeight: 500, color: cottage.accentDeep, margin: 0 }}>
      Almost there.
    </h3>
    <p style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 18, color: 'var(--fg-2)', marginTop: 8 }}>
      We host both cottages on Airbnb. Tap below to confirm dates and pay there.
    </p>

    <div style={{
      marginTop: 24, padding: '24px 24px',
      background: cottage.accentSoft, border: `1px solid ${cottage.accent}`,
      borderRadius: 'var(--radius-md)',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
        <div style={{ width: 88, height: 88, borderRadius: 8, overflow: 'hidden', flexShrink: 0 }}>
          <img src={cottage.hero} alt={cottage.name} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}/>
        </div>
        <div>
          <div className="eyebrow" style={{ color: cottage.accentDeep }}>{cottage.eyebrow}</div>
          <div style={{ fontFamily: 'var(--font-serif)', fontSize: 26, fontWeight: 500, color: cottage.accentDeep, marginTop: 2 }}>
            {cottage.name}
          </div>
          <div style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--fg-2)', marginTop: 4 }}>
            {fmt(checkIn)} → {fmt(checkOut)} · {guests} guest{guests > 1 ? 's' : ''}{dogs > 0 && <> · {dogs} dog{dogs > 1 ? 's' : ''}</>}
          </div>
        </div>
      </div>

      <ul style={{ listStyle: 'none', padding: 0, margin: '24px 0 0', display: 'flex', flexDirection: 'column', gap: 8 }}>
        <Row label={`£${cottage.pricePerNight} × ${nights} nights`} value={`£${subtotal}`}/>
        <Row label="Cleaning" value={`£${cleaning}`}/>
        {dogFee > 0 && <Row label={`Dog fee (${dogs})`} value={`£${dogFee}`}/>}
      </ul>
      <div style={{
        marginTop: 12, paddingTop: 14, borderTop: `1px solid ${cottage.accent}`,
        display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
        fontFamily: 'var(--font-serif)', fontSize: 22,
      }}>
        <span style={{ fontStyle: 'italic', color: 'var(--fg)' }}>Total</span>
        <span style={{ fontWeight: 600, color: cottage.accentDeep }}>£{total}</span>
      </div>
    </div>

    <p style={{
      fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--fg-3)',
      marginTop: 20, lineHeight: 1.6, textAlign: 'center',
    }}>
      Prices are guides. The exact total &amp; final availability are confirmed on Airbnb.
    </p>
  </div>
);

const Row = ({ label, value }) => (
  <li style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--font-sans)', fontSize: 14, color: 'var(--fg-2)' }}>
    <span>{label}</span>
    <span>{value}</span>
  </li>
);

// ============== UTIL ==============
function addMonths(d, n) { const out = new Date(d); out.setDate(1); out.setMonth(out.getMonth() + n); return out; }
function fmt(d) { return d ? d.toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' }) : ''; }

window.BookingModal = BookingModal;
