// Stránka respektuje omezený pohyb v nastavení zařízení.
    const motionQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
    function applyMotionPreference() {
      document.body.classList.toggle('paused', motionQuery.matches);
      document.getElementById('intro-replay').hidden = motionQuery.matches;
    }
    applyMotionPreference();
    motionQuery.addEventListener('change', applyMotionPreference);
    const dialog = document.getElementById('contact-dialog');
    document.getElementById('contact-open').addEventListener('click', () => dialog.showModal());
    document.getElementById('contact-close').addEventListener('click', () => dialog.close());
    dialog.addEventListener('click', event => {
      if (event.target !== dialog) return;
      const rect = dialog.getBoundingClientRect();
      if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) dialog.close();
    });
    // Canvas používá skutečné jezdce z vloženého loga, bez zrcadlení jejich hlav.
    const cinematic = document.getElementById('cinematic');
    const page = document.querySelector('.page');
    const skipIntro = document.getElementById('intro-skip');
    const replayIntro = document.getElementById('intro-replay');
    const mainLogo = document.querySelector('.logo');
    const logoSource = new Image();
    logoSource.src = mainLogo.src;
    const loadingStatus = document.getElementById('loading-status');
    const canvas = document.getElementById('intro-canvas');
    const context = canvas.getContext('2d');
    const timers = new Set();
    let frame = 0, introToken = 0, introOpen = false, returnFocus = null;
    let sprite = null, width = 0, height = 0, pixelRatio = 1;
    const later = (callback, ms) => { const id = setTimeout(() => { timers.delete(id); callback(); }, ms); timers.add(id); return id; };
    const clamp = value => Math.min(1, Math.max(0,value));
    const ease = value => { const p = clamp(value); return p*p*(3-2*p); };
    const mix = (a,b,p) => a+(b-a)*p;
    function fitCanvas() {
      width = window.innerWidth; height = window.innerHeight;
      pixelRatio = Math.min(window.devicePixelRatio || 1, 2);
      canvas.width = Math.round(width*pixelRatio); canvas.height = Math.round(height*pixelRatio);
    }
    function makeSprite() {
      if (sprite) return;
      if (!logoSource.naturalWidth) throw new Error('Logo nebylo načteno');
      sprite = document.createElement('canvas'); sprite.width = 2048; sprite.height = 768;
      const ctx = sprite.getContext('2d',{willReadFrequently:true});
      ctx.drawImage(logoSource,0,0,2048,768);
      const image = ctx.getImageData(0,0,2048,768);
      // Odstranění bílé plochy pouze pro pohybující se kopii loga; originál zůstává.
      for(let i=0;i<image.data.length;i+=4) {
        const low = Math.min(image.data[i],image.data[i+1],image.data[i+2]);
        if(low>=245) image.data[i+3]=0;
        else if(low>220) image.data[i+3]=Math.round(255*(245-low)/25);
      }
      ctx.putImageData(image,0,0);
      mainLogo.src = sprite.toDataURL("image/png");
      // Dekorace jsou výřezy téhož loga jako figury v úvodu, nikoli typografické symboly.
      document.querySelector('.glyph-a').getContext('2d').drawImage(sprite,140,140,258,480,0,0,258,480);
      document.querySelector('.glyph-b').getContext('2d').drawImage(sprite,398,140,254,480,0,0,254,480);
    }
    function finishIntro(instant=false) {
      introToken++; introOpen=false;
      cancelAnimationFrame(frame); timers.forEach(clearTimeout); timers.clear();
      document.documentElement.classList.remove('intro-pending');
      document.body.classList.remove('intro-running'); page.inert=false;
      page.classList.remove('arrived'); void page.offsetWidth;
      if(!instant) page.classList.add('arrived');
      const restore = () => (returnFocus || document.getElementById('contact-open')).focus({preventScroll:true});
      if(instant) { cinematic.hidden=true; cinematic.className='cinematic'; restore(); }
      else { cinematic.classList.add('leaving'); later(() => {cinematic.hidden=true;cinematic.className='cinematic';restore();},650); }
    }
    function knightOffset(progress, travel, direction) {
      const p=clamp(progress);
      if(p<.35) return {x:direction*mix(travel,travel*.55,ease(p/.35)), y:-direction*65};
      if(p<.7) return {x:direction*travel*.55,y:-direction*mix(65,0,ease((p-.35)/.35))};
      return {x:direction*mix(travel*.55,0,ease((p-.7)/.3)),y:0};
    }
    function heartPath(ctx) {
      ctx.beginPath(); ctx.moveTo(397,306);
      ctx.bezierCurveTo(367,274,312,267,284,295);
      ctx.bezierCurveTo(248,331,283,385,397,477);
      ctx.bezierCurveTo(511,385,546,331,510,295);
      ctx.bezierCurveTo(482,267,427,274,397,306);ctx.closePath();
    }
    function paint(seconds) {
      context.setTransform(pixelRatio,0,0,pixelRatio,0,0);
      context.globalAlpha=1; context.fillStyle='#11457e'; context.fillRect(0,0,width,height);
      const reveal=ease(seconds/.55);
      context.save();context.beginPath();context.arc(width/2,height/2,Math.hypot(width,height)*reveal,0,Math.PI*2);context.clip();context.fillStyle='#ffffff';context.fillRect(0,0,width,height);context.restore();
      if(seconds>.55) cinematic.classList.add('light');
      const depart=ease((seconds-3.45)/1.05);
      const scale=Math.min(420,width*.78,height*.63)/512;
      const initial={x:width/2-396*scale,y:height/2-30-380*scale,scale};
      const target=mainLogo.getBoundingClientRect();
      const landingScale=target.width/2048;
      const x=mix(initial.x,target.left,depart), y=mix(initial.y,target.top,depart), s=mix(scale,landingScale,depart);
      const progress=clamp((seconds-.28)/1.95);
      const blue=knightOffset(progress,Math.min(width*.42,420),-1);
      const red=knightOffset(progress,Math.min(width*.42,420),1);
      // Abstraktní síť naznačuje dráhu tahů, nepřekrývá hotové logo.
      context.save();context.globalAlpha=.09*ease(seconds/.5)*(1-depart);context.strokeStyle='#11457e';context.lineWidth=1;
      const grid=width<600?50:75;
      for(let gx=(width/2)%grid;gx<width;gx+=grid){context.beginPath();context.moveTo(gx,height*.15);context.lineTo(gx,height*.85);context.stroke();}
      for(let gy=height*.15;gy<height*.86;gy+=grid){context.beginPath();context.moveTo(0,gy);context.lineTo(width,gy);context.stroke();}
      context.restore();
      context.globalAlpha=ease(seconds/.38);
      context.drawImage(sprite,140,140,258,480,x+140*s+blue.x,y+140*s+blue.y,258*s,480*s);
      context.drawImage(sprite,398,140,254,480,x+398*s+red.x,y+140*s+red.y,254*s,480*s);
      // Srdce se zvýrazní až po přesném spojení původních siluet.
      const heartTime=seconds-2.25;
      if(heartTime>=0 && heartTime<1.15) {
        const p=clamp(heartTime/1.15);
        const maximum=Math.max(6,Math.hypot(width,height)/(180*s));
        const growth=1+(maximum-1)*p*p*p;
        const opacity=ease(p/.12)*(1-ease((p-.38)/.62));
        context.save();
        context.translate(x+397*s,y+380*s);
        context.scale(s*growth,s*growth);
        context.translate(-397,-380);
        heartPath(context);
        context.fillStyle=`rgba(215,20,26,${.12*opacity})`;context.fill();
        context.lineWidth=4/Math.sqrt(growth);
        context.strokeStyle=`rgba(215,20,26,${.85*opacity})`;context.stroke();
        context.restore();
      }
      context.globalAlpha=ease((seconds-3.62)/.8);
      context.drawImage(sprite,690,250,1358,310,target.left+690*landingScale,target.top+250*landingScale,1358*landingScale,310*landingScale);
      const captionAlpha=ease((seconds-.65)/.4)*(1-ease((seconds-3.05)/.4));
      context.globalAlpha=captionAlpha;context.fillStyle='#11457e';context.font=`500 ${width<600?22:30}px system-ui, sans-serif`;context.textAlign='center';
      context.fillText('Každý tah nás spojuje.',width/2,Math.min(height-65,height/2+scale*250+25));
      context.globalAlpha=1;
    }
    async function startIntro(replay=false) {
      if(!context || motionQuery.matches) {document.documentElement.classList.remove('intro-pending');return;}
      cancelAnimationFrame(frame);timers.forEach(clearTimeout);timers.clear();
      const token=++introToken;introOpen=true;returnFocus=replay?replayIntro:null;
      cinematic.className='cinematic';cinematic.hidden=false;document.body.classList.add('intro-running');
      document.documentElement.classList.remove('intro-pending');page.inert=true;skipIntro.focus({preventScroll:true});
      loadingStatus.textContent='Připravujeme první tah.';fitCanvas();
      later(()=>finishIntro(true),10000);
      try {
        const ready=typeof logoSource.decode==='function'?logoSource.decode():new Promise((resolve,reject)=>{
          if(logoSource.complete) logoSource.naturalWidth?resolve():reject(new Error('Logo'));
          else {logoSource.addEventListener('load',resolve,{once:true});logoSource.addEventListener('error',reject,{once:true});}
        });
        await Promise.all([ready,new Promise(resolve=>later(resolve,replay?100:350))]);
        if(token!==introToken || !introOpen)return;
        makeSprite();loadingStatus.textContent='Logo je připravené.';cinematic.classList.add('ready');
        const start=performance.now();
        const tick=now=>{
          if(token!==introToken || !introOpen)return;
          const seconds=(now-start)/1000;paint(Math.min(seconds,4.65));
          if(seconds>=4.65){finishIntro();return;}
          frame=requestAnimationFrame(tick);
        };
        frame=requestAnimationFrame(tick);
      } catch(error) { if(token===introToken)finishIntro(true); }
    }
    skipIntro.addEventListener('click',()=>finishIntro());
    replayIntro.addEventListener('click',()=>startIntro(true));
    cinematic.addEventListener('keydown',event=>{
      if(event.key==='Escape'){event.preventDefault();finishIntro();}
      if(event.key==='Tab' && introOpen){event.preventDefault();skipIntro.focus();}
    });
    window.addEventListener('resize',()=>{if(introOpen)fitCanvas();});
    motionQuery.addEventListener('change',event=>{if(event.matches)finishIntro(true);});
    window.addEventListener('pagehide',()=>finishIntro(true));
    // Připravit shodné dekorace i při vypnutém úvodu (omezený pohyb).
    logoSource.decode().then(makeSprite).catch(()=>{});
    startIntro();
