const D = window.K7DATA;
const { MetaLabel, SectionHeader, Button, PhotoFrame, RoomCard, PriceBlock, EventCard, Wayfinding, BookingForm, Quote, Tag, NeedsData, SpecList } = window.K7DesignSystem_46f20a;

const px = (k) => (k ? D.photo[k] : '');

const K7_MAX = 'var(--content-max)';

function Screen({ id, index, label, children, style, wide }) {
  return (
    <section id={id} data-screen-label={index} style={Object.assign({ borderBottom: '1px solid var(--border-hairline)', padding: 'var(--space-12) var(--space-10)' }, style)}>
      <div style={{ maxWidth: wide ? 'var(--content-wide)' : K7_MAX, marginInline: 'auto' }}>
      {(index || label) && (
        <div style={{ display: 'flex', gap: 'var(--space-6)', alignItems: 'baseline', marginBottom: 'var(--space-6)' }}>
          <MetaLabel tone="accent">{index}</MetaLabel>
          <MetaLabel wide>{label}</MetaLabel>
        </div>
      )}
      {children}
      </div>
    </section>
  );
}

/* 01 — УЛИЦА */
function Street({ go, mobile }) {
  return (
    <section data-screen-label="01" style={{ position: 'relative', minHeight: mobile ? 520 : 600, display: 'grid' }}>
      <img src={px('yard')} alt="Двор на Большой Ордынке, стеклянный тамбур и лампочные буквы" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', filter: 'var(--photo-filter-dim)' }} />
      <div style={{ position: 'absolute', inset: 0, background: 'var(--scrim-bottom)' }} />
      <div style={{ position: 'relative', alignSelf: 'end', width: '100%', boxSizing: 'border-box', maxWidth: mobile ? undefined : 'calc(var(--content-max) + 2 * var(--space-10))', marginInline: 'auto', padding: mobile ? 'var(--space-8) var(--space-4)' : 'var(--space-12) var(--space-10)', display: 'grid', gap: 'var(--space-6)' }}>
        <div style={{ display: 'flex', gap: 'var(--space-6)', flexWrap: 'wrap' }}>
          <MetaLabel tone="primary" wide>Большая Ордынка, 68</MetaLabel>
          <MetaLabel tone="accent" wide>вход со двора</MetaLabel>
        </div>
        <h1 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-black)', fontSize: mobile ? 52 : 108, lineHeight: .9, letterSpacing: '-0.04em', textTransform: 'uppercase', color: 'var(--k7-sand-50)', whiteSpace: 'nowrap' }}>Квартира 7</h1>
        <div style={{ display: 'flex', gap: 'var(--space-4)', alignItems: 'center', flexWrap: 'wrap' }}>
          <Button variant="primary" size="lg" onClick={() => go('booking')}>Зайти в Квартиру</Button>
          <Button variant="inverse" size="lg" onClick={() => go('rooms')}>Посмотреть комнаты</Button>
        </div>
      </div>
    </section>
  );
}

/* 02 — СПУСК */
function Descent({ mobile }) {
  return (
    <Screen index="02" label="Спуск" style={{ background: 'var(--surface-sunken)' }}>
      <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : '0.8fr 1.2fr', gap: mobile ? 'var(--space-8)' : 'var(--space-12)', alignItems: 'center' }}>
        <PhotoFrame src={px('stairs')} alt="Каменная лестница вниз, подсветка ступеней" ratio={mobile ? '4 / 3' : '3 / 2'} caption="Спуск / −1 этаж" />
        <div style={{ display: 'grid', gap: 'var(--space-6)' }}>
          <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-black)', fontSize: mobile ? 36 : 64, lineHeight: .98, letterSpacing: '-0.035em', textTransform: 'uppercase', color: 'var(--text-primary)' }}>Антикафе-кальянная на Ордынке</h2>
          <p style={{ margin: 0, fontSize: mobile ? 21 : 28, lineHeight: 1.35, color: 'var(--text-primary)', maxWidth: '26ch' }}>Здесь можно просто быть.</p>
          <p style={{ margin: 0, fontSize: 19, lineHeight: 1.55, color: 'var(--text-secondary)', maxWidth: '42ch' }}>Это подвал. Так и задумано: город остаётся сверху, внизу темнее, тише и теплее.</p>
        </div>
      </div>
    </Screen>
  );
}

