// heritage/booking.jsx — Booking widget with calendar + guest popovers

function MiniCal({ month, value, hover, onPick, onHover, theme }) {
  const first = new Date(month.getFullYear(), month.getMonth(), 1);
  const last = new Date(month.getFullYear(), month.getMonth() + 1, 0);
  const startDay = (first.getDay() + 6) % 7; // Monday=0
  const cells = [];
  for (let i = 0; i < startDay; i++) cells.push(null);
  for (let d = 1; d <= last.getDate(); d++) cells.push(new Date(month.getFullYear(), month.getMonth(), d));

  const today = new Date(); today.setHours(0, 0, 0, 0);

  return (
    <div style={{ minWidth: 264 }}>
      <div style={{ fontFamily: theme.serif, fontSize: 18, color: theme.ink, textAlign: 'center', marginBottom: 14 }}>
        {month.toLocaleDateString('en-GB', { month: 'long', year: 'numeric' })}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 2, fontFamily: theme.sans }}>
        {['M', 'T', 'W', 'T', 'F', 'S', 'S'].map((d, i) => (
          <div key={i} style={{ textAlign: 'center', fontSize: 10, letterSpacing: '0.14em', color: `${theme.ink}77`, paddingBottom: 8 }}>{d}</div>
        ))}
        {cells.map((d, i) => {
          if (!d) return <div key={i} />;
          const disabled = d < today;
          const isStart = value.start && sameDay(d, value.start);
          const isEnd = value.end && sameDay(d, value.end);
          const inRange = value.start && value.end && isBetween(d, value.start, value.end);
          const hoverEnd = !value.end && value.start && hover && hover > value.start;
          const hoverRange = hoverEnd && isBetween(d, value.start, hover);
          const isHoverEnd = hoverEnd && sameDay(d, hover);
          const selected = isStart || isEnd;
          const ranged = inRange || hoverRange;
          return (
            <button key={i}
              disabled={disabled}
              onClick={() => !disabled && onPick(d)}
              onMouseEnter={() => onHover(d)}
              style={{
                aspectRatio: '1 / 1', border: 'none',
                background: selected ? theme.oxblood : ranged ? `${theme.oxblood}1c` : 'transparent',
                color: selected ? theme.cream : disabled ? `${theme.ink}33` : theme.ink,
                fontFamily: theme.sans, fontSize: 13, fontWeight: selected ? 600 : 400,
                cursor: disabled ? 'default' : 'pointer',
                borderRadius: selected ? 2 : 0,
                outline: isHoverEnd ? `1px dashed ${theme.oxblood}99` : 'none',
                outlineOffset: -2, transition: 'background .12s',
              }}>
              {d.getDate()}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function CalendarPopover({ value, onChange, onClose, theme, mobile }) {
  const [pivot, setPivot] = React.useState(() => {
    const d = value.start || new Date();
    return new Date(d.getFullYear(), d.getMonth(), 1);
  });
  const [draft, setDraft] = React.useState(value);
  const [hover, setHover] = React.useState(null);

  const nextMonth = new Date(pivot.getFullYear(), pivot.getMonth() + 1, 1);

  const pick = (d) => {
    if (!draft.start || (draft.start && draft.end)) {
      setDraft({ start: d, end: null });
    } else if (d <= draft.start) {
      setDraft({ start: d, end: null });
    } else {
      const next = { start: draft.start, end: d };
      setDraft(next);
      setTimeout(() => { onChange(next); onClose(); }, 180);
    }
  };

  const nights = draft.start && draft.end ? Math.round((draft.end - draft.start) / 86400000) : 0;

  const popStyle = mobile
    ? { position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 30, background: '#fff', boxShadow: '0 -8px 40px rgba(0,0,0,0.18)', border: `1px solid ${theme.ink}15`, padding: 20, borderRadius: '12px 12px 0 0' }
    : { position: 'absolute', top: 'calc(100% + 12px)', left: 0, zIndex: 30, background: '#fff', boxShadow: '0 24px 60px rgba(0,0,0,0.18), 0 2px 6px rgba(0,0,0,0.06)', border: `1px solid ${theme.ink}15`, padding: 24 };

  return (
    <div data-pop="cal" onClick={(e) => e.stopPropagation()} style={popStyle}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
        <button onClick={() => setPivot(new Date(pivot.getFullYear(), pivot.getMonth() - 1, 1))}
          style={{ width: 28, height: 28, border: `1px solid ${theme.ink}22`, background: 'transparent', cursor: 'pointer', color: theme.ink, borderRadius: 14 }}>
          <svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" style={{ display: 'block', margin: 'auto' }}><path d="M6 2L3 5l3 3"/></svg>
        </button>
        <Caps size={10} color={theme.oxblood} ls={0.24} style={{ fontFamily: theme.sans }}>
          {nights > 0 ? `${nights} night${nights > 1 ? 's' : ''} selected` : 'Select arrival'}
        </Caps>
        <button onClick={() => setPivot(new Date(pivot.getFullYear(), pivot.getMonth() + 1, 1))}
          style={{ width: 28, height: 28, border: `1px solid ${theme.ink}22`, background: 'transparent', cursor: 'pointer', color: theme.ink, borderRadius: 14 }}>
          <svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" style={{ display: 'block', margin: 'auto' }}><path d="M4 2l3 3-3 3"/></svg>
        </button>
      </div>

      <div style={{ display: 'flex', gap: 32 }}>
        <MiniCal month={pivot} value={draft} hover={hover} onPick={pick} onHover={setHover} theme={theme} />
        {!mobile && <MiniCal month={nextMonth} value={draft} hover={hover} onPick={pick} onHover={setHover} theme={theme} />}
      </div>

      <div style={{ marginTop: 18, paddingTop: 16, borderTop: `1px solid ${theme.ink}11`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div style={{ fontFamily: theme.serif, fontStyle: 'italic', fontSize: 14, color: `${theme.ink}99` }}>
          Minimum 2 nights · Sun–Thu best rate
        </div>
        <button onClick={() => { setDraft({ start: null, end: null }); }}
          style={{ background: 'transparent', border: 'none', cursor: 'pointer', fontFamily: theme.sans, fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: `${theme.ink}88` }}>
          Clear
        </button>
      </div>
    </div>
  );
}

function GuestPopover({ value, onChange, onClose, theme, mobile }) {
  const rows = [
    { k: 'adults',   label: 'Adults',   sub: 'Ages 13 and over', min: 1, max: 6 },
    { k: 'children', label: 'Children', sub: 'Ages 2–12',         min: 0, max: 4 },
    { k: 'infants',  label: 'Infants',  sub: 'Under 2',           min: 0, max: 2 },
  ];

  const Stepper = ({ val, onMinus, onPlus, dec, inc }) => (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
      <button onClick={onMinus} disabled={dec}
        style={{ width: 30, height: 30, borderRadius: 15, border: `1px solid ${theme.ink}33`, background: 'transparent', cursor: dec ? 'not-allowed' : 'pointer', color: theme.ink, opacity: dec ? 0.3 : 1, fontSize: 16, lineHeight: 1 }}>−</button>
      <span style={{ fontFamily: theme.serif, fontSize: 20, color: theme.ink, minWidth: 16, textAlign: 'center', fontVariantNumeric: 'tabular-nums' }}>{val}</span>
      <button onClick={onPlus} disabled={inc}
        style={{ width: 30, height: 30, borderRadius: 15, border: `1px solid ${theme.ink}33`, background: 'transparent', cursor: inc ? 'not-allowed' : 'pointer', color: theme.ink, opacity: inc ? 0.3 : 1, fontSize: 16, lineHeight: 1 }}>+</button>
    </div>
  );

  const popStyle = mobile
    ? { position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 30, background: '#fff', boxShadow: '0 -8px 40px rgba(0,0,0,0.18)', border: `1px solid ${theme.ink}15`, padding: 24, borderRadius: '12px 12px 0 0' }
    : { position: 'absolute', top: 'calc(100% + 12px)', left: 0, zIndex: 30, background: '#fff', boxShadow: '0 24px 60px rgba(0,0,0,0.18), 0 2px 6px rgba(0,0,0,0.06)', border: `1px solid ${theme.ink}15`, padding: 24, minWidth: 340 };

  return (
    <div data-pop="guests" onClick={(e) => e.stopPropagation()} style={popStyle}>
      <Caps size={10} color={theme.oxblood} ls={0.24} style={{ fontFamily: theme.sans, marginBottom: 18, display: 'block' }}>Guests</Caps>
      {rows.map((r, i) => (
        <div key={r.k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: i ? 18 : 0, paddingBottom: i < rows.length - 1 ? 18 : 0, borderTop: i ? `1px solid ${theme.ink}10` : 'none' }}>
          <div>
            <div style={{ fontFamily: theme.serif, fontSize: 18, color: theme.ink }}>{r.label}</div>
            <div style={{ fontFamily: theme.sans, fontSize: 12, color: `${theme.ink}88`, marginTop: 2 }}>{r.sub}</div>
          </div>
          <Stepper val={value[r.k]}
            dec={value[r.k] <= r.min} inc={value[r.k] >= r.max}
            onMinus={() => onChange({ ...value, [r.k]: Math.max(r.min, value[r.k] - 1) })}
            onPlus={() => onChange({ ...value, [r.k]: Math.min(r.max, value[r.k] + 1) })} />
        </div>
      ))}
      <div style={{ borderTop: `1px solid ${theme.ink}11`, paddingTop: 18, marginTop: 18, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div style={{ fontFamily: theme.serif, fontStyle: 'italic', fontSize: 14, color: `${theme.ink}99` }}>
          Children under 5 stay complimentary
        </div>
        <button onClick={onClose}
          style={{ background: theme.ink, color: theme.cream, border: 'none', padding: '10px 18px', fontFamily: theme.sans, fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', cursor: 'pointer' }}>
          Done
        </button>
      </div>
    </div>
  );
}

function BookingWidget({ theme, layout, onSearch, mobile }) {
  const [dates, setDates] = React.useState(() => ({
    start: addDays(new Date(), 14),
    end: addDays(new Date(), 17),
  }));
  const [guests, setGuests] = React.useState({ adults: 2, children: 0, infants: 0 });
  const [openPop, setOpenPop] = React.useState(null);

  const wrapRef = React.useRef(null);
  React.useEffect(() => {
    const onDocClick = (e) => {
      if (!wrapRef.current) return;
      if (!wrapRef.current.contains(e.target)) setOpenPop(null);
    };
    document.addEventListener('mousedown', onDocClick);
    return () => document.removeEventListener('mousedown', onDocClick);
  }, []);

  const guestSummary = (() => {
    const a = guests.adults, c = guests.children, i = guests.infants;
    const bits = [`${a} ${a === 1 ? 'Adult' : 'Adults'}`];
    if (c) bits.push(`${c} ${c === 1 ? 'Child' : 'Children'}`);
    if (i) bits.push(`${i} ${i === 1 ? 'Infant' : 'Infants'}`);
    return bits.join(' · ');
  })();

  const Field = ({ k, label, value, noBorderRight }) => (
    <button type="button" onClick={(e) => { e.stopPropagation(); setOpenPop(openPop === k ? null : k); }}
      style={{
        width: '100%', textAlign: 'left', padding: '18px 22px', border: 'none',
        background: openPop === k ? `${theme.ink}06` : 'transparent', cursor: 'pointer',
        borderRight: noBorderRight ? 'none' : `1px solid ${theme.ink}15`,
        fontFamily: 'inherit', transition: 'background .15s',
      }}
      onMouseEnter={(e) => { if (openPop !== k) e.currentTarget.style.background = `${theme.ink}04`; }}
      onMouseLeave={(e) => { if (openPop !== k) e.currentTarget.style.background = 'transparent'; }}>
      <Caps size={9} color={theme.ink} ls={0.22} style={{ fontFamily: theme.sans, opacity: 0.55, display: 'block' }}>{label}</Caps>
      <div style={{ fontFamily: theme.serif, fontSize: 18, color: theme.ink, marginTop: 4 }}>{value}</div>
    </button>
  );

  return (
    <div ref={wrapRef} style={{ position: 'relative', background: '#fff', border: `1px solid ${theme.ink}22`, padding: 2 }}>
      {mobile ? (
        // ── Mobile: stacked layout ──
        <div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
            <Field k="cal" label="Arrive" value={fmtDate(dates.start)} />
            <Field k="cal" label="Depart" value={fmtDate(dates.end)} noBorderRight />
          </div>
          <div style={{ borderTop: `1px solid ${theme.ink}15` }}>
            <Field k="guests" label="Guests" value={guestSummary} noBorderRight />
          </div>
          <div style={{ borderTop: `1px solid ${theme.ink}15` }}>
            <button onClick={() => onSearch && onSearch({ dates, guests })}
              style={{
                width: '100%', background: theme.oxblood, color: theme.cream, border: 'none',
                padding: '18px 24px', fontFamily: theme.sans, fontSize: 11, letterSpacing: '0.18em',
                textTransform: 'uppercase', cursor: 'pointer', fontWeight: 500,
                transition: 'background .2s', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = theme.ink}
              onMouseLeave={(e) => e.currentTarget.style.background = theme.oxblood}>
              Check Availability
            </button>
          </div>
        </div>
      ) : (
        // ── Desktop: 4-col grid ──
        <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1.1fr 1.2fr auto', alignItems: 'stretch' }}>
          <Field k="cal" label="Arrive" value={fmtDate(dates.start)} />
          <Field k="cal" label="Depart" value={fmtDate(dates.end)} />
          {/* Guests wrapped so popover drops directly below this field */}
          <div style={{ position: 'relative' }}>
            <Field k="guests" label="Guests" value={guestSummary} />
            {openPop === 'guests' && (
              <GuestPopover value={guests} onChange={setGuests} onClose={() => setOpenPop(null)} theme={theme} mobile={false} />
            )}
          </div>
          <button onClick={() => onSearch && onSearch({ dates, guests })}
            style={{
              background: theme.oxblood, color: theme.cream, border: 'none',
              padding: '0 36px', fontFamily: theme.sans, fontSize: 11, letterSpacing: '0.18em',
              textTransform: 'uppercase', cursor: 'pointer', fontWeight: 500,
              transition: 'background .2s', display: 'flex', alignItems: 'center', gap: 10,
            }}
            onMouseEnter={(e) => e.currentTarget.style.background = theme.ink}
            onMouseLeave={(e) => e.currentTarget.style.background = theme.oxblood}>
            Check Availability
            <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><path d="M1 5h12M9 1l4 4-4 4"/></svg>
          </button>
        </div>
      )}

      {openPop === 'cal' && (
        <CalendarPopover value={dates} onChange={setDates} onClose={() => setOpenPop(null)} theme={theme} mobile={mobile} />
      )}
      {/* Mobile guest popover rendered at wrapRef level as bottom sheet */}
      {openPop === 'guests' && mobile && (
        <GuestPopover value={guests} onChange={setGuests} onClose={() => setOpenPop(null)} theme={theme} mobile={true} />
      )}
    </div>
  );
}

window.BookingWidget = BookingWidget;
