const D = window.K7DATA;
const { NavBar, MobileNav, StickyBookingBar, Footer, MetaLabel, Button } = window.K7DesignSystem_46f20a;

/* Собирается на каждый рендер: значения приходят из K7LIVE после загрузки. */
function buildFooter() {
  const links = window.K7L('links');
  const hours = window.K7L('hours');
  return [
    { title: 'Адрес', items: [{ label: 'Москва, Большая Ордынка, 68', href: links.maps }, { label: 'Вход со двора' }, { label: '−1 этаж' }] },
    { title: 'Часы', items: [{ label: hours.regular }, { label: hours.tail }].concat((hours.exceptions || []).map(e => ({ label: e.text }))) },
    { title: 'Связь', items: [{ label: links.phone, href: 'tel:' + links.phone.replace(/[^+\d]/g, '') }, { label: 'Telegram', href: links.telegram }, { label: 'Забронировать в телеграме', href: links.booking }].concat(links.vk ? [{ label: 'ВК — Подпишись!', href: links.vk }] : []).concat([{ label: 'Отзыв на Яндекс.Картах', href: links.maps }]) },
    { title: 'Разделы', items: [{ label: 'Комнаты', href: '#rooms' }, { label: 'События', href: '#events' }, { label: 'Цены', href: '#prices' }, { label: 'Бронь', href: '#booking' }] },
  ];
}

/* Сообщение от нас: тонкая полоса над шапкой, гаснет сама после until. */
function MessageStrip() {
  const message = window.K7L('message');
  if (!window.K7FMT.live(message)) return null;
  return (
    <div style={{ display: 'flex', gap: 'var(--space-4)', alignItems: 'baseline', padding: 'var(--space-3) var(--space-10)', background: 'var(--k7-mustard-500)', color: 'var(--k7-ink-900)' }}>
      <MetaLabel size="sm" wide>От нас</MetaLabel>
      <span style={{ fontSize: 15, lineHeight: 1.5 }}>{message.text}</span>
    </div>
  );
}

/* Мобильная вёрстка включается по ширине экрана: макет рисовался под 390px. */
const MOBILE_QUERY = '(max-width: 767px)';
function useIsMobile() {
  const [mobile, setMobile] = React.useState(() => window.matchMedia(MOBILE_QUERY).matches);
  React.useEffect(() => {
    const mq = window.matchMedia(MOBILE_QUERY);
    const onChange = (e) => setMobile(e.matches);
    setMobile(mq.matches);
    mq.addEventListener('change', onChange);
    return () => mq.removeEventListener('change', onChange);
  }, []);
  return mobile;
}

function SiteApp() {
  const [page, setPage] = React.useState('home');
  const mobile = useIsMobile();
  const [, live] = React.useReducer(x => x + 1, 0);
  React.useEffect(() => {
    document.addEventListener('k7:content', live);
    return () => document.removeEventListener('k7:content', live);
  }, []);
  const status = window.K7L('status');
  const go = (id) => { setPage(id); window.scrollTo({ top: 0 }); };
  const body = page === 'rooms' ? <window.K7RoomsPage go={go} mobile={mobile} />
    : page === 'events' ? <window.K7EventsPage go={go} mobile={mobile} />
    : page === 'prices' ? <window.K7PricesPage go={go} mobile={mobile} />
    : page === 'booking' ? <window.K7BookingPage mobile={mobile} />
    : <window.K7Home go={go} mobile={mobile} />;

  const site = (
    <div style={{ background: 'var(--surface-page)', color: 'var(--text-primary)', fontFamily: 'var(--font-body)', minHeight: '100%' }}>
      <MessageStrip />
      {mobile
        ? <MobileNav items={D.nav} active={page} onNavigate={go} status={{ state: status.state, label: window.K7FMT.statusLabel(status) }} />
        : <NavBar items={D.nav} active={page} onNavigate={go} status={{ state: status.state, label: window.K7FMT.statusLabel(status) }}
            action={<Button variant="primary" size="sm" onClick={() => go('booking')}>Занять свой стол</Button>} />}
      {body}
      <Footer columns={buildFooter()} legal="ИП Тертерян Армен Левонович, ИНН: 772154027190" />
      {mobile && <StickyBookingBar onAction={() => go('booking')} />}
    </div>
  );

  return site;
}

ReactDOM.createRoot(document.getElementById('root')).render(<SiteApp />);