/* 03 — ТЫ УЖЕ ДОМА */
function AtHome({ mobile }) {
  return (
    <Screen index="03" label="Ты уже дома">
      <div style={{ display: 'grid', gap: 'var(--space-6)' }}>
        <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-black)', fontSize: mobile ? 38 : 76, lineHeight: .96, letterSpacing: '-0.035em', textTransform: 'uppercase', color: 'var(--text-primary)', maxWidth: '20ch' }}>Мы не навязываемся, но всегда рядом</h2>
        <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : '0.85fr 1.15fr', gap: 'var(--space-6)', alignItems: 'start' }}>
          <PhotoFrame src={px('evening')} alt="Компания за длинным столом вечером: разговор, кубки на полке, тёплый свет" ratio="1 / 1" caption="Люди за столом / вечер" />
          <div style={{ display: 'grid', gap: 'var(--space-5)', alignContent: 'start' }}>
            <p style={{ margin: 0, fontSize: 19, lineHeight: 1.55, color: 'var(--text-secondary)' }}>Никто не стоит над столом и не спрашивает каждые пять минут, всё ли хорошо. Но если нужно — мы здесь.</p>
            <p style={{ margin: 0, fontSize: 19, lineHeight: 1.55, color: 'var(--text-secondary)' }}>Мы больше, чем антикафе, и точно не стандартная кальянная. Здесь не надо заказывать, чтобы остаться, и не надо уходить, когда захотелось большего.</p>
            <p style={{ margin: 0, fontSize: 19, lineHeight: 1.55, color: 'var(--text-secondary)' }}>Час в квартире — это чай, кофе, настолки и место, где можно просто сидеть. Кальян, свой зал, проектор, караоке — когда решите, что вечер того стоит.</p>
            <p style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-bold)', fontSize: mobile ? 22 : 28, lineHeight: 1.2, letterSpacing: '-0.02em', color: 'var(--text-primary)' }}>Уютно как дома. Возможности как у заведения.</p>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr 1fr' : 'repeat(3, 1fr)', gap: 'var(--space-3)' }}>
          <PhotoFrame src={px('wide')} alt="Большой зал: кирпич, лампы, длинные столы" ratio="4 / 3" />
          <PhotoFrame src="./assets/photo/04-hall-sofas-new.jpg" alt="Зал с диванами" ratio="4 / 3" />
          <img src={px('table')} alt="Стол на восемь человек" style={{ width: '100%', aspectRatio: '4 / 3', objectFit: 'cover', objectPosition: 'center', display: 'block', filter: 'var(--photo-filter)' }} />
        </div>
      </div>
    </Screen>
  );
}

