// layouts.jsx — top bar, apartment toggle, and three layout variations.
const { useState: useStateL } = React;

// ── Segmented apartment toggle (apartments WITHIN one reservation) ─
// A reservation can hold more than one apartment. Instead of stacking them
// (forcing a long scroll) we show one at a time behind an elegant in-page
// segmented control.
function ApartmentTabs({ stays, active, onChange, code, narrow }) {
  const t = window.useT();
  return (
    <div>
      <window.Eyebrow style={{ marginBottom: 10 }}>{t('yourApartments')}</window.Eyebrow>
      <div style={{ display: 'grid', gridTemplateColumns: `repeat(${stays.length}, 1fr)`, border: '1px solid var(--line-strong)', background: 'var(--surface)' }}>
        {stays.map((s, i) => {
          const on = active === i;
          return (
            <button key={s.id} onClick={() => onChange(i)} style={{
              display: 'flex', alignItems: 'center', gap: narrow ? 9 : 12, padding: narrow ? '11px 12px' : '13px 16px', minWidth: 0,
              background: on ? 'var(--brand)' : 'transparent', color: on ? 'var(--on-brand)' : 'var(--fg)',
              border: 'none', borderLeft: i ? '1px solid var(--line-strong)' : 'none',
              cursor: 'pointer', transition: 'background .18s ease, color .18s ease', textAlign: 'start'
            }}>
              <span style={{ width: 32, height: 32, background: s.photo, flexShrink: 0, boxShadow: on ? '0 0 0 2px rgba(249,244,234,0.55)' : 'none' }} />
              <span style={{ minWidth: 0 }}>
                <span style={{ display: 'block', fontFamily: 'var(--font-mono)', fontSize: 12.5, letterSpacing: '0.03em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.unitName}</span>
                <span style={{ display: 'block', fontFamily: 'var(--font-accent)', fontStyle: 'italic', fontSize: 12, opacity: on ? 0.85 : 0.66, marginTop: 2 }}>{t('room')} {s.room} · {t('floor')} {s.floor}</span>
              </span>
            </button>);

        })}
      </div>
    </div>);

}

// Building name set large, light, uppercase (the "LINZERGASSE" lockup).
function BuildingName({ stay, size = 26, color = 'var(--fg)' }) {
  return (
    <div style={{ fontFamily: 'var(--font-serif)', fontWeight: 300, textTransform: 'uppercase', letterSpacing: '0.04em', fontSize: size, lineHeight: 1.05, color, textAlign: 'center' }}>{stay.buildingShort}</div>);

}

// ── Top bar (dark green) ──────────────────────────────────────────
function TopBar({ current, count, narrow }) {
  return (
    <header style={{
      background: 'var(--topbar)', color: 'var(--on-topbar)', display: 'flex', alignItems: 'center',
      justifyContent: 'space-between', padding: narrow ? '0 16px' : '0 28px', height: narrow ? 60 : 68,
      boxShadow: '0px 2px 18px rgba(0,0,0,0.12)', position: 'relative', zIndex: 30
    }}>
      {!narrow ? <window.PropertyName name={current.building} size={16} color="var(--on-topbar)" /> : <span style={{ width: 1 }} />}
      <div style={{ position: 'absolute', left: 0, right: 0, display: 'flex', justifyContent: 'center', pointerEvents: 'none' }}>
        <window.Wordmark height={narrow ? 18 : 22} color="var(--on-topbar)" />
      </div>
      <window.LangToggle onDark align="end" compact={narrow} />
    </header>);

}

// Greeting block. Falls back to a plain "Welcome" headline when the reservation
// carries no guest name, and hides the confirmation chip when there's no code.
function Greeting({ stay, narrow }) {
  const t = window.useT();
  const first = stay.reservation.guest.first;
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16 }}>
      <div>
        {first && <window.Accent style={{ fontSize: 15 }}>{t('welcome')}</window.Accent>}
        <h1 style={{ margin: '4px 0 0', fontFamily: 'var(--font-serif)', fontWeight: 300, fontSize: narrow ? 34 : 44, lineHeight: 1, color: 'var(--fg)' }}>{first || t('welcome')}</h1>
      </div>
      {stay.reservation.code &&
      <div style={{ textAlign: 'end' }}>
        <window.Eyebrow style={{ marginBottom: 6 }}>{t('confirmation')}</window.Eyebrow>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 15, color: 'var(--fg)', letterSpacing: '0.1em' }}>{stay.reservation.code}</div>
      </div>
      }
    </div>);

}

