// ─── SOUNDTRACK ───
// Jedidiah's own score, "The Call to Emberock", served from this site.
//
// It used to stream from SoundCloud through a hidden iframe and the Widget API,
// and it had never once played: a PRIVATE SoundCloud set cannot be addressed by
// its share link, so the widget fired ERROR and died without a sound. That is a
// silent failure mode with a third party in the middle of it, and there is no
// reason to keep the third party — these are the designer's own files. A plain
// <audio> element has no API to break, no script to load, and no account that
// can quietly change a sharing setting.
//
// The masters live here at the bitrate they were delivered in. Only ONE track is
// ever fetched — preload is off and the browser streams it — so the 38 MB on
// disk costs a listener about 5 MB, once, when the music starts. If a smaller
// web cut is ever wanted, derive it into a separate folder; do not re-encode
// these in place.
const TRACKS=[
  {file:"coin-rules-the-tide",   title:"Coin Rules the Tide"},
  {file:"crown-of-stone",        title:"Crown of Stone"},
  {file:"fleet-leader",          title:"Fleet Leader"},
  {file:"flesh-to-flame",        title:"Flesh to Flame"},
  {file:"grip-the-scythe-tight", title:"Grip the Scythe Tight"},
  {file:"noblemens-banner",      title:"Noblemen's Banner"},
  {file:"the-ballad-of-bendoss", title:"The Ballad of Bendoss"},
  {file:"the-yoke-of-strongoak", title:"The Yoke of Strongoak"}
];

const Music=(()=>{
  let el=null, order=[], at=0, wanted=false, vol=55, failed=false, playing=false, armed=false;

  // "Coin Rules the Tide" is the opener, every time — the piece the game should
  // be heard starting on. The other seven shuffle behind it, so the session
  // still varies without ever losing the entrance.
  const OPENER="coin-rules-the-tide";

  // Math.random, NOT the game's RNG. RNG is seeded so a match can be replayed
  // move for move; drawing from it to shuffle the music would make the running
  // order part of the game state and change every roll that followed.
  function shuffled(){
    const first=TRACKS.findIndex(t=>t.file===OPENER);
    const rest=TRACKS.map((_,i)=>i).filter(i=>i!==first);
    for(let i=rest.length-1;i>0;i--){const j=Math.floor(Math.random()*(i+1));[rest[i],rest[j]]=[rest[j],rest[i]]}
    return first>=0?[first,...rest]:rest;
  }

  function ensure(){
    if(el)return el;
    order=shuffled();at=0;
    el=document.createElement("audio");
    el.id="bbn-score";
    el.preload="none";                       // nothing is fetched until we play
    el.volume=Math.max(0,Math.min(1,vol/100));
    el.addEventListener("ended",()=>{at=(at+1)%order.length;load();if(wanted)tryPlay()});
    el.addEventListener("play",()=>{playing=true});
    el.addEventListener("pause",()=>{playing=false});
    // One bad file should move the score along, not end it. Only when a whole
    // pass over the set has failed is the soundtrack genuinely broken.
    let misses=0;
    el.addEventListener("error",()=>{
      playing=false;
      if(++misses>=TRACKS.length){failed=true;return}
      at=(at+1)%order.length;load();if(wanted)tryPlay();
    });
    el.addEventListener("playing",()=>{misses=0});
    load();
    // In the document, not floating free: a detached media element is fair game
    // for a browser to throttle or collect, and it cannot be inspected when
    // something goes wrong. It has no controls, so it draws nothing.
    if(document.body)document.body.appendChild(el);
    return el;
  }
  function load(){ if(el)el.src="audio/"+TRACKS[order[at]].file+".mp3" }

  function tryPlay(){
    if(!el)return;
    const p=el.play();
    // A refused promise is the browser saying "not from here" — not a fault.
    // Arm a retry against the next real gesture rather than giving up.
    if(p&&p.catch)p.catch(()=>{playing=false;arm()});
  }

  // A browser only lets audio start from a real gesture, and the title screen's
  // "tap to begin" was the ONLY one ever wired up. Reload inside a session and
  // the intro is skipped, so nothing asked again and the game played silent.
  // This listens for the next touch or key anywhere, tries once more, and takes
  // itself off as soon as the score is actually running.
  function arm(){
    if(armed||typeof document==="undefined")return;
    armed=true;
    const go=()=>{
      if(!wanted||playing){off();return}
      tryPlay();
      if(playing)off();
    };
    const off=()=>{
      armed=false;
      document.removeEventListener("pointerdown",go,true);
      document.removeEventListener("keydown",go,true);
    };
    document.addEventListener("pointerdown",go,true);
    document.addEventListener("keydown",go,true);
  }

  // A swell under the title sequence, so the score arrives WITH the menu rather
  // than being switched on at it. `vol` stays the target the whole way through —
  // the ramp only decides how fast the element gets there — so the volume
  // slider can be moved mid-fade and the swell simply climbs to the new mark.
  let fadeTimer=null;
  function rampTo(target,ms){
    if(!el)return;
    if(fadeTimer){clearInterval(fadeTimer);fadeTimer=null}
    const from=el.volume, to=Math.max(0,Math.min(1,target));
    if(ms<=0){el.volume=to;return}
    const t0=Date.now();
    fadeTimer=setInterval(()=>{
      if(!el){clearInterval(fadeTimer);fadeTimer=null;return}
      const k=Math.min(1,(Date.now()-t0)/ms);
      // ease in: quiet for longer, then it opens up — a swell, not a dimmer
      const eased=k*k;
      el.volume=Math.max(0,Math.min(1,from+(vol/100-from)*eased));
      if(k>=1){clearInterval(fadeTimer);fadeTimer=null;el.volume=Math.max(0,Math.min(1,vol/100))}
    },50);
  }

  return{
    // called once the player has tapped, so autoplay is allowed.
    // opts.fadeMs swells from silence over that long — used by the title
    // sequence so the music is already running when the menu lands.
    start(opts){
      wanted=true;ensure();
      const f=opts&&opts.fadeMs;
      if(f>0&&el){el.volume=0;tryPlay();rampTo(vol/100,f)}
      else tryPlay();
      arm();
    },
    stop(){wanted=false;playing=false;
      if(fadeTimer){clearInterval(fadeTimer);fadeTimer=null}
      if(el)el.pause()},
    setEnabled(on){on?this.start():this.stop()},
    setVolume(v){vol=Math.max(0,Math.min(100,v));
      if(el&&!fadeTimer)el.volume=vol/100},
    skip(){if(!el)return;at=(at+1)%order.length;load();if(wanted)tryPlay()},
    nowPlaying(){return el&&order.length?TRACKS[order[at]].title:null},
    trackCount(){return TRACKS.length},
    isReady(){return !!el&&!failed},
    isPlaying(){return playing},
    hasFailed(){return failed}
  };
})();
