/* global React */
// Variant 1 — PREMIUM LUXURY (refined)
const { useState: useState1, useEffect: useEffect1 } = React;

// Three rotating hero messages (as the user wrote them)
const HERO_MESSAGES = [
  {
    // Бильярд — искусство, спорт, страсть
    head1: 'Бильярд',
    tail1: ' — как искусство,',
    mid:   'как спорт',
    tail:  'как страсть.',
    highlight: 'Бильярд',
    chips: ['Русский · 10 столов', 'Американский пул · 3 стола'],
  },
  {
    head1: 'Настольный теннис',
    tail1: ' — игра скорости,',
    mid:   'реакции',
    tail:  'и сложной техники.',
    highlight: 'Настольный теннис',
    chips: ['2 качественных стола', 'Прокат инвентаря'],
  },
  {
    head1: 'Дартс',
    tail1: ' — игра нервов,',
    mid:   'меткого глаза',
    tail:  'и твёрдой руки.',
    highlight: 'Дартс',
    chips: ['Профессиональная мишень', 'Подходит для турниров'],
  },
];

function HeroHeadline() {
  const [idx, setIdx] = useState1(0);
  useEffect1(() => {
    const t = setTimeout(() => setIdx(i => (i + 1) % HERO_MESSAGES.length), 6200);
    return () => clearTimeout(t);
  }, [idx]);

  const m = HERO_MESSAGES[idx];
  return (
    <h1 className="v1-h1" key={idx}>
      <span className="v1-line v1-line-1">
        <em className="v1-word">{m.head1}</em>{m.tail1}
      </span>
      <span className="v1-line v1-line-2">
        {m.mid} <span className="v1-amp">&amp;</span>
      </span>
      <span className="v1-line v1-line-3">{m.tail}</span>
    </h1>
  );
}

function HeroChips({ idx }) {
  const m = HERO_MESSAGES[idx];
  return (
    <div className="v1-crown" key={idx}>
      <OpenStatusChip />
      {m.chips.map(c => <span key={c} className="chip" style={{ opacity: 0.85 }}>{c}</span>)}
    </div>
  );
}

// "Сейчас в клубе" — live status block.
// Fetches /api/tables-status (Vercel Serverless proxy → Railway-app).
// Falls back to demo data when the upstream isn't ready/available.
const NOW_FALLBACK = [
  { cat: 'Русский бильярд',    free: 4, total: 10 },
  { cat: 'Американский пул',   free: 2, total: 3  },
  { cat: 'Настольный теннис',  free: 1, total: 2  },
  { cat: 'Дартс',              free: 1, total: 1  },
  { cat: 'VIP-комната',        free: 0, total: 1  },
];

function toneFor(free, total) {
  if (!total || free <= 0) return 'r';
  const ratio = free / total;
  if (ratio < 0.34) return 'y';
  return 'g';
}

// Расписание клуба: Пн-Чт 12:00-00:00, Пт-Вс 10:00-02:00 (ночная смена пересекает полночь)
function getScheduleStatus(now) {
  const pad = n => String(n).padStart(2, '0');
  const fmt = mins => `${pad(Math.floor(mins / 60) % 24)}:${pad(mins % 60)}`;
  // openMin → closeMin (в минутах от 00:00 текущего дня; closeMin > 1440 → закрытие на следующий день)
  const sched = {
    1: [12 * 60, 24 * 60], 2: [12 * 60, 24 * 60], 3: [12 * 60, 24 * 60], 4: [12 * 60, 24 * 60],
    5: [10 * 60, 26 * 60], 6: [10 * 60, 26 * 60], 0: [10 * 60, 26 * 60],
  };
  const day = now.getDay();
  const totalMin = now.getHours() * 60 + now.getMinutes();
  const [todayOpen, todayClose] = sched[day];
  if (totalMin >= todayOpen && totalMin < todayClose) {
    return { open: true, closesAt: fmt(todayClose) };
  }
  const prevDay = (day + 6) % 7;
  const [, prevClose] = sched[prevDay];
  if (prevClose > 24 * 60) {
    const carry = prevClose - 24 * 60;
    if (totalMin < carry) return { open: true, closesAt: fmt(carry) };
  }
  if (totalMin < todayOpen) return { open: false, opensAt: fmt(todayOpen) };
  const nextDay = (day + 1) % 7;
  return { open: false, opensAt: fmt(sched[nextDay][0]) };
}