// Stay dates strip — time is the headline, date is the support. The weather cell
// only appears once live weather has loaded (it's omitted when the property has
// no coordinates / the weather call failed). Empty check-in/out values fall back
// to an em dash so the strip never shows a blank.
function DatesStrip({ stay, availableNow }) {
  const t = window.useT();
  const checkIn = availableNow ?
  { value: t('availableNow'), sub: t('walkRightIn'), accent: true } :
  { value: stay.checkIn.time || '—', sub: stay.checkIn.date };
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 0, border: '1px solid var(--line)', background: 'var(--surface)' }}>
      {/* check-in */}
      <div style={{ flex: 1, padding: '16px 18px' }}>
        <window.Eyebrow style={{ marginBottom: 6 }}>{t('checkIn')}</window.Eyebrow>
        {checkIn.accent ?
        <div className="avail-badge" style={{ display: 'inline-flex', alignItems: 'center', gap: 7, background: 'var(--brand)', color: 'var(--on-brand)', padding: '7px 12px', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', lineHeight: 1, backgroundColor: "rgb(127, 149, 131)" }}>
            <window.DoodleSparkle size={14} /> {t('availableNow')}
          </div> :
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 21, color: 'var(--fg)', lineHeight: 1, whiteSpace: 'nowrap' }}>{checkIn.value}</div>
        }
        {checkIn.sub && <div style={{ fontFamily: 'var(--font-accent)', fontStyle: 'italic', fontSize: 12, color: 'var(--fg-faint)', marginTop: 7 }}>{checkIn.sub}</div>}
      </div>
      {/* check-out */}
      <div style={{ flex: 1, padding: '16px 18px', borderLeft: '1px solid var(--line)' }}>
        <window.Eyebrow style={{ marginBottom: 6 }}>{t('checkOut')}</window.Eyebrow>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 21, color: 'var(--fg)', lineHeight: 1 }}>{stay.checkOut.time || '—'}</div>
        {stay.checkOut.date && <div style={{ fontFamily: 'var(--font-accent)', fontStyle: 'italic', fontSize: 12, color: 'var(--fg-faint)', marginTop: 5 }}>{stay.checkOut.date}</div>}
      </div>
      {/* weather replaces the guests cell — it's the live, glanceable thing */}
      {stay.weather &&
      <div style={{ flex: 1, padding: '16px 18px', borderLeft: '1px solid var(--line)' }}>
        <window.Eyebrow style={{ marginBottom: 6 }}>{t('weather')}</window.Eyebrow>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontSize: 20, lineHeight: 1 }}>{{ partly: '⛅', sunny: '☀️', clear: '☀️', cloudy: '☁️', rain: '🌧️', snow: '❄️' }[stay.weather.kind] || '⛅'}</span>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 21, color: 'var(--fg)', lineHeight: 1 }}>{stay.weather.tempC}°</div>
        </div>
        <div style={{ fontFamily: 'var(--font-accent)', fontStyle: 'italic', fontSize: 12, color: 'var(--fg-faint)', marginTop: 5 }}>{stay.weather.label}</div>
      </div>
      }
    </div>);

}

