// heritage/rooms.jsx — Rooms grid + detail modal

function RoomCard({ room, onOpen, theme, idx }) {
  const [hover, setHover] = React.useState(false);
  return (
    <article
      onClick={onOpen}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        background: theme.cream, border: `1px solid ${theme.ink}15`,
        cursor: 'pointer', position: 'relative',
        transition: 'transform .35s cubic-bezier(.2,.7,.2,1), box-shadow .35s',
        transform: hover ? 'translateY(-4px)' : 'translateY(0)',
        boxShadow: hover ? '0 24px 48px rgba(0,0,0,0.12)' : '0 0 0 rgba(0,0,0,0)',
      }}>
      <div style={{ aspectRatio: '4 / 5', overflow: 'hidden', position: 'relative' }}>
        <img src={img(room.images[0], 800)} loading="lazy"
          style={{
            position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover',
            transition: 'transform 1.2s ease',
            transform: hover ? 'scale(1.04)' : 'scale(1)',
          }} alt="" />
        {/* corner badge */}
        <div style={{
          position: 'absolute', top: 16, left: 16,
          background: hover ? theme.oxblood : `${theme.cream}f0`, color: hover ? theme.cream : theme.ink,
          padding: '6px 10px', transition: 'background .3s, color .3s',
        }}>
          <Caps size={9} ls={0.24} style={{ fontFamily: theme.sans }}>{room.tag}</Caps>
        </div>
      </div>

      <div style={{ padding: '28px 28px 32px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 14, gap: 16, flexWrap: 'wrap' }}>
          <h3 style={{ fontFamily: theme.serif, fontSize: 'clamp(24px, 2.2vw, 32px)', fontWeight: 400, color: theme.ink, margin: 0, letterSpacing: '-0.01em', minWidth: 0, flex: '1 1 auto' }}>{room.name}</h3>
          <div style={{ textAlign: 'right', flex: '0 0 auto' }}>
            <Caps size={9} color={theme.ink} ls={0.2} style={{ fontFamily: theme.sans, opacity: 0.55 }}>From</Caps>
            <div style={{ fontFamily: theme.serif, fontSize: 22, color: theme.oxblood, marginTop: 2 }}>${room.rate}</div>
          </div>
        </div>
        <div style={{ fontFamily: theme.serif, fontStyle: 'italic', fontSize: 14, color: `${theme.ink}99`, marginBottom: 22, lineHeight: 1.45 }}>
          {room.note}
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderTop: `1px solid ${theme.ink}15`, paddingTop: 16 }}>
          <Caps size={10} color={theme.ink} ls={0.18} style={{ fontFamily: theme.sans, opacity: 0.7 }}>
            {room.size} · {room.bed}
          </Caps>
          <span style={{ fontFamily: theme.serif, fontStyle: 'italic', fontSize: 14, color: theme.oxblood, transition: 'transform .2s', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            View room <span style={{ transition: 'transform .2s', transform: hover ? 'translateX(4px)' : 'translateX(0)' }}>→</span>
          </span>
        </div>
      </div>
    </article>
  );
}