// Hero "open until / opens at" chip — driven by the same schedule as the live status block
function OpenStatusChip() {
  const [now, setNow] = useState1(new Date());
  useEffect1(() => {
    const t = setInterval(() => setNow(new Date()), 30_000);
    return () => clearInterval(t);
  }, []);
  const status = getScheduleStatus(now);
  const text = status.open
    ? `Открыт до ${status.closesAt}`
    : `Откроется в ${status.opensAt}`;
  return <span className="chip"><span className="dot"></span>{text}</span>;
}

function NowAtClub() {
  const [now, setNow] = useState1(new Date());
  const [tablesData, setTablesData] = useState1(null);
  const [isLive, setIsLive] = useState1(false);

  useEffect1(() => {
    const t = setInterval(() => setNow(new Date()), 30_000);
    return () => clearInterval(t);
  }, []);

  useEffect1(() => {
    let cancelled = false;
    async function load() {
      try {
        const r = await fetch('/api/tables-status', { cache: 'no-store' });
        if (!r.ok) throw new Error('http ' + r.status);
        const data = await r.json();
        if (cancelled) return;
        if (data && data.ok && Array.isArray(data.tables) && data.tables.length) {
          setTablesData(data.tables);
          setIsLive(true);
        } else {
          setTablesData(null);
          setIsLive(false);
        }
      } catch {
        if (!cancelled) { setTablesData(null); setIsLive(false); }
      }
    }
    load();
    const id = setInterval(load, 30_000);
    return () => { cancelled = true; clearInterval(id); };
  }, []);

  const status = getScheduleStatus(now);
  const closed = !status.open;

  useEffect1(() => {
    document.body.classList.toggle('club-closed', closed);
    return () => document.body.classList.remove('club-closed');
  }, [closed]);

  const source = (tablesData && tablesData.length) ? tablesData : NOW_FALLBACK;
  const tables = source.map(t => ({ ...t, tone: t.tone || toneFor(t.free, t.total) }));

  const timeStr = now.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
  return (
    <div className={`v1-now glass${closed ? ' is-closed' : ''}`}>
      <div className="v1-now-head">
        <div className="v1-now-live">
          <span className="v1-now-pulse"></span>
          {closed ? 'Сейчас клуб закрыт' : 'Сейчас в клубе'}
        </div>
        <div className="v1-now-time">
          <span className="v1-now-clock">{timeStr}</span>
          <span className="v1-now-open">
            {closed ? `откроется в ${status.opensAt}` : `открыт до ${status.closesAt}`}
          </span>
        </div>
      </div>
      <div className="v1-now-grid">
        {tables.map(t => (
          <div key={t.cat} className={`v1-now-row tone-${t.tone} ${t.free === 0 ? 'is-busy' : ''}`}>
            <div className="v1-now-row-cat">{t.cat}</div>
            <div className="v1-now-row-pill">
              <strong>{t.free}</strong> <span>/ {t.total}</span>
            </div>
            <div className="v1-now-row-dots">
              {Array.from({ length: t.total }).map((_, i) => (
                <span key={i} className={`v1-now-dot ${i < t.free ? 'free' : 'busy'}`}></span>
              ))}
            </div>
          </div>
        ))}
      </div>
      <div className="v1-now-foot">
        <span>{closed
          ? `Откроется в ${status.opensAt} — позвоните для предварительной брони`
          : (isLive ? 'Синхронизация с приложением клуба · 30 сек' : 'Демо-данные · ожидаем подключение к приложению')}</span>
        <a
          href={closed ? undefined : '#contact'}
          onClick={closed ? (e) => e.preventDefault() : undefined}
          className={`v1-now-cta${closed ? ' is-disabled' : ''}`}
          aria-disabled={closed || undefined}
        >Забронировать →</a>
      </div>
    </div>
  );
}