// Per-apartment content (the "apartment box"). Shown one at a time.
function ApartmentPane({ apt, showImage, density, narrow }) {
  const gap = density === 'compact' ? 32 : 48;
  return (
    <div className="apt-pane" key={apt.id} style={{ animation: 'aptFade .26s ease', display: 'flex', flexDirection: 'column', gap }}>
      <window.StayHero stay={apt} showImage={showImage} tall={!narrow} />
      <window.AccessBlock stay={apt} columns={narrow ? 2 : 3} />
      <window.BreakfastBlock stay={apt} collapsible={narrow} />
      <window.EssentialsBlock stay={apt} dense={density === 'compact'} />
      <window.CheckoutBlock stay={apt} />
    </div>);

}

// ════════════════════════════════════════════════════════════════
// VARIATION A — Editorial column
// ════════════════════════════════════════════════════════════════
function LayoutEditorial({ stay, stays, showImage, density, narrow, availableNow }) {
  const t = window.useT();
  const gap = density === 'compact' ? 32 : 48;
  const multi = stays.length > 1;
  const [ai, setAi] = useStateL(0);
  const apt = stays[Math.min(ai, stays.length - 1)];
  return (
    <div style={{ background: 'var(--bg)', minHeight: '100%' }}>
      <TopBar current={stay} count={stays.length} narrow={narrow} />
      <div style={{ maxWidth: 620, margin: '0 auto', padding: narrow ? '28px 18px 60px' : '44px 24px 80px', display: 'flex', flexDirection: 'column', gap }}>
        <Greeting stay={stay} narrow={narrow} />
        <DatesStrip stay={stay} availableNow={availableNow} />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12, paddingBottom: gap, borderBottom: '1px solid var(--line)' }}>
          <window.Accent style={{ fontSize: 13 }}>{stay.city}, {stay.country}</window.Accent>
          <window.Accent style={{ fontSize: 13 }}>{t('guestsNights', { guests: stay.reservation.guests, nights: stay.reservation.nights })}</window.Accent>
        </div>
        {multi && <ApartmentTabs stays={stays} active={ai} onChange={setAi} code={stay.reservation.code} narrow={narrow} />}
        <ApartmentPane apt={apt} showImage={showImage} density={density} narrow={narrow} />
        <window.AddressBlock stay={stay} />
        <window.GuideBlock stay={stay} />
        <window.SupportBlock stay={stay} />
        <Footer />
      </div>
    </div>);

}

