(() => {
  'use strict';
  const $ = (q,root=document) => root.querySelector(q);
  const $$ = (q,root=document) => Array.from(root.querySelectorAll(q));
  const INFO = Object.freeze({
    name: 'Spolujezdci z. s.',
    ico: '30123704',
    address: 'Klokotská 111/3, 390 01 Tábor',
    email: 'info@spolujezdci.eu',
    dataBox: 'dw3ztft'
  });

  const setText = (sel,val) => { const el=$(sel); if(el) el.textContent = val; };
  setText('#legalName', INFO.name);
  setText('#legalAddress', INFO.address);
  setText('#icoValue', INFO.ico);
  setText('#dataBox', INFO.dataBox);
  setText('#year', new Date().getFullYear());
  const email = $('#contactEmail');
  if(email){ email.href = 'mailto:' + INFO.email; email.textContent = INFO.email; }

  // Mezikruží kolem znaku: texty s ikonami jedou dokola (CSS animace otáčí celé SVG).
  // Seznam se mění jen tady; ikony jsou <symbol id="ic-…"> v index.html.
  // Životní cyklus turnaje po směru hodinových ručiček: před turnajem → během → po něm (→ další turnaj).
  const SERVICES = [
    { icon: 'megaphone', text: 'Propagace' },
    { icon: 'register', text: 'Registrace' },
    { icon: 'organizers', text: 'Pořadatelé' },
    { icon: 'screen', text: 'Infotainment' },
    { icon: 'spark', text: 'Aktivity' },
    { icon: 'feedback', text: 'Zpětná vazba' },
  ];
  const heroArt = $('.hero-art'), orbit = $('#heroOrbit'), words = $('#heroWords');
  if(words){
    const NS = 'http://www.w3.org/2000/svg', R = 400, L = 2 * Math.PI * R;   // obvod kružnice #orbitPath (cesta má 2 oběhy)
    words.setAttribute('aria-label', 'Co děláme: ' + SERVICES.map((s) => s.text).join(', '));
    const items = SERVICES.map((s, i) => {
      const text = document.createElementNS(NS, 'text'), path = document.createElementNS(NS, 'textPath');
      const icon = document.createElementNS(NS, 'use');
      path.setAttribute('href', '#orbitPath');
      path.textContent = s.text;
      text.appendChild(path);
      icon.setAttribute('href', '#ic-' + s.icon);
      icon.style.color = i % 2 ? 'var(--red)' : 'var(--blue)';
      words.append(icon, text);
      return { text, path, icon };
    });
    // Písmo co největší (max. 22 px), aby se všechny položky vešly po obvodu s mezerami;
    // ikona 1,7× písmo. Pod 11 px by nebyly čitelné → skryjí se (hero-art--plain).
    const ICON = 1.7, GAP = .45, SPACE = 2.4;   // násobky velikosti písma (mezera s rezervou pro Safari)
    const layoutWords = () => {
      const size = orbit.clientWidth;
      if(!size) return;
      let per = 0;                                   // délka všech položek při písmu 1 jednotka
      items.forEach((it) => {
        it.path.removeAttribute('textLength');       // měřit skutečnou délku, ne vynucenou
        it.text.setAttribute('font-size', '100');
        it.len = it.text.getComputedTextLength() / 100;
        per += it.len + ICON + GAP + SPACE;
      });
      if(!per) return;                               // skryté (nízký displej) – nic neměřit
      const px = size / 1000;                        // px na jednotku viewBoxu
      const fu = Math.min(22 / px, L / per);
      heroArt.classList.toggle('hero-art--plain', fu * px < 11);
      const ic = fu * ICON, gap = fu * GAP;
      const space = (L - items.reduce((sum, it) => sum + (it.len + ICON + GAP) * fu, 0)) / items.length;
      let at = 0;
      items.forEach((it) => {
        it.text.setAttribute('font-size', fu.toFixed(1));
        // délku textu vynutit (Safari měří a kreslí text na kružnici trochu jinak než Chrome)
        it.path.setAttribute('textLength', (it.len * fu).toFixed(1));
        it.path.setAttribute('lengthAdjust', 'spacing');
        it.icon.setAttribute('x', (500 - ic / 2).toFixed(1));
        it.icon.setAttribute('y', (100 - fu * .36 - ic / 2).toFixed(1));   // na výšce středu písma
        it.icon.setAttribute('width', ic.toFixed(1));
        it.icon.setAttribute('height', ic.toFixed(1));
        it.icon.setAttribute('transform', 'rotate(' + ((at + ic / 2) / L * 360).toFixed(2) + ' 500 500)');
        it.path.setAttribute('startOffset', (at + ic + gap).toFixed(1));
        at += ic + gap + it.len * fu + space;
      });
    };
    layoutWords();
    if(document.fonts){   // znovu změřit, až se načte písmo Inter (i když se načte později)
      document.fonts.ready.then(layoutWords);
      if(document.fonts.addEventListener) document.fonts.addEventListener('loadingdone', layoutWords);
    }
    if(window.ResizeObserver) new ResizeObserver(layoutWords).observe(orbit);
  }

  const intro = $('#intro');
  const site = $('#site');
  const meter = $('#introMeter');
  const skipBtn = $('#skipIntro');
  const replayBtn = $('#replayIntro');
  const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
  const skipIntro = new URLSearchParams(location.search).has('skipintro');

  // Choreografie intra (ms od startu) – jediné místo, kde se ladí časování:
  // reflektory se rozsvítí a hledají logo ve tmě → první ho najde (found) → druhý dorazí
  // a stopa se rozšíří přes celé logo (expand → brand) → logo zmizí → vrstva se prolne do stránky.
  const T = { lights: 60, found: 2050, expand: 2350, brand: 2950, dissolve: 3900, reveal: 4150, end: 5150 };
  // Dráhy reflektorů v jednotkách loga (0,0 = střed loga, ±0,5 = jeho okraj); poslední bod = střed.
  // from = poloha reflektoru (podíl šířky a výšky obrazovky), end = kdy dorazí na logo.
  const SPOTS = [
    { from: [0.12, -0.04], end: T.found,
      path: [[-1.3, 1.1], [-0.8, 0.2], [-0.25, 0.6], [0.55, 0.85], [0.95, -0.3], [0.3, -0.75], [0, 0]] },
    { from: [0.88, -0.04], end: T.expand,
      path: [[1.4, -0.9], [0.6, -1], [0.22, -0.28], [-0.7, -0.55], [-1.05, 0.45], [-0.45, 0.75], [0, 0]] },
  ];
  const logo = $('.intro__reveal img');
  const beams = $$('.intro__beam'), pools = $$('.intro__pool');
  const BEAM_W = 200, BEAM_H = 1000, POOL = 100;   // základní rozměry z CSS (.intro__beam, .intro__pool)
  let playing = false, raf = 0, start = 0, timers = [];

  function clearIntroTimers(){ timers.forEach(clearTimeout); timers = []; }
  const at = (ms, fn) => timers.push(setTimeout(fn, ms));

  function endIntro(focus=false){
    playing = false;
    cancelAnimationFrame(raf);
    clearIntroTimers();
    resetLights();
    intro.classList.remove('intro--loading');
    intro.classList.add('intro--done');
    intro.setAttribute('aria-hidden','true');
    site.inert = false;
    skipBtn.tabIndex = -1;
    if(focus) $('[data-open-contact]')?.focus({preventScroll:true});
  }

  const clamp01 = (u) => Math.max(0, Math.min(1, u));
  const easeInOut = (u) => u < .5 ? 2 * u * u : 1 - Math.pow(2 - 2 * u, 2) / 2;
  const easeOut = (u) => 1 - Math.pow(1 - u, 3);
  // plynulá křivka (Catmull-Rom) přes body dráhy, u = 0–1
  function along(pts, u){
    const n = pts.length - 1, f = Math.min(u * n, n - 1e-6), i = Math.floor(f), s = f - i;
    const a = pts[Math.max(i - 1, 0)], b = pts[i], c = pts[i + 1], d = pts[Math.min(i + 2, n)];
    return [0, 1].map((k) => .5 * (2 * b[k] + (c[k] - a[k]) * s + (2 * a[k] - 5 * b[k] + 4 * c[k] - d[k]) * s * s
      + (3 * b[k] - a[k] - 3 * c[k] + d[k]) * s * s * s));
  }
  function setMask(m){ logo.style.webkitMaskImage = m; logo.style.maskImage = m; }

  // Jeden snímek reflektorů v čase t: logo je vidět jen ve světelných stopách (maska), stopy
  // a kužely světla se posouvají jen přes transform. Od T.brand je logo celé, bez masky.
  function lights(t){
    const box = logo.getBoundingClientRect();
    if(!box.width) return;
    const r0 = Math.max(box.width * .2, 44);
    const rFull = Math.hypot(box.width, box.height) / 2 / .55;     // plná část masky (55 %) pokryje celé logo
    const grow = easeOut(clamp01((t - T.expand) / (T.brand - T.expand)));
    const r = r0 + (rFull - r0) * grow;
    const rLight = r * (1 - .38 * grow);       // světelná stopa skončí jen o kus větší než logo
    const masks = [];
    SPOTS.forEach((spot, i) => {
      const [ux, uy] = along(spot.path, easeInOut(clamp01((t - T.lights) / (spot.end - T.lights))));
      // na úzké obrazovce (mobil) zůstane stopa vždy na obrazovce
      const x = Math.max(r0 - box.left, Math.min(innerWidth - r0 - box.left, box.width * (.5 + ux)));
      const y = Math.max(r0 - box.top, Math.min(innerHeight - r0 - box.top, box.height * (.5 + uy)));
      masks.push('radial-gradient(circle ' + r.toFixed(1) + 'px at ' + x.toFixed(1) + 'px ' + y.toFixed(1)
        + 'px,#000 55%,rgba(0,0,0,.4) 78%,transparent)');
      const px = box.left + x, py = box.top + y;
      pools[i].style.transform = 'translate(' + (px - POOL).toFixed(1) + 'px,' + (py - POOL).toFixed(1) + 'px) scale('
        + (rLight / POOL).toFixed(3) + ')';
      const sx = spot.from[0] * innerWidth, sy = spot.from[1] * innerHeight, dx = px - sx, dy = py - sy;
      beams[i].style.transform = 'translate(' + (sx - BEAM_W / 2).toFixed(1) + 'px,' + sy.toFixed(1) + 'px) rotate('
        + Math.atan2(-dx, dy).toFixed(4) + 'rad) scale(' + (1.6 * rLight / BEAM_W).toFixed(3) + ','
        + (Math.hypot(dx, dy) / BEAM_H).toFixed(3) + ')';
    });
    masks.push('linear-gradient(rgba(0,0,0,.04),rgba(0,0,0,.04))');   // obrys loga ve tmě jen tušit
    setMask(t < T.brand ? masks.join(',') : '');
  }
  function resetLights(){ setMask(''); beams.concat(pools).forEach((el) => { el.style.transform = ''; }); }

  function frame(now){
    if(!playing) return;
    const t = now - start;
    meter.style.transform = 'scaleX(' + clamp01(t / T.reveal).toFixed(4) + ')';
    if(t < T.dissolve) lights(t);
    if(t < T.reveal) raf = requestAnimationFrame(frame);
  }

  // Nástup obsahu stránky ve chvíli, kdy se intro začne prolínat.
  function enterSite(){
    site.classList.remove('site--enter');
    void site.offsetWidth;
    site.classList.add('site--enter');
  }

  function beginIntro(){
    if(reduced){ endIntro(); return; }
    cancelAnimationFrame(raf);
    clearIntroTimers();
    intro.className = 'intro';
    intro.removeAttribute('aria-hidden');
    site.inert = true;
    skipBtn.tabIndex = 0;
    meter.style.transform = 'scaleX(0)';
    playing = true;
    start = performance.now();
    lights(0);
    at(T.lights, () => intro.classList.add('intro--lights'));
    at(T.found, () => intro.classList.add('intro--found'));
    at(T.brand, () => { setMask(''); intro.classList.add('intro--brand'); });
    at(T.dissolve, () => intro.classList.add('intro--dissolve'));
    at(T.reveal, () => { intro.classList.add('intro--peek'); enterSite(); });
    at(T.end, () => endIntro());
    raf = requestAnimationFrame(frame);
  }

  // Preloader: intro začne, až je načtené písmo a logo (max. 4 s). Smyčka se ukáže
  // jen při pomalejším načítání (CSS ji zobrazí až po 200 ms), aby neproblikla.
  function whenReady(){
    const imgs = $$('.intro__reveal img, .hero-art__logo');
    const decode = (img) => img.decode ? img.decode().catch(() => {}) : Promise.resolve();
    const ready = Promise.all([document.fonts ? document.fonts.ready : null, ...imgs.map(decode)]);
    const timeout = new Promise((res) => setTimeout(res, 4000));
    const t0 = performance.now();
    return Promise.race([ready, timeout]).then(() => {
      const shown = performance.now() - t0 > 200;          // byl preloader vidět?
      const wait = shown ? Math.max(0, 650 - (performance.now() - t0)) : 0;
      // smyčka se rozplyne současně s nástupem světel (beginIntro odebere intro--loading)
      return new Promise((res) => setTimeout(res, wait));
    });
  }

  skipBtn.addEventListener('click', () => endIntro(true));
  replayBtn.addEventListener('click', () => { closeContact(); beginIntro(); });
  if(skipIntro || reduced) endIntro();
  else whenReady().then(() => { if(!intro.classList.contains('intro--done')) beginIntro(); });

  const overlay = $('#contact');
  const board = $('#chessboard');
  const close = $('#closeContact');
  const puzzle = $('#contactPuzzle');
  const result = $('#contactResult');
  const feedback = $('#moveFeedback');
  let opener = null;
  const alphabet = 'ABCD';
  const knightImg = '<img src="assets/brand/jezdec-modry.svg?v=2.18.3" alt="" class="chessboard__knight" draggable="false">';

  function revealContact(){
    feedback.textContent = 'Skvělý tah.';
    puzzle.hidden = true;
    result.hidden = false;
    $('#resultTitle').setAttribute('tabindex','-1');
    $('#resultTitle').focus({preventScroll:true});
  }

  for(let row=0; row<4; row++){
    for(let col=0; col<4; col++){
      const name = alphabet[col] + (4-row);
      const origin = row===3 && col===1;
      const valid = (row===1 && (col===0 || col===2)) || (row===2 && col===3);
      const button = document.createElement('button');
      button.type = 'button';
      button.className = ((row+col)%2 ? 'dark ' : '') + (origin ? 'origin ' : valid ? 'valid ' : 'wrong');
      button.setAttribute('aria-label', name + (origin ? ', zde stojí jezdec' : valid ? ', možný tah jezdce' : ''));
      if(origin) button.innerHTML = knightImg;
      button.addEventListener('click', () => {
        if(valid){
          button.innerHTML = knightImg;
          button.classList.remove('valid');
          button.classList.add('origin');
          setTimeout(() => { if(overlay.classList.contains('is-open')) revealContact(); }, 220);
        } else {
          feedback.textContent = 'Tudy ne. Jezdec chodí 2 + 1.';
          feedback.classList.remove('shake'); void feedback.offsetWidth; feedback.classList.add('shake');
        }
      });
      board.append(button);
    }
  }

  function openContact(event){
    opener = event?.currentTarget || document.activeElement;
    overlay.inert = false;
    overlay.classList.add('is-open');
    overlay.setAttribute('aria-hidden','false');
    site.inert = true;
    close.focus({preventScroll:true});
  }
  function closeContact(){
    if(!overlay.classList.contains('is-open')) return;
    overlay.classList.remove('is-open');
    overlay.setAttribute('aria-hidden','true');
    overlay.inert = true;
    site.inert = false;
    if(opener?.focus) opener.focus({preventScroll:true});
  }

  $$('[data-open-contact]').forEach(btn => btn.addEventListener('click', openContact));
  close.addEventListener('click', closeContact);
  $('#showAnyway').addEventListener('click', revealContact);
  document.addEventListener('keydown', (e) => {
    if(e.key === 'Escape' && overlay.classList.contains('is-open')){ e.preventDefault(); closeContact(); }
    if(e.key === 'Escape' && playing){ e.preventDefault(); endIntro(true); }
    if(e.key === 'Tab' && overlay.classList.contains('is-open')){
      const focusables = $$('button:not([disabled]),a[href]', overlay).filter(x => x.getClientRects().length && !x.closest('[hidden]'));
      if(!focusables.length) return;
      const first = focusables[0], last = focusables[focusables.length-1];
      if(e.shiftKey && document.activeElement === first){ e.preventDefault(); last.focus(); }
      else if(!e.shiftKey && document.activeElement === last){ e.preventDefault(); first.focus(); }
    }
  });
})();
