// ═══ TITLE SEQUENCE ═══
// The animated cover waits on its first frame. Tapping starts it, it plays once,
// and the end of the video fades into the menu — the animation already pushes
// in, so nothing is layered on top of it.
// Audio is synthesised with the Web Audio API — no sound files to download, and
// nothing plays until the player taps, which is also what unlocks audio on iOS.

const Sfx=(()=>{
  let ctx=null,master=null,enabled=true;
  const ac=()=>{
    if(!ctx){
      const AC=window.AudioContext||window.webkitAudioContext;
      if(!AC)return null;
      ctx=new AC();
      master=ctx.createGain();master.gain.value=0.9;master.connect(ctx.destination);
    }
    if(ctx.state==="suspended")ctx.resume();
    return ctx;
  };
  const noiseBuffer=(c,secs)=>{
    const b=c.createBuffer(1,c.sampleRate*secs,c.sampleRate);
    const d=b.getChannelData(0);
    for(let i=0;i<d.length;i++)d[i]=Math.random()*2-1;
    return b;
  };
  return{
    unlock(){ac()},
    setEnabled(v){enabled=v;if(master)master.gain.value=v?0.9:0},
    isEnabled(){return enabled},
    // deep brass-like swell for the push-in
    swell(dur=2.4){
      const c=ac();if(!c||!enabled)return;
      const t=c.currentTime;
      const g=c.createGain();g.gain.setValueAtTime(0.0001,t);
      g.gain.exponentialRampToValueAtTime(0.5,t+dur*0.55);
      g.gain.exponentialRampToValueAtTime(0.0001,t+dur);
      g.connect(master);
      [55,82.5,110,164.8].forEach((f,i)=>{
        const o=c.createOscillator();
        o.type=i<2?"sawtooth":"triangle";
        o.frequency.setValueAtTime(f*0.99,t);
        o.frequency.linearRampToValueAtTime(f,t+dur*0.8);
        const og=c.createGain();og.gain.value=[0.5,0.34,0.2,0.1][i];
        const lp=c.createBiquadFilter();lp.type="lowpass";
        lp.frequency.setValueAtTime(220,t);
        lp.frequency.exponentialRampToValueAtTime(1800,t+dur*0.7);
        o.connect(og);og.connect(lp);lp.connect(g);
        o.start(t);o.stop(t+dur);
      });
    },
    // crackling embers bed
    embers(dur=3.2){
      const c=ac();if(!c||!enabled)return;
      const t=c.currentTime;
      const src=c.createBufferSource();src.buffer=noiseBuffer(c,dur);
      const bp=c.createBiquadFilter();bp.type="bandpass";bp.frequency.value=1600;bp.Q.value=0.7;
      const g=c.createGain();
      g.gain.setValueAtTime(0.0001,t);
      g.gain.exponentialRampToValueAtTime(0.09,t+0.6);
      g.gain.exponentialRampToValueAtTime(0.0001,t+dur);
      src.connect(bp);bp.connect(g);g.connect(master);
      src.start(t);src.stop(t+dur);
      // occasional pops
      for(let i=0;i<14;i++){
        const at=t+Math.random()*dur;
        const o=c.createOscillator();o.type="triangle";
        o.frequency.setValueAtTime(500+Math.random()*1400,at);
        const og=c.createGain();
        og.gain.setValueAtTime(0.0001,at);
        og.gain.exponentialRampToValueAtTime(0.05+Math.random()*0.05,at+0.006);
        og.gain.exponentialRampToValueAtTime(0.0001,at+0.09);
        o.connect(og);og.connect(master);o.start(at);o.stop(at+0.1);
      }
    },
    // bright metallic ring for the reveal
    steel(){
      const c=ac();if(!c||!enabled)return;
      const t=c.currentTime;
      const g=c.createGain();
      g.gain.setValueAtTime(0.0001,t);
      g.gain.exponentialRampToValueAtTime(0.32,t+0.012);
      g.gain.exponentialRampToValueAtTime(0.0001,t+1.9);
      g.connect(master);
      [1046,1568,2093,3136,4186].forEach((f,i)=>{
        const o=c.createOscillator();o.type="sine";
        o.frequency.setValueAtTime(f*(1+(Math.random()-0.5)*0.004),t);
        const og=c.createGain();og.gain.value=[0.5,0.3,0.22,0.12,0.07][i];
        o.connect(og);og.connect(g);o.start(t);o.stop(t+2);
      });
      const src=c.createBufferSource();src.buffer=noiseBuffer(c,0.18);
      const hp=c.createBiquadFilter();hp.type="highpass";hp.frequency.value=3000;
      const ng=c.createGain();
      ng.gain.setValueAtTime(0.16,t);ng.gain.exponentialRampToValueAtTime(0.0001,t+0.18);
      src.connect(hp);hp.connect(ng);ng.connect(master);src.start(t);src.stop(t+0.2);
    },
    // small UI tick
    tick(){
      const c=ac();if(!c||!enabled)return;
      const t=c.currentTime;
      const o=c.createOscillator();o.type="triangle";
      o.frequency.setValueAtTime(760,t);o.frequency.exponentialRampToValueAtTime(420,t+0.07);
      const g=c.createGain();
      g.gain.setValueAtTime(0.0001,t);
      g.gain.exponentialRampToValueAtTime(0.12,t+0.008);
      g.gain.exponentialRampToValueAtTime(0.0001,t+0.12);
      o.connect(g);g.connect(master);o.start(t);o.stop(t+0.13);
    },

    // ── the battle bed ──
    // Everything below is synthesised. A short burst of filtered noise is what
    // most physical sounds actually are; the filter shape and envelope are what
    // make one read as a sword and another as a musket.
    noise(dur,type,freq,q,peak,at,dk,when){
      const c=ac();if(!c||!enabled)return null;
      const t=(when||c.currentTime);
      const src=c.createBufferSource();src.buffer=noiseBuffer(c,dur);
      const f=c.createBiquadFilter();f.type=type;f.frequency.value=freq;
      if(q!=null)f.Q.value=q;
      const g=c.createGain();
      g.gain.setValueAtTime(0.0001,t);
      g.gain.exponentialRampToValueAtTime(peak,t+at);
      g.gain.exponentialRampToValueAtTime(0.0001,t+at+dk);
      src.connect(f);f.connect(g);g.connect(master);
      src.start(t);src.stop(t+dur);
      return{t,f,g};
    },
    // dice tumbling and settling on the table
    diceRoll(n){
      const c=ac();if(!c||!enabled)return;
      const t0=c.currentTime;
      const hits=Math.min(14,4+(n||1)*2);
      for(let i=0;i<hits;i++){
        // clatter crowds together then thins out as the dice settle
        const at=t0+Math.pow(i/hits,0.6)*0.95+Math.random()*0.04;
        const o=c.createOscillator();o.type="square";
        o.frequency.setValueAtTime(240+Math.random()*520,at);
        const g=c.createGain();
        g.gain.setValueAtTime(0.0001,at);
        g.gain.exponentialRampToValueAtTime(0.05+Math.random()*0.05,at+0.004);
        g.gain.exponentialRampToValueAtTime(0.0001,at+0.05);
        const f=c.createBiquadFilter();f.type="bandpass";
        f.frequency.value=1400+Math.random()*1800;f.Q.value=1.4;
        o.connect(f);f.connect(g);g.connect(master);o.start(at);o.stop(at+0.06);
      }
    },
    // boots on the board, one per hex crossed
    step(hexes){
      const c=ac();if(!c||!enabled)return;
      const n=Math.max(1,Math.min(8,hexes||1));
      for(let i=0;i<n;i++){
        const at=c.currentTime+i*0.15;
        this.noise(0.09,"lowpass",620,0.9,0.075,0.006,0.07,at);
      }
    },
    // weapon voices — see WEAPON_OF() for which character sounds like what
    weapon(kind){
      const c=ac();if(!c||!enabled)return;
      const t=c.currentTime;
      if(kind==="gun"){
        this.noise(0.22,"highpass",900,null,0.5,0.003,0.16,t);
        this.noise(0.3,"lowpass",180,null,0.42,0.006,0.26,t);   // the thump
      }else if(kind==="cannon"){
        this.noise(0.75,"lowpass",120,null,0.62,0.012,0.62,t);
        const o=c.createOscillator();o.type="sine";
        o.frequency.setValueAtTime(96,t);o.frequency.exponentialRampToValueAtTime(34,t+0.5);
        const g=c.createGain();
        g.gain.setValueAtTime(0.0001,t);
        g.gain.exponentialRampToValueAtTime(0.5,t+0.02);
        g.gain.exponentialRampToValueAtTime(0.0001,t+0.6);
        o.connect(g);g.connect(master);o.start(t);o.stop(t+0.62);
      }else if(kind==="bow"){
        this.noise(0.1,"bandpass",1500,3,0.24,0.004,0.08,t);    // the release
        this.noise(0.34,"bandpass",3600,7,0.13,0.05,0.24,t+0.03); // the flight
      }else if(kind==="magic"){
        [880,1320,1760,2640].forEach((f,i)=>{
          const o=c.createOscillator();o.type="sine";
          o.frequency.setValueAtTime(f*0.7,t);
          o.frequency.exponentialRampToValueAtTime(f*1.5,t+0.42);
          const g=c.createGain();
          g.gain.setValueAtTime(0.0001,t+i*0.03);
          g.gain.exponentialRampToValueAtTime(0.13/(i+1),t+i*0.03+0.05);
          g.gain.exponentialRampToValueAtTime(0.0001,t+0.5);
          o.connect(g);g.connect(master);o.start(t);o.stop(t+0.52);
        });
      }else{                                    // blade
        this.noise(0.18,"bandpass",2600,2.2,0.34,0.004,0.13,t);
        this.noise(0.26,"highpass",4200,null,0.16,0.012,0.2,t+0.02);
      }
    },
    // a hit landing, and a figure going down
    impact(){
      const c=ac();if(!c||!enabled)return;
      const t=c.currentTime;
      this.noise(0.2,"lowpass",320,null,0.4,0.004,0.16,t);
      const o=c.createOscillator();o.type="triangle";
      o.frequency.setValueAtTime(160,t);o.frequency.exponentialRampToValueAtTime(58,t+0.16);
      const g=c.createGain();
      g.gain.setValueAtTime(0.0001,t);
      g.gain.exponentialRampToValueAtTime(0.3,t+0.006);
      g.gain.exponentialRampToValueAtTime(0.0001,t+0.2);
      o.connect(g);g.connect(master);o.start(t);o.stop(t+0.22);
    },
    fall(){
      const c=ac();if(!c||!enabled)return;
      const t=c.currentTime;
      this.noise(0.5,"lowpass",240,null,0.34,0.01,0.44,t);
      [330,247,196].forEach((f,i)=>{
        const at=t+0.06+i*0.09;
        const o=c.createOscillator();o.type="triangle";
        o.frequency.setValueAtTime(f,at);
        const g=c.createGain();
        g.gain.setValueAtTime(0.0001,at);
        g.gain.exponentialRampToValueAtTime(0.13,at+0.02);
        g.gain.exponentialRampToValueAtTime(0.0001,at+0.32);
        o.connect(g);g.connect(master);o.start(at);o.stop(at+0.34);
      });
    },
    coin(){
      const c=ac();if(!c||!enabled)return;
      const t=c.currentTime;
      [2100,3150,4200].forEach((f,i)=>{
        const o=c.createOscillator();o.type="sine";
        o.frequency.setValueAtTime(f*(1+(Math.random()-0.5)*0.02),t);
        const g=c.createGain();
        g.gain.setValueAtTime(0.0001,t);
        g.gain.exponentialRampToValueAtTime(0.16/(i+1),t+0.006);
        g.gain.exponentialRampToValueAtTime(0.0001,t+0.55);
        o.connect(g);g.connect(master);o.start(t);o.stop(t+0.57);
      });
    }
  };
})();