/* 04 — ЧТО ЗДЕСЬ ДЕЛАТЬ */
function Doing({ mobile }) {
  return (
    <Screen wide index="04" label="Что здесь делать" style={{ background: 'var(--surface-petrol)' }}>
      <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1.15fr 0.85fr', gap: mobile ? 'var(--space-8)' : 'var(--space-12)', alignItems: 'start' }}>
        <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'grid', alignContent: 'space-between', gap: 'var(--space-3)', height: '100%' }}>
          {D.doing.map((d, i) => (
            <li key={i} style={{ display: 'grid', columnGap: 'var(--space-6)', rowGap: 'var(--space-1)', gridTemplateColumns: mobile ? '1fr' : 'minmax(min-content,1fr) auto', alignItems: 'baseline', paddingBottom: 'var(--space-3)', borderBottom: '1px solid var(--border-hairline)' }}>
              <span style={{ fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-bold)', fontSize: mobile ? 22 : 30, lineHeight: 1.12, letterSpacing: '-0.02em', color: 'var(--text-primary)' }}>{d.label}</span>
              <MetaLabel size="lg" tone="primary">{d.note}</MetaLabel>
            </li>
          ))}
        </ul>
        <div style={{ display: 'grid', gap: 'var(--space-4)', alignContent: 'start' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
            <PhotoFrame src={px('bar')} alt="Барная стойка из массива дерева, табак на полках" ratio="4 / 3" caption="Стойка" />
            <PhotoFrame src={px('trophies')} alt="Комната с кубками и дипломами, длинный стол" ratio="4 / 3" caption="Кубки и дипломы" />
          </div>
          <p style={{ margin: 0, fontSize: 17, lineHeight: 1.55, color: 'var(--text-secondary)' }}>Кальян здесь — одна из обычных вещей, доступных дома. Не главный герой сайта.</p>
          <div style={{ marginTop: 'var(--space-4)', border: '1px solid var(--border-hairline)', padding: mobile ? 'var(--space-6)' : 'var(--space-8)', display: 'grid', gap: 'var(--space-5)', alignContent: 'center', justifyItems: 'start', minHeight: mobile ? undefined : 260 }}>
            <MetaLabel wide tone="accent">Кстати, наш слоган:</MetaLabel>
            <p style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-black)', fontSize: mobile ? 40 : 64, lineHeight: .95, letterSpacing: '-0.035em', textTransform: 'uppercase', color: 'var(--text-primary)' }}>В К7<br />к 7-и</p>
            <div style={{ display: 'grid', gap: 'var(--space-2)' }}>
              <MetaLabel size="lg" tone="primary">{window.K7FMT.hours ? window.K7FMT.hours(window.K7L('hours')) : '18:00 — ДО ПОСЛЕДНЕГО ГОСТЯ'}</MetaLabel>
              <MetaLabel wide>Большая Ордынка, 68 · вход со двора</MetaLabel>
            </div>
          </div>
        </div>
      </div>
    </Screen>
  );
}