function RoomModal({ room, onClose, theme, mobile }) {
  const [imgIdx, setImgIdx] = React.useState(0);

  React.useEffect(() => {
    document.body.style.overflow = 'hidden';
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowRight') setImgIdx((i) => (i + 1) % room.images.length);
      if (e.key === 'ArrowLeft') setImgIdx((i) => (i - 1 + room.images.length) % room.images.length);
    };
    document.addEventListener('keydown', onKey);
    return () => { document.body.style.overflow = ''; document.removeEventListener('keydown', onKey); };
  }, [room, onClose]);

  return ReactDOM.createPortal(
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 100,
      background: 'rgba(20, 16, 12, 0.72)', backdropFilter: 'blur(8px)',
      display: 'flex', alignItems: mobile ? 'flex-end' : 'center', justifyContent: 'center',
      padding: mobile ? '0' : '40px 56px', animation: 'mFade .3s ease',
    }}>
      <style>{`
        @keyframes mFade { from { opacity: 0; } to { opacity: 1; } }
        @keyframes mSlide { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
      `}</style>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: theme.cream, width: '100%', maxWidth: mobile ? '100%' : 1240,
        maxHeight: mobile ? '92vh' : 'calc(100vh - 80px)',
        overflow: 'auto', position: 'relative', animation: 'mSlide .4s cubic-bezier(.2,.7,.2,1)',
        borderRadius: mobile ? '12px 12px 0 0' : 0,
      }}>
        {/* close */}
        <button onClick={onClose} style={{
          position: 'absolute', top: 16, right: 16, zIndex: 5,
          width: 40, height: 40, borderRadius: 20, border: 'none',
          background: theme.cream, color: theme.ink, cursor: 'pointer',
          fontSize: 18, lineHeight: 1, boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
        }}>×</button>

        <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1.3fr 1fr' }}>
          {/* gallery */}
          <div style={{ background: theme.ink }}>
            <div style={{ position: 'relative', aspectRatio: '4 / 5' }}>
              {room.images.map((k, i) => (
                <img key={i} src={img(k, 1400)} style={{
                  position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover',
                  opacity: i === imgIdx ? 1 : 0, transition: 'opacity .5s ease',
                }} alt="" />
              ))}
              <PhotoKey label={`room${ROOMS.indexOf(room) + 1}_${imgIdx + 1}`} />
              {/* prev / next */}
              <button onClick={() => setImgIdx((i) => (i - 1 + room.images.length) % room.images.length)}
                style={{ position: 'absolute', left: 16, top: '50%', transform: 'translateY(-50%)', width: 40, height: 40, borderRadius: 20, border: 'none', background: `${theme.cream}cc`, cursor: 'pointer', color: theme.ink, fontSize: 16 }}>‹</button>
              <button onClick={() => setImgIdx((i) => (i + 1) % room.images.length)}
                style={{ position: 'absolute', right: 16, top: '50%', transform: 'translateY(-50%)', width: 40, height: 40, borderRadius: 20, border: 'none', background: `${theme.cream}cc`, cursor: 'pointer', color: theme.ink, fontSize: 16 }}>›</button>
              {/* thumbs */}
              <div style={{ position: 'absolute', bottom: 16, left: 16, right: 16, display: 'flex', gap: 6, justifyContent: 'center' }}>
                {room.images.map((_, i) => (
                  <button key={i} onClick={() => setImgIdx(i)}
                    style={{ flex: 1, height: 3, background: i === imgIdx ? theme.cream : `${theme.cream}55`, border: 'none', cursor: 'pointer', padding: 0, transition: 'background .25s' }} />
                ))}
              </div>
            </div>
          </div>

          {/* details */}
          <div style={{ padding: '48px 48px 44px', display: 'flex', flexDirection: 'column' }}>
            <Caps size={10} color={theme.oxblood} ls={0.28} style={{ fontFamily: theme.sans }}>{room.tag}</Caps>
            <h2 style={{ fontFamily: theme.serif, fontSize: 52, fontWeight: 400, color: theme.ink, margin: '12px 0 16px', letterSpacing: '-0.015em', lineHeight: 1 }}>{room.name}</h2>
            <Rule color={theme.ink} w={36} opacity={0.35} />

            <div style={{ fontFamily: theme.serif, fontStyle: 'italic', fontSize: 18, color: `${theme.ink}cc`, lineHeight: 1.55, marginTop: 24, marginBottom: 32 }}>
              {room.note}
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0, borderTop: `1px solid ${theme.ink}15`, borderBottom: `1px solid ${theme.ink}15`, padding: '16px 0', marginBottom: 28 }}>
              {[['Size', room.size], ['Bed', room.bed], ['View', room.view], ['Sleeps', `${room.sleeps} guests`]].map(([k, v]) => (
                <div key={k} style={{ padding: '10px 0' }}>
                  <Caps size={9} color={theme.ink} ls={0.22} style={{ fontFamily: theme.sans, opacity: 0.55 }}>{k}</Caps>
                  <div style={{ fontFamily: theme.serif, fontSize: 16, color: theme.ink, marginTop: 4 }}>{v}</div>
                </div>
              ))}
            </div>

            <Caps size={10} color={theme.oxblood} ls={0.24} style={{ fontFamily: theme.sans, marginBottom: 14, display: 'block' }}>In the room</Caps>
            <ul style={{ listStyle: 'none', padding: 0, margin: '0 0 32px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px 16px' }}>
              {room.amenities.map((a) => (
                <li key={a} style={{ fontFamily: theme.serif, fontSize: 15, color: `${theme.ink}cc`, fontStyle: 'italic', display: 'flex', alignItems: 'center', gap: 8 }}>
                  <svg width="5" height="5" viewBox="0 0 5 5"><rect x="2.5" y="0" width="3.5" height="3.5" transform="rotate(45 2.5 2.5)" fill={theme.oxblood} /></svg>
                  {a}
                </li>
              ))}
            </ul>

            <div style={{ marginTop: 'auto', display: 'flex', alignItems: 'center', justifyContent: 'space-between', borderTop: `1px solid ${theme.ink}22`, paddingTop: 24 }}>
              <div>
                <Caps size={9} color={theme.ink} ls={0.22} style={{ fontFamily: theme.sans, opacity: 0.55 }}>Best Rate · per night</Caps>
                <div style={{ fontFamily: theme.serif, fontSize: 36, color: theme.oxblood, marginTop: 2, lineHeight: 1 }}>${room.rate}</div>
              </div>
              <button style={{
                background: theme.oxblood, color: theme.cream, border: 'none',
                padding: '18px 32px', fontFamily: theme.sans, fontSize: 11,
                letterSpacing: '0.18em', textTransform: 'uppercase', cursor: 'pointer',
                transition: 'background .2s', fontWeight: 500,
              }}
              onClick={() => { onClose(); document.querySelector('#top')?.scrollIntoView({ behavior: 'smooth' }); }}
              onMouseEnter={(e) => e.currentTarget.style.background = theme.ink}
              onMouseLeave={(e) => e.currentTarget.style.background = theme.oxblood}>
                Reserve this room →
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>,
    document.body,
  );
}