// ════════════════════════════════════════════════════════════════
// VARIATION B — Dashboard (sidebar + content)
// ════════════════════════════════════════════════════════════════
function LayoutDashboard({ stay, stays, showImage, density, narrow, availableNow }) {
  const t = window.useT();
  // Only surface nav items that have content across the reservation's rooms.
  const has = {
    access: stays.some((s) => s.wifi && (s.wifi.network || s.wifi.password)),
    breakfast: stays.some((s) => s.breakfast), // only when the rate includes breakfast
    where: stays.some((s) => s.address || s.lat != null || s.googleMaps || s.waze),
    living: stays.some((s) => s.sections && s.sections.length),
    guide: stays.some((s) => s.guide && s.guide.length),
    checkout: stays.some((s) => s.isCheckoutDay), // only on departure day
  };
  // Check-out sits above Connect (only present on the departure day anyway).
  const nav = [['stay', t('navGettingIn')], ['breakfast', t('navBreakfast')], ['checkout', t('navCheckout')], ['access', t('navConnect')], ['where', t('navLocation')], ['living', t('navLiving')], ['guide', t('navExplore')]].
  filter(([id]) => has[id] === undefined || has[id]);
  const [active, setActive] = useStateL('stay');
  const [ai, setAi] = useStateL(0);
  const gap = density === 'compact' ? 28 : 40;
  const multi = stays.length > 1;
  const apt = stays[Math.min(ai, stays.length - 1)];

  if (narrow) {
    // Flat, divided section list: `.divided-sections > * + *` adds a hairline +
    // spacing between each *rendered* section, so sections that return null just
    // don't create a divider. Breakfast sits above Connect; the hero and support
    // cards stay outside the divided list (they have their own boundaries).
    return (
      <div style={{ background: 'var(--bg)', minHeight: '100%' }}>
        <TopBar current={stay} count={stays.length} narrow />
        <div style={{ padding: '24px 18px 60px', display: 'flex', flexDirection: 'column', gap }}>
          <Greeting stay={stay} narrow />
          <DatesStrip stay={stay} availableNow={availableNow} />
          {multi && <ApartmentTabs stays={stays} active={ai} onChange={setAi} code={stay.reservation.code} narrow />}
          <window.StayHero stay={apt} showImage={showImage} />
          <div className="divided-sections apt-pane" key={apt.id} style={{ animation: 'aptFade .26s ease', display: 'flex', flexDirection: 'column' }}>
            <window.BreakfastBlock stay={apt} collapsible />
            {/* On the departure day, check-out (and the luggage box) move above
                Connect. Both render null off checkout-day, so order is unchanged then. */}
            <window.CheckoutBlock stay={apt} />
            <window.LuggageBlock stay={apt} compact />
            <window.AccessBlock stay={apt} columns={2} collapsible />
            <window.EssentialsBlock stay={apt} dense={density === 'compact'} collapsible />
            <window.AddressBlock stay={stay} collapsible />
            <window.GuideBlock stay={stay} collapsible />
          </div>
          <window.SupportBlock stay={stay} />
          <div style={{ textAlign: 'center', fontFamily: 'var(--font-mono)', fontSize: 9.5, color: 'var(--fg-faint)', letterSpacing: '0.06em', marginTop: 4 }}>{t('footer')}</div>
        </div>
      </div>);

  }

  const blocks = {
    stay:
    <div style={{ display: 'flex', flexDirection: 'column', gap }}>
        <Greeting stay={stay} />
        {multi && <ApartmentTabs stays={stays} active={ai} onChange={setAi} />}
        <div className="apt-pane" key={apt.id} style={{ animation: 'aptFade .26s ease', display: 'flex', flexDirection: 'column', gap }}>
          <window.StayHero stay={apt} showImage={showImage} tall />
          <DatesStrip stay={stay} availableNow={availableNow} />
        </div>
      </div>,

    access:
    <div style={{ display: 'flex', flexDirection: 'column', gap }}>
        {multi && <ApartmentTabs stays={stays} active={ai} onChange={setAi} />}
        <div className="apt-pane" key={apt.id} style={{ animation: 'aptFade .26s ease' }}><window.Panel><window.AccessBlock stay={apt} columns={3} /></window.Panel></div>
      </div>,
    where: <window.Panel><window.AddressBlock stay={stay} /></window.Panel>,
    breakfast:
    <div style={{ display: 'flex', flexDirection: 'column', gap }}>
        {multi && <ApartmentTabs stays={stays} active={ai} onChange={setAi} />}
        <div className="apt-pane" key={apt.id} style={{ animation: 'aptFade .26s ease' }}><window.Panel><window.BreakfastBlock stay={apt} /></window.Panel></div>
      </div>,
    living:
    <div style={{ display: 'flex', flexDirection: 'column', gap }}>
        {multi && <ApartmentTabs stays={stays} active={ai} onChange={setAi} />}
        <div className="apt-pane" key={apt.id} style={{ animation: 'aptFade .26s ease' }}><window.Panel><window.EssentialsBlock stay={apt} dense={density === 'compact'} /></window.Panel></div>
      </div>,
    guide: <window.Panel><window.GuideBlock stay={stay} /></window.Panel>,
    checkout:
    <div style={{ display: 'flex', flexDirection: 'column', gap }}>
        {multi && <ApartmentTabs stays={stays} active={ai} onChange={setAi} />}
        <div className="apt-pane" key={apt.id} style={{ animation: 'aptFade .26s ease', display: 'flex', flexDirection: 'column', gap }}>
          <window.Panel><window.CheckoutBlock stay={apt} /></window.Panel>
          <window.LuggageBlock stay={apt} />
        </div>
      </div>
  };

  return (
    <div style={{ background: 'var(--bg)', minHeight: '100vh', display: 'grid', gridTemplateColumns: '286px 1fr' }}>
      {/* sidebar */}
      <aside style={{ background: 'var(--topbar)', color: 'var(--on-topbar)', padding: '28px 24px', display: 'flex', flexDirection: 'column', gap: 26, position: 'sticky', top: 0, alignSelf: 'start', height: '100vh' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <window.Wordmark height={22} color="var(--on-topbar)" />
          <BuildingName stay={stay} size={28} color="var(--on-topbar)" />
        </div>
        <nav style={{ display: 'flex', flexDirection: 'column', gap: 2, marginTop: 6 }}>
          {nav.map(([id, label]) => {
            const on = active === id;
            return (
              <button key={id} onClick={() => setActive(id)} style={{
                textAlign: 'left', background: on ? 'rgba(249,244,234,0.12)' : 'transparent', border: 'none',
                borderLeft: '2px solid ' + (on ? 'var(--on-topbar)' : 'transparent'), color: 'var(--on-topbar)',
                opacity: on ? 1 : 0.66, cursor: 'pointer', padding: '12px 14px', fontFamily: 'var(--font-mono)',
                fontSize: 13, letterSpacing: '0.05em', transition: 'all .15s ease', textAlign: 'start'
              }}>{label}</button>);

          })}
        </nav>
        <div style={{ marginTop: 'auto', paddingTop: 20, borderTop: '1px solid rgba(249,244,234,0.18)' }}>
          <div style={{ marginBottom: 18 }}><window.LangToggle onDark full up /></div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, color: 'var(--on-topbar)' }}>
            <window.DoodleChat size={26} />
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.04em' }}>{t('weReplyMinutes')}</div>
          </div>
          <button onClick={() => window.open('https://wa.me/4366012345678', '_blank')} style={{ marginTop: 14, width: '100%', background: 'var(--on-topbar)', color: 'var(--topbar)', border: 'none', padding: '12px', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', cursor: 'pointer' }}>{t('contactUs')}</button>
          <div style={{ marginTop: 16, textAlign: 'center', fontFamily: 'var(--font-mono)', fontSize: 9.5, color: 'rgba(249,244,234,0.5)', letterSpacing: '0.06em' }}>{t('footer')}</div>
        </div>
      </aside>
      {/* content */}
      <main style={{ padding: '48px 56px 72px', maxWidth: 920 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap }}>
          {blocks[active]}
        </div>
      </main>
    </div>);

}

// ════════════════════════════════════════════════════════════════
// VARIATION C — Bento grid (playful, doodle-forward)
// ════════════════════════════════════════════════════════════════
function LayoutBento({ stay, stays, showImage, density, narrow, availableNow }) {
  const t = window.useT();
  const cols = narrow ? 1 : 3;
  const cell = { background: 'var(--surface)', border: '1px solid var(--line)', padding: 24 };
  const multi = stays.length > 1;
  const [ai, setAi] = useStateL(0);
  const apt = stays[Math.min(ai, stays.length - 1)];
  return (
    <div style={{ background: 'var(--bg)', minHeight: '100%' }}>
      <TopBar current={stay} count={stays.length} narrow={narrow} />
      <div style={{ padding: narrow ? '24px 16px 56px' : '40px 40px 72px', maxWidth: 1180, margin: '0 auto' }}>
        <div style={{ marginBottom: 28 }}><Greeting stay={stay} narrow={narrow} /></div>

        {/* reservation-level row */}
        <div style={{ display: 'grid', gridTemplateColumns: `repeat(${cols}, 1fr)`, gap: 16 }}>
          <div style={{ ...cell, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', gap: 16 }}>
            <window.Eyebrow>{stay.city} {t('now')}</window.Eyebrow>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <span style={{ color: 'var(--illustration)' }}><window.DoodleWeather size={48} /></span>
              <div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 34, color: 'var(--fg)', lineHeight: 1 }}>{stay.weather.tempC}°</div>
                <window.Accent style={{ fontSize: 13 }}>{stay.weather.label}</window.Accent>
              </div>
            </div>
          </div>
          <div style={{ ...cell, gridColumn: narrow ? 'auto' : 'span 2' }}>
            <window.Eyebrow style={{ marginBottom: 14 }}>{t('yourDates')}</window.Eyebrow>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <DateRow label={t('checkIn')} v={availableNow ? t('availableNow') : stay.checkIn.time} s={availableNow ? t('walkRightIn') : stay.checkIn.date} accent={availableNow} />
              <DateRow label={t('checkOut')} v={stay.checkOut.time} s={stay.checkOut.date} />
              <DateRow label={t('guests')} v={stay.reservation.guests} s={stay.reservation.nights + ' ' + t('nights')} />
            </div>
          </div>
        </div>

        {/* apartment toggle + active apartment sub-grid */}
        {multi && <div style={{ marginTop: 28 }}><ApartmentTabs stays={stays} active={ai} onChange={setAi} code={stay.reservation.code} narrow={narrow} /></div>}
        <div className="apt-pane" key={apt.id} style={{ animation: 'aptFade .26s ease', marginTop: multi ? 16 : 28, display: 'grid', gridTemplateColumns: `repeat(${cols}, 1fr)`, gap: 16, gridAutoFlow: 'dense' }}>
          <div style={{ gridColumn: narrow ? 'auto' : 'span 2', gridRow: narrow ? 'auto' : 'span 2', padding: 0, overflow: 'hidden', background: 'var(--surface)', border: '1px solid var(--line)' }}>
            <window.StayHero stay={apt} showImage={showImage} tall />
          </div>
          <div style={{ ...cell }}><window.AddressBlock stay={apt} /></div>
          <div style={{ ...cell }}><window.AccessBlock stay={apt} columns={1} /></div>
          <div style={{ ...cell, gridColumn: narrow ? 'auto' : `span ${cols}` }}><window.EssentialsBlock stay={apt} dense /></div>
          <div style={{ ...cell, gridColumn: narrow ? 'auto' : `span ${cols}` }}><window.CheckoutBlock stay={apt} /></div>
        </div>

        {/* shared city + support */}
        <div style={{ display: 'grid', gridTemplateColumns: `repeat(${cols}, 1fr)`, gap: 16, marginTop: 28 }}>
          <div style={{ ...cell, gridColumn: narrow ? 'auto' : 'span 1' }}><window.GuideBlock stay={stay} /></div>
          <div style={{ gridColumn: narrow ? 'auto' : 'span 2' }}><window.SupportBlock stay={stay} /></div>
        </div>
        <Footer />
      </div>
    </div>);

}

function DateRow({ label, v, s, accent }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', borderBottom: '1px solid var(--line)', paddingBottom: 10 }}>
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-muted)', letterSpacing: '0.04em' }}>{label}</span>
      <span style={{ textAlign: 'right' }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 15, color: accent ? 'var(--brand)' : 'var(--fg)' }}>{v}</span>
        <span style={{ fontFamily: 'var(--font-accent)', fontStyle: 'italic', fontSize: 12, color: 'var(--fg-faint)', marginLeft: 8 }}>{s}</span>
      </span>
    </div>);

}

function Footer() {
  const t = window.useT();
  return (
    <div style={{ marginTop: 8, paddingTop: 28, borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-faint)', letterSpacing: '0.06em' }}>{t('footer')}</span>
    </div>);

}

Object.assign(window, { ApartmentTabs, ApartmentPane, BuildingName, TopBar, Greeting, DatesStrip, LayoutEditorial, LayoutDashboard, LayoutBento, Footer });