/* 05 — КОМНАТЫ */
function Rooms({ go, mobile, full }) {
  const rail = React.useRef(null);
  const [at, setAt] = React.useState(0);
  const onScroll = () => {
    const el = rail.current;
    if (!el) return;
    const step = el.scrollWidth / D.rooms.length;
    setAt(Math.min(D.rooms.length - 1, Math.round(el.scrollLeft / step)));
  };
  const nudge = (k) => {
    const el = rail.current;
    if (!el) return;
    el.scrollTo({ left: (el.scrollWidth / D.rooms.length) * k, behavior: 'smooth' });
  };
  return (
    <Screen index={full ? undefined : '05'} label={full ? undefined : 'Комнаты'}>
      <SectionHeader eyebrow={full ? undefined : 'Четыре пространства'} title="Выбери, где сидеть"
        note="Мафию играем в лофт-зале. «Underground» на фотографиях — внутреннее имя зала с проектором, а не отдельная комната."
        action={!full && <Button variant="ghost" onClick={() => go('rooms')}>Все комнаты</Button>} style={{ marginBottom: 'var(--space-8)' }} />
      <div ref={rail} onScroll={mobile ? onScroll : undefined} style={mobile
        ? { display: 'flex', gap: 'var(--space-4)', overflowX: 'auto', scrollSnapType: 'x mandatory', margin: '0 calc(-1 * var(--space-4))', padding: '0 var(--space-4)', scrollbarWidth: 'none' }
        : { display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(280px,1fr))', gap: 'var(--space-5)' }}>
        {D.rooms.map(r => (
          <RoomCard key={r.index} {...r} photo={r.photo !== undefined ? r.photo : px(r.photoKey)}
            photos={r.galleryKey ? D.gallery[r.galleryKey] : undefined}
            layout={mobile ? 'tall' : 'stack'} onBook={() => go('booking')}
            style={mobile ? { flex: '0 0 86%', scrollSnapAlign: 'center' } : undefined} />
        ))}
      </div>
      {mobile && (
        <div style={{ marginTop: 'var(--space-5)', display: 'grid', gap: 'var(--space-3)' }}>
          <div style={{ display: 'flex', gap: 'var(--space-3)', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
              {D.rooms.map((r, k) => (
                <button key={r.id} type="button" aria-label={r.name} aria-current={k === at} onClick={() => nudge(k)}
                  style={{ appearance: 'none', cursor: 'pointer', padding: 0, border: 0, height: 3, width: k === at ? 26 : 12, background: k === at ? 'var(--k7-mustard-500)' : 'var(--k7-sand-50)', opacity: k === at ? 1 : .4, transition: 'width var(--transition-default), opacity var(--transition-default)' }} />
              ))}
            </div>
            <MetaLabel size="sm">{String(at + 1).padStart(2, '0') + ' / ' + String(D.rooms.length).padStart(2, '0')}</MetaLabel>
          </div>
          <MetaLabel size="sm" wide>Листай в сторону — четыре комнаты. Фото меняется тапом</MetaLabel>
        </div>
      )}
      {window.K7L('occupancy').publish && (
        <div style={{ marginTop: 'var(--space-8)', display: 'flex', gap: 'var(--space-4)', alignItems: 'baseline' }}>
          <MetaLabel size="sm" wide>Сегодня</MetaLabel>
          <MetaLabel tone="accent" size="lg">{'СВОБОДНО ' + window.K7L('occupancy').free + ' ИЗ ' + window.K7L('occupancy').total}</MetaLabel>
        </div>
      )}
    </Screen>
  );
}

/* 06 — СКОЛЬКО ЭТО СТОИТ */
function Prices({ mobile, full, go }) {
  const P = D.prices;
  return (
    <Screen index={full ? undefined : '06'} label={full ? undefined : 'Сколько это стоит'}>
      <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr', gap: mobile ? 'var(--space-10)' : 'var(--space-12)', alignItems: 'start' }}>
        <PriceBlock index="01 / АНТИКАФЕ" title="Время в квартире" rows={P.anticafe}
          note="Чай, кофе, печенье, настолки и само пространство — внутри тарифа. Платишь за время, а не за чек."
          footer={<p style={{ margin: 0, fontSize: 17, lineHeight: 1.55, color: 'var(--text-secondary)', maxWidth: '46ch' }}>А если вдруг вы забежали к нам только покурить кальян — вы можете заплатить за него 2000 и посидеть пообщаться просто так!</p>} />
        <PriceBlock index="02 / КАЛЬЯН" title="Кальян" rows={P.hookah}
          note="Если не понравился — первые 15 минут перезабиваем бесплатно." />
        <PriceBlock index="03 / КОМНАТЫ" title="Комнаты" rows={P.rooms}
          note="Пятница после 17:00 считается выходным днём." />
        <PriceBlock index="04 / КАРАОКЕ" title="Караоке" rows={P.karaoke} />
        <PriceBlock index="05 / ДОПОЛНИТЕЛЬНО" title="Дополнительно" rows={P.extras} />
        <PriceBlock tone="petrol" index="06 / УСЛОВИЯ" title="Пробковый сбор" rows={P.corkage}
          note="Считаем за бутылку. Оставишь отзыв о нас на Яндекс.Картах — сбор снимем, просто скажи об этом на входе."
          footer={<Button variant="ghost" size="sm" href={D.links.maps} target="_blank" rel="noopener">Оставить отзыв</Button>} />
        {full && <PriceBlock tone="blue" index="07 / ПОСТОЯННЫМ" title="Депозит" rows={P.deposit}
          note="Продукт для тех, кто ходит часто. Не оффер главной страницы." />}
      </div>
      {full && (
        <div style={{ marginTop: 'var(--space-10)', display: 'grid', gap: 'var(--space-4)', maxWidth: '58ch', marginInline: mobile ? 0 : 'auto', width: '100%' }}>
          <MetaLabel wide>Правила дома</MetaLabel>
          <div style={{ display: 'grid', gap: 'var(--space-3)' }}>
            {window.K7L('rules').map(r => (
              <div key={r.id} style={{ display: 'flex', gap: 'var(--space-4)', alignItems: 'baseline', justifyContent: 'space-between', paddingBottom: 'var(--space-3)', borderBottom: '1px solid var(--border-hairline)' }}>
                <MetaLabel size="sm">{r.label}</MetaLabel>
                {r.value ? <span style={{ fontSize: 17, color: 'var(--text-secondary)', textAlign: 'right' }}>{r.value}</span> : <NeedsData>уточняется</NeedsData>}
              </div>
            ))}
          </div>
        </div>
      )}
      {!full && <div style={{ marginTop: 'var(--space-8)' }}><Button variant="secondary" onClick={() => go('prices')}>Все цены и условия</Button></div>}
    </Screen>
  );
}

/* 07 — ЗДЕСЬ ЧТО-ТО ПРОИСХОДИТ */
function Events({ mobile, full, go }) {
  return (
    <Screen index={full ? undefined : '07'} label={full ? undefined : 'Здесь что-то происходит'}>
      <SectionHeader eyebrow="Ближайшие события" title="Квартира живёт, а не сдаётся по часам"
        note={full ? undefined : 'По средам обычно играем. По выходным собираются настольщики.'}
        action={!full && <Button variant="ghost" onClick={() => go('events')}>Все события</Button>} style={{ marginBottom: 'var(--space-8)' }} />
      <div style={{ display: 'grid', gap: 'var(--space-3)' }}>
        {D.events.map(e => <EventCard key={e.index} {...e} date={e.id === 'mafia' ? (window.K7FMT.dates(window.K7L('mafia').dates) || e.date) : e.date} layout={mobile ? 'stack' : 'row'} photo={mobile ? '' : undefined} onClick={() => go('events')} />)}
      </div>
      <div style={{ marginTop: 'var(--space-6)', display: 'flex', gap: 'var(--space-4)', alignItems: 'baseline', flexWrap: 'wrap' }}>
        <MetaLabel size="sm" wide>Мафия</MetaLabel>
        {window.K7FMT.dates(window.K7L('mafia').dates)
          ? <MetaLabel tone="accent" size="lg">{window.K7FMT.dates(window.K7L('mafia').dates)}</MetaLabel>
          : <MetaLabel tone="muted" size="lg">Дни уточняются</MetaLabel>}
        {window.K7L('mafia').note && <span style={{ fontSize: 17, color: 'var(--text-secondary)' }}>{window.K7L('mafia').note}</span>}
      </div>
      {full && (
        <div style={{ marginTop: 'var(--space-12)', display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr', gap: 'var(--space-8)', alignItems: 'center' }}>
          <PhotoFrame src={px('trophies')} alt="Полка с кубками и стена дипломов" ratio="4 / 3" caption="Мафия / архив побед" />
          <div style={{ display: 'grid', gap: 'var(--space-5)' }}>
            <h3 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-black)', fontSize: 34, lineHeight: 1.02, letterSpacing: '-0.025em', textTransform: 'uppercase' }}>Мафия</h3>
            <p style={{ margin: 0, fontSize: 19, lineHeight: 1.55, color: 'var(--text-secondary)', maxWidth: '44ch' }}>Здесь свои ведущие, свои столы и люди, которые знают друг друга по игре годами. Прийти одному нормально — возьмут в круг.</p>
            <div><NeedsData>регулярные дни и часы</NeedsData></div>
          </div>
        </div>
      )}
    </Screen>
  );
}

/* 08 — ПРОПИСАТЬСЯ НА ВЕЧЕР */
function Book({ mobile, full }) {
  return (
    <Screen index="08" label="Прописаться на вечер">
      <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr', gap: mobile ? 'var(--space-8)' : 'var(--space-12)', alignItems: 'start' }}>
        <BookingForm compact={mobile} note="Напишем в ответ и придержим стол. Без предоплаты бронь не считается принятой — это стоимость первого часа." />
        <div style={{ display: 'grid', gap: 'var(--space-8)' }}>
          <SpecList items={[
            { label: 'Адрес', value: 'БОЛЬШАЯ ОРДЫНКА, 68', href: window.K7L('links').maps },
            { label: 'Вход', value: 'СО ДВОРА, ВНИЗ' },
            { label: 'Телефон', value: window.K7L('links').phone },
            { label: 'Предоплата брони', value: 'ПЕРВЫЙ ЧАС' },
          ]} />
          <div style={{ marginTop: 'calc(-1 * var(--space-6))', display: 'flex', justifyContent: 'flex-end' }}><MetaLabel size="sm">(после подтверждения брони)</MetaLabel></div>
          <div style={mobile
            ? { display: 'grid', gap: 'var(--space-3)', justifyItems: 'start' }
            : { display: 'flex', gap: 'var(--space-4)', alignItems: 'center', flexWrap: 'nowrap' }}>
            <a href={'tel:' + window.K7L('links').phone.replace(/[^+\d]/g, '')} style={{ fontFamily: 'var(--font-mono)', fontSize: 'var(--size-mono)', fontWeight: 'var(--fw-medium)', letterSpacing: 'var(--ls-mono)', color: 'var(--text-accent)', whiteSpace: 'nowrap' }}>{window.K7L('links').phone}</a>
            <a href={window.K7L('links').telegram} style={{ fontFamily: 'var(--font-mono)', fontSize: 'var(--size-mono)', fontWeight: 'var(--fw-medium)', letterSpacing: 'var(--ls-mono)', textTransform: 'uppercase', color: 'var(--text-accent)', borderLeft: mobile ? 0 : '1px solid var(--border-hairline)', paddingLeft: mobile ? 0 : 'var(--space-4)', whiteSpace: 'nowrap' }}>Telegram</a>
            <a href={window.K7L('links').booking} style={{ fontFamily: 'var(--font-mono)', fontSize: 'var(--size-mono)', fontWeight: 'var(--fw-medium)', letterSpacing: 'var(--ls-mono)', textTransform: 'uppercase', color: 'var(--text-accent)', borderLeft: mobile ? 0 : '1px solid var(--border-hairline)', paddingLeft: mobile ? 0 : 'var(--space-4)', whiteSpace: 'nowrap' }}>Бронь в телеграме</a>
          </div>
          {!mobile && <Wayfinding title="Как нас найти" note="От Ордынки — в арку, через двор, дверь и вниз по лестнице."
            steps={D.wayfinding.map(s => ({ ...s, photo: px(s.photoKey) }))} />}
        </div>
      </div>
      {mobile && <div style={{ marginTop: 'var(--space-10)' }}><Wayfinding title="Как нас найти" steps={D.wayfinding.map(s => ({ ...s, photo: px(s.photoKey) }))} /></div>}
    </Screen>
  );
}

function Home({ go, mobile }) {
  return (
    <>
      <Street go={go} mobile={mobile} />
      <Descent mobile={mobile} />
      <AtHome mobile={mobile} />
      <Doing mobile={mobile} />
      <Rooms go={go} mobile={mobile} />
      <Prices go={go} mobile={mobile} />
      <Events go={go} mobile={mobile} />
      <Book mobile={mobile} />
    </>
  );
}

Object.assign(window, { K7Home: Home, K7Screen: Screen, K7Rooms: Rooms, K7Prices: Prices, K7Events: Events, K7Book: Book, k7px: px });