function HeritageRooms({ theme, mobile }) {
  const [openRoom, setOpenRoom] = React.useState(null);
  const px = mobile ? 24 : 56;

  return (
    <section id="rooms" style={{ background: theme.sand, padding: `${theme.sp(140)}px ${px}px` }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <div data-reveal style={{
          display: 'grid',
          gridTemplateColumns: mobile ? '1fr' : '1fr 1.6fr',
          gap: mobile ? 24 : 96,
          marginBottom: mobile ? 40 : 80,
          alignItems: 'flex-end',
        }}>
          <div>
            <Caps size={10} color={theme.oxblood} ls={0.3} style={{ fontFamily: theme.sans }}>Chapter II · The Rooms</Caps>
            <Rule color={theme.ink} w={36} opacity={0.35} style={{ marginTop: 14 }} />
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 32 }}>
            <h2 style={{
              fontFamily: theme.serif, fontSize: 'clamp(36px, 5.5vw, 80px)',
              lineHeight: 1.0, fontWeight: 400, color: theme.ink,
              margin: 0, letterSpacing: '-0.02em',
            }}>
              The best sleep <em style={{ fontStyle: 'italic', color: theme.oxblood }}>you'll ever get.</em>
            </h2>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : 'repeat(auto-fit, minmax(300px, 1fr))', gap: mobile ? 24 : 32 }}>
          {ROOMS.map((r, i) => (
            <div key={r.id} data-reveal data-reveal-delay={String(Math.min(3, i + 1))}>
              <RoomCard room={r} onOpen={() => setOpenRoom(r)} theme={theme} idx={i} />
            </div>
          ))}
        </div>
      </div>

      {openRoom && <RoomModal room={openRoom} onClose={() => setOpenRoom(null)} theme={theme} mobile={mobile} />}
    </section>
  );
}

window.HeritageRooms = HeritageRooms;