// Sticky contact dock (always visible)
function ContactDock() {
  const F = window.FORTUNA;
  return (
    <aside className="v1-dock">
      <a href={`tel:${F.club.phone.replace(/[^\d+]/g,'')}`} className="v1-dock-row">
        <span className="v1-dock-icn">
          <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.8 19.8 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.12 4.18 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.8a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.28-1.28a2 2 0 0 1 2.11-.45c.9.34 1.84.57 2.8.7A2 2 0 0 1 22 16.92z"/>
          </svg>
        </span>
        <div>
          <div className="v1-dock-lbl">Телефон</div>
          <div className="v1-dock-val">{F.club.phone}</div>
        </div>
      </a>
      <div className="v1-dock-sep"></div>
      <div className="v1-dock-row">
        <span className="v1-dock-icn">
          <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/>
            <circle cx="12" cy="10" r="3"/>
          </svg>
        </span>
        <div>
          <div className="v1-dock-lbl">Адрес</div>
          <div className="v1-dock-val v1-dock-val--sm">Театральная 3/3, с. Быково</div>
        </div>
      </div>
      <a href="#contact" className="v1-dock-cta">Забронировать стол</a>
    </aside>
  );
}

function V1Premium() {
  const F = window.FORTUNA;
  const [idx, setIdx] = useState1(0);
  useEffect1(() => {
    const t = setTimeout(() => setIdx(i => (i + 1) % HERO_MESSAGES.length), 6200);
    return () => clearTimeout(t);
  }, [idx]);

  return (
    <div className="variant v1" data-variant="1">
      <div className="v1-root variant-root">
        <Header />

        {/* HERO — clean, rotating headline */}
        <section className="v1-hero">
          <div className="v1-hero-left">
            <HeroChipsCycle idx={idx} />
            <HeroHeadlineCycle idx={idx} />
            <p className="lead">
              Пятнадцать профессиональных столов, тренеры — мастера спорта, зал, где
              каждая партия становится событием. Добро пожаловать в «Фортуну».
            </p>
            <div className="cta-row">
              <a href="#contact" className="btn btn-primary">Забронировать стол</a>
              <a href="#halls" className="btn btn-ghost">Посмотреть залы</a>
            </div>
          </div>
          <div className="v1-hero-aside">
            <NowAtClub />
          </div>
        </section>

        {/* ABOUT */}
        <section id="about" className="section">
          <div className="v1-about">
            <div>
              <div className="eyebrow" style={{ color: 'var(--fortuna-gold)', marginBottom: 20 }}>— О клубе</div>
              <p className="lede">
                «Фортуна» — <em>пятнадцать столов</em> под одной крышей: бильярд,
                настольный теннис, а ещё дартс. Тренеры — <em>мастера спорта</em>{' '}
                для продвинутых любителей, кто хочет расти, и площадка для школы
                бильярда — для тех, кто только берёт кий в руки.
              </p>
              <p style={{ marginTop: 24, opacity: 0.75, fontSize: 16, lineHeight: 1.6, maxWidth: 520 }}>
                А спорт-бар с большим экраном — для болельщиков: качественные
                трансляции лучших матчей рядом с теми, кто понимает игру.
              </p>
            </div>
            <StatRow />
          </div>
        </section>

        {/* SERVICES */}
        <section id="services" className="section">
          <div className="section-header">
            <h2 className="section-title">Услуги клуба</h2>
            <p className="section-sub">Всё, что нужно для игры и после неё — под одной крышей.</p>
          </div>
          <div className="v1-services">
            {F.services.map((s, i) => (
              <div key={s.id} className="v1-svc-card glass">
                <div>
                  <div className="num">{String(i+1).padStart(2, '0')}</div>
                  <h3 style={{ marginTop: 14 }}>{s.title}</h3>
                  <p>{s.desc}</p>
                </div>
                <a href="#contact" style={{ color: 'var(--fortuna-gold)', textDecoration: 'none', fontSize: 14, fontWeight: 700, letterSpacing: '0.05em' }}>Подробнее →</a>
              </div>
            ))}
          </div>
        </section>

        {/* HALLS */}
        <section id="halls" className="section">
          <div className="section-header">
            <h2 className="section-title">Залы и&nbsp;оборудование</h2>
            <p className="section-sub">Пятнадцать столов, отдельная VIP-комната, всё для тренировок и отличного вечера за игрой.</p>
          </div>
          <div className="v1-halls">
            {F.equipment.map(e => (
              <div key={e.id} className="v1-hall-card">
                {e.logo && <img className="v1-hall-logo" src={e.logo} alt="" aria-hidden="true" />}
                <div className="count">{e.count}</div>
                <div>
                  <h4>{e.label}</h4>
                  <div className="note">{e.note}</div>
                </div>
              </div>
            ))}
          </div>
        </section>

        {/* PRICING */}
        <section id="pricing" className="section">
          <div className="section-header">
            <h2 className="section-title">Тарифы</h2>
            <p className="section-sub">Цены — за час игры за столом. Бронирование по телефону или через телеграм.</p>
          </div>
          <div className="glass panel" style={{ padding: '12px 28px 24px' }}>
            <PricingTable />
          </div>
        </section>

        {/* COACHES */}
        <section id="coaches" className="section coaches">
          <div className="section-header">
            <h2 className="section-title">Тренеры и&nbsp;Школа</h2>
            <p className="section-sub">Профессионалы с титулами всероссийского и международного уровня. Помогут поставить технику, разобрать тактику и вывести вашу игру на новый уровень.</p>
          </div>
          <div className="coaches__inner">
            <div className="coaches__grid">
              {F.coaches.map(c => (
                <article
                  key={c.firstName + c.lastName}
                  className={`coach${c.featured ? ' coach--featured' : ''}`}
                >
                  <div className="coach__photo">
                    <img src={c.photo} alt={`${c.firstName} ${c.lastName}`} loading="lazy" />
                    {c.tags && c.tags.length ? (
                      <div className="coach__tags">
                        {c.tags.map((t, i) => (
                          <span key={i} className="coach__tag">{t}</span>
                        ))}
                      </div>
                    ) : c.tagHtml ? (
                      <span className="coach__tag" dangerouslySetInnerHTML={{ __html: c.tagHtml }} />
                    ) : c.tag ? (
                      <span className="coach__tag">{c.tag}</span>
                    ) : null}
                  </div>
                  <div className="coach__body">
                    <h3 className="coach__name">
                      {c.firstName} <span>{c.lastName}</span>
                    </h3>
                    <ul className="coach__list">
                      {c.achievements.map((a, i) => (
                        <li key={i}>{a}</li>
                      ))}
                    </ul>
                  </div>
                </article>
              ))}
            </div>
          </div>
        </section>

        {/* REVIEWS — MyReviews carousel widget */}
        <section className="section">
          <div className="section-header">
            <h2 className="section-title">Отзывы игроков</h2>
            <p className="section-sub">Живые отзывы — обновляются автоматически.</p>
          </div>
          <MyReviewsWidget />
        </section>

        {/* CONTACT + MAP */}
        <section id="contact" className="section">
          <div className="v1-contact glass">
            <div className="v1-contact-info">
              <div className="eyebrow" style={{ color: 'var(--fortuna-gold)', marginBottom: 16 }}>— Контакты</div>
              <h3>Приходите играть<br/>в «Фортуну».</h3>
              <div className="c-row">
                <div className="lbl">Адрес</div>
                <div className="val">{F.club.address}</div>
              </div>
              <div className="c-row">
                <div className="lbl">Телефон</div>
                <div className="val"><a href={`tel:${F.club.phone.replace(/[^+\d]/g, '')}`}>{F.club.phone}</a></div>
              </div>
              <div className="c-row">
                <div className="lbl">Telegram</div>
                <div className="val">{F.club.tg}</div>
              </div>
              <div className="c-row">
                <div className="lbl">Часы работы</div>
                <div className="val">Пн–Чт 12:00–00:00 · Пт–Вс 10:00–02:00</div>
              </div>
            </div>
            <div className="v1-contact-map">
              <a
                href="https://yandex.com/maps/org/fortuna/57130596652/?utm_medium=mapframe&utm_source=maps"
                className="v1-map-attr"
                style={{ top: 0 }}
              >Фортуна</a>
              <a
                href="https://yandex.com/maps/1/moscow-and-moscow-oblast/category/billiard_hall/184106358/?utm_medium=mapframe&utm_source=maps"
                className="v1-map-attr"
                style={{ top: 14 }}
              >Бильярдный клуб в Москве и Московской области</a>
              <a
                href="https://yandex.com/maps/1/moscow-and-moscow-oblast/category/cafe/184106390/?utm_medium=mapframe&utm_source=maps"
                className="v1-map-attr"
                style={{ top: 28 }}
              >Кафе в Москве и Московской области</a>
              <iframe
                title="Бильярдный клуб Фортуна — Яндекс.Карты"
                src="https://yandex.com/map-widget/v1/?from=mapframe&ll=38.079926%2C55.609353&mode=poi&poi%5Bpoint%5D=38.078500%2C55.609919&poi%5Buri%5D=ymapsbm1%3A%2F%2Forg%3Foid%3D57130596652&z=16"
                loading="lazy"
                allowFullScreen
              />
            </div>
          </div>
        </section>

        <footer className="v1-footer">
          <div>© 2026 Бильярдный клуб «Фортуна» · Жуковский</div>
          <div>Сделано с любовью к русскому бильярду</div>
        </footer>

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

// Cycled versions (re-animate on idx change)
function HeroChipsCycle({ idx }) {
  const m = HERO_MESSAGES[idx];
  return (
    <div className="v1-crown" key={idx}>
      <OpenStatusChip />
      {m.chips.map((c, i) => <span key={c} className="chip chip-cycle" style={{ opacity: 0.85, animationDelay: `${0.12 + i*0.06}s` }}>{c}</span>)}
    </div>
  );
}

function HeroHeadlineCycle({ idx }) {
  const m = HERO_MESSAGES[idx];
  return (
    <div className="v1-h1-stage">
      <h1 className="v1-h1" key={idx}>
        <span className="v1-line" style={{ animationDelay: '0.02s' }}>
          <em className="v1-word">{m.head1}</em>{m.tail1}
        </span>
        <span className="v1-line" style={{ animationDelay: '0.14s' }}>
          {m.mid} <span className="v1-amp">&amp;</span>
        </span>
        <span className="v1-line" style={{ animationDelay: '0.26s' }}>{m.tail}</span>
      </h1>
    </div>
  );
}

window.V1Premium = V1Premium;

// MyReviews widget — loads blockWidget.js once and inits against an in-page iframe
// with id `myReviews__block-widget`. The widget script sets that iframe's src to
// myreviews.dev, so review content lives in its own cross-origin frame.
function MyReviewsWidget() {
  useEffect1(() => {
    let cancelled = false;

    function tryInit() {
      if (cancelled) return false;
      const W = window.myReviews && window.myReviews.BlockWidget;
      if (!W) return false;
      try {
        new W({
          uuid: '844bc8b9-c678-437b-a72d-028625764167',
          name: 'g5978809',
          additionalFrame: 'none',
          lang: 'ru',
          widgetId: '1',
        }).init();
      } catch (e) { console.warn('[myreviews] init failed', e); }
      return true;
    }

    if (tryInit()) return () => { cancelled = true; };

    let s = document.querySelector('script[data-myreviews]');
    const onReady = () => { tryInit(); };
    if (!s) {
      s = document.createElement('script');
      s.src = 'https://myreviews.dev/widget/dist/blockWidget.js';
      s.async = true;
      s.dataset.myreviews = '1';
      s.addEventListener('load', onReady);
      s.addEventListener('error', () => console.warn('[myreviews] script failed to load'));
      document.head.appendChild(s);
    } else {
      s.addEventListener('load', onReady);
      // If script already loaded but global wasn't ready earlier, poll a few times.
      let tries = 0;
      const t = setInterval(() => {
        if (cancelled || tryInit() || ++tries > 40) clearInterval(t);
      }, 150);
    }

    return () => { cancelled = true; if (s) s.removeEventListener('load', onReady); };
  }, []);

  return (
    <div className="v1-myreviews-wrap">
      <iframe
        id="myReviews__block-widget"
        title="Виджет с отзывами Карусель от MyReviews"
        className="v1-myreviews-frame"
      />
    </div>
  );
}
window.MyReviewsWidget = MyReviewsWidget;