// Which weapon a character is holding. Range separates melee from ranged, and
// the faction and name settle what KIND of ranged — a Musketeer should crack,
// an Alchemist should shimmer, the Cannoneers should boom.
function weaponOf(card){
  if(!card)return "blade";
  const n=(card.name||"").toLowerCase();
  const id=(card.id||"").toLowerCase();
  const rng=(card.s&&card.s.range)||1;
  if(/cannon/.test(n+id))return "cannon";
  if(/musket|gun|coat|harbormen|admiral|infantry/.test(n+id))return "gun";
  // Alchemists who strike at a distance are throwing something; the ones who
  // fight at arm's length (Elysium, Hadrian, the Marywicks) still swing steel.
  if(card.faction==="Alchemist"&&rng>=2)return "magic";
  if(rng>=5)return "bow";
  if(rng>=3)return card.faction==="Merchant"?"gun":"bow";
  return "blade";
}

function Intro({onDone,sound,music}){
  const[phase,setPhase]=useState("idle");      // idle → playing → gone
  const[videoOk,setVideoOk]=useState(true);    // false once the cover fails to play
  const[ended,setEnded]=useState(false);       // the cover has played out
  const vidRef=useRef(null);
  const reduced=typeof matchMedia!=="undefined"
    &&matchMedia("(prefers-reduced-motion: reduce)").matches;

  // The cover holds on its poster until you tap. The tap starts it, it plays
  // once, and the end of the video IS the transition — no invented zoom on top
  // of an animation that already moves.
  //
  // Muted is set on the node rather than as a prop because React does not apply
  // that attribute reliably; the element carries no autoPlay for the same
  // reason, and because nothing should play before the tap anyway. A refused
  // play() is not a broken video — only a genuine media error gives up, and the
  // poster carries the same frame meanwhile.
  const playCover=useCallback(()=>{
    const v=vidRef.current;
    if(!v)return false;
    v.muted=true;v.defaultMuted=true;
    try{v.currentTime=0}catch(_){}
    const p=v.play();
    if(p&&p.catch)p.catch(()=>{
      // it will not play — do not strand the player on a frozen frame
      setTimeout(()=>{setPhase("gone");onDone()},600);
    });
    return true;
  },[onDone]);

  const finish=useCallback(()=>{
    setPhase(p=>{
      if(p==="gone")return p;
      setTimeout(onDone,20);
      return "gone";
    });
  },[onDone]);

  const begin=useCallback(()=>{
    if(phase!=="idle")return;
    Sfx.unlock();
    Sfx.setEnabled(sound!==false);
    // This tap is the only moment a browser will let audio start.
    //
    // It swells from silence across the title sequence rather than snapping on,
    // so "Coin Rules the Tide" is already running — and already up — at the
    // moment the menu lands. Matched to the 4.06s cover plus its fade out; if
    // the video is skipped the ramp is short, because the menu is right there.
    if(music!==false&&typeof Music!=="undefined")
      Music.start({fadeMs:(reduced||!videoOk)?900:4200});
    if(reduced||!videoOk){onDone();return}
    Sfx.embers(3.0);
    Sfx.swell(2.2);
    setPhase("playing");
    if(!playCover()){onDone();return}
    setTimeout(()=>Sfx.steel(),1150);
    // The video is 4.06s. If `ended` never fires — a stall, a tab switch — the
    // player must not be left staring at the cover forever.
    setTimeout(finish,5200);
  },[phase,onDone,reduced,sound,music,videoOk,playCover,finish]);

  useEffect(()=>{
    const onKey=e=>{if(e.key===" "||e.key==="Enter")begin()};
    window.addEventListener("keydown",onKey);
    return()=>window.removeEventListener("keydown",onKey);
  },[begin]);

  const playing=phase==="playing";
  return(
    <div onClick={begin} style={{position:"fixed",inset:0,zIndex:800,overflow:"hidden",
      background:"var(--ink-950)",cursor:"pointer",
      opacity:phase==="gone"?0:1,transition:"opacity 620ms ease-out"}}>

      {/* The animated cover. It waits on its poster, the tap starts it, and the
          end of the video is the cue to fade into the menu — the video already
          pushes in, so there is nothing to add on top of it.
          The source was a 12MB HEVC square: HEVC does not play in Chrome or
          Firefox at all, so it is transcoded to H.264 regardless of size, and
          720px at CRF 26 brings it to 675KB. */}
      <div style={{position:"absolute",inset:"-6%",overflow:"hidden"}}>
        {(reduced||!videoOk)
          ? <img src="brand/intro-poster.jpg" alt="" aria-hidden="true"
              style={{width:"100%",height:"100%",objectFit:"cover",
                objectPosition:"center 42%",display:"block"}}/>
          : <video ref={vidRef} src="brand/intro.mp4" poster="brand/intro-poster.jpg"
              muted playsInline preload="auto"
              onEnded={()=>{setEnded(true);finish()}}
              onError={()=>setVideoOk(false)}
              style={{width:"100%",height:"100%",objectFit:"cover",
                objectPosition:"center 42%",display:"block"}}/>}
      </div>

      {/* darkening so the wordmark reads */}
      <div style={{position:"absolute",inset:0,pointerEvents:"none",
        background:"radial-gradient(115% 80% at 50% 46%,rgba(0,0,0,.12),rgba(0,0,0,.72) 74%,rgba(0,0,0,.92))",
        opacity:playing?1:.85,transition:"opacity 2000ms ease-in"}}/>
      <div className="grain" style={{position:"absolute",inset:0,pointerEvents:"none"}}/>

      {/* centred wordmark */}
      <div style={{position:"absolute",inset:0,display:"flex",flexDirection:"column",
        alignItems:"center",justifyContent:"center",gap:"var(--s-5)",
        padding:"var(--s-5)",textAlign:"center",zIndex:4,
        transform:playing?"scale(1.5)":"scale(1)",
        opacity:playing?0:1,
        transition:playing?"transform 2000ms cubic-bezier(.5,0,.35,1), opacity 1500ms ease-in":"none"}}>
        <img src="brand/logo.png" alt="Barnburners &amp; Noblemen" className="brand-logo"
          style={{animation:"introLogo 1400ms var(--ease-out-quint) both"}}/>
        <div className="t-eyebrow" style={{color:"var(--gold-300)",
          animation:"introHint 1200ms var(--ease-out-quint) 700ms both"}}>
          <span style={{opacity:.9}}>Tap to begin</span>
        </div>
      </div>

      {/* publisher mark, low and quiet */}
      <div style={{position:"absolute",left:0,right:0,
        bottom:"calc(var(--s-5) + var(--sa-b))",zIndex:5,
        display:"flex",flexDirection:"column",alignItems:"center",gap:"var(--s-1)",
        opacity:playing?0:.9,transition:"opacity 900ms ease-in",pointerEvents:"none",
        animation:"introHint 1200ms var(--ease-out-quint) 1000ms both"}}>
        <img src="brand/faction-sinderstone.png" alt="Sinderstone Games"
          style={{width:44,height:"auto",filter:"drop-shadow(0 3px 12px rgba(0,0,0,.9))"}}/>
        <span className="t-micro" style={{color:"var(--parch-400)",letterSpacing:".2em",
          textTransform:"uppercase"}}>Sinderstone Games</span>
      </div>

      {/* white flash on the reveal */}
      <div style={{position:"absolute",inset:0,pointerEvents:"none",background:"#F7E7B8",
        opacity:0,animation:playing?"introFlash 900ms ease-out 1150ms both":"none",zIndex:6}}/>
    </div>);
}
