/* ============================================================
   SHADOW STEP — app-cards
   Mounts every ShadowStepCard island + builds data-driven DOM
   (map grid, feed, carousel). Exposes window.SS control API.
   Runs as Babel; everything shared via window.SS.
   ============================================================ */
const SS = (window.SS = window.SS || {});

/* ── Demo roster ─────────────────────────────────── */
SS.roster = [
  { playerName:'kingflexjr', archetype:'finalForm',  tier:'celestial', xpProgress:.88, xp:96240,
    stats:{record:'31-3',offRtg:'92.1',defRtg:'74.0'}, homeCourt:'Rucker Park', homeCourtSub:'Harlem · NY',
    squad:'The Grind Collective', seasonRecord:{wins:31,losses:3,streak:11},
    skills:[{icon:'flame',tier:'V'},{icon:'bolt',tier:'IV'},{icon:'target',tier:'IV'},{icon:'ball',tier:'III'},{icon:'eye',tier:'III'},{icon:'loop',tier:'II'}] },
  { playerName:'eq_so_lo',   archetype:'flamethrower', tier:'prismatic', xpProgress:.71, xp:54110,
    stats:{record:'24-8',offRtg:'88.6',defRtg:'70.2'}, homeCourt:'Venice Beach', homeCourtSub:'LA · CA',
    squad:'Sunset Snipers', seasonRecord:{wins:24,losses:8,streak:4},
    skills:[{icon:'flame',tier:'IV'},{icon:'target',tier:'III'},{icon:'ball',tier:'II'},{icon:'bolt',tier:'II'},{icon:'eye',tier:'I'},{icon:'loop',tier:'I'}] },
  { playerName:'p.g.dior',   archetype:'pointGod',    tier:'crystalline', xpProgress:.55, xp:38600,
    stats:{record:'19-6',offRtg:'90.3',defRtg:'77.5'}, homeCourt:'Dyckman', homeCourtSub:'Inwood · NY',
    squad:'Maestro Unit', seasonRecord:{wins:19,losses:6,streak:3},
    skills:[{icon:'loop',tier:'IV'},{icon:'eye',tier:'III'},{icon:'ball',tier:'III'},{icon:'bolt',tier:'II'},{icon:'target',tier:'I'},{icon:'flame',tier:'I'}] },
  { playerName:'air.mail',   archetype:'aerialArtist', tier:'prismatic', xpProgress:.64, xp:47220,
    stats:{record:'22-9',offRtg:'85.0',defRtg:'72.8'}, homeCourt:'The Cage', homeCourtSub:'W4th · NY',
    squad:'Above The Rim', seasonRecord:{wins:22,losses:9,streak:5},
    skills:[{icon:'bolt',tier:'V'},{icon:'flame',tier:'III'},{icon:'ball',tier:'II'},{icon:'target',tier:'II'},{icon:'eye',tier:'I'},{icon:'loop',tier:'I'}] },
  { playerName:'lockcity',   archetype:'shadow',      tier:'satin', xpProgress:.34, xp:14800,
    stats:{record:'15-5',offRtg:'68.1',defRtg:'91.4'}, homeCourt:'Mosswood', homeCourtSub:'Oakland · CA',
    squad:'No Easy Buckets', seasonRecord:{wins:15,losses:5,streak:6},
    skills:[{icon:'eye',tier:'IV'},{icon:'target',tier:'III'},{icon:'ball',tier:'II'},{icon:'bolt',tier:'I'},{icon:'flame',tier:'I'},{icon:'loop',tier:'I'}] },
  { playerName:'tower.uni',  archetype:'unicorn',     tier:'celestial', xpProgress:.81, xp:78900,
    stats:{record:'27-4',offRtg:'89.9',defRtg:'85.6'}, homeCourt:'Goat Park', homeCourtSub:'Harlem · NY',
    squad:'Mismatch Inc', seasonRecord:{wins:27,losses:4,streak:9},
    skills:[{icon:'target',tier:'V'},{icon:'flame',tier:'IV'},{icon:'eye',tier:'IV'},{icon:'ball',tier:'III'},{icon:'bolt',tier:'II'},{icon:'loop',tier:'II'}] },
  { playerName:'ankle.gov',  archetype:'ankletaker',  tier:'crystalline', xpProgress:.49, xp:31200,
    stats:{record:'20-7',offRtg:'86.7',defRtg:'69.0'}, homeCourt:'St. Mary', homeCourtSub:'Bronx · NY',
    squad:'The Puppeteers', seasonRecord:{wins:20,losses:7,streak:2},
    skills:[{icon:'loop',tier:'IV'},{icon:'ball',tier:'III'},{icon:'bolt',tier:'III'},{icon:'eye',tier:'II'},{icon:'target',tier:'I'},{icon:'flame',tier:'I'}] },
  { playerName:'blur.exe',   archetype:'blur',        tier:'prismatic', xpProgress:.6, xp:44000,
    stats:{record:'21-6',offRtg:'84.4',defRtg:'73.3'}, homeCourt:'Lincoln', homeCourtSub:'Brooklyn · NY',
    squad:'Lightspeed', seasonRecord:{wins:21,losses:6,streak:4},
    skills:[{icon:'bolt',tier:'V'},{icon:'ball',tier:'III'},{icon:'loop',tier:'II'},{icon:'eye',tier:'II'},{icon:'target',tier:'I'},{icon:'flame',tier:'I'}] },
];

/* archetype descriptions for the carousel */
SS.archDesc = {
  finalForm:'The apex build. Everything maxed, nothing wasted. You don\u2019t get here — you become it.',
  flamethrower:'Range that bends the floor. Pull up from the logo and dare them to follow.',
  pointGod:'The system runs through you. Read the floor, drop the dime, control the tempo.',
  aerialArtist:'Gravity is a suggestion. Live above the rim, finish through contact.',
  shadow:'They don\u2019t score on you. Read, anticipate, erase. Defense as identity.',
  unicorn:'Stretch and protect. Splash from deep, anchor the paint. A walking mismatch.',
  ankletaker:'The handle that ends careers. Shift, cross, showtime. Leave them on the floor.',
  blur:'Pure speed in the open floor. Coast-to-coast before they cross half court.',
};

/* ── Hero layouts per variation (read by app-motion) ── */
/* x/y in %, scale, z(px), blur(px), rot(deg) */
SS.heroLayouts = {
  scatter: {
    hero: { x:50, y:50, scale:1,    z:0,    blur:0, rot:0 },
    scatter: [
      { x:16, y:30, scale:.42, z:-360, blur:2.5, rot:-6 },
      { x:83, y:26, scale:.46, z:-300, blur:2,   rot:5 },
      { x:24, y:74, scale:.5,  z:-240, blur:1.6, rot:4 },
      { x:78, y:72, scale:.4,  z:-420, blur:3,   rot:-5 },
      { x:64, y:18, scale:.34, z:-520, blur:3.5, rot:7 },
      { x:38, y:84, scale:.36, z:-480, blur:3,   rot:-4 },
      { x:90, y:52, scale:.3,  z:-560, blur:4,   rot:6 },
    ],
  },
  monolith: {
    hero: { x:50, y:50, scale:1.08, z:0, blur:0, rot:0 },
    scatter: [
      { x:50,y:50,scale:.3,z:-900,blur:8,rot:0,hide:1 },
      { x:50,y:50,scale:.3,z:-900,blur:8,rot:0,hide:1 },
      { x:50,y:50,scale:.3,z:-900,blur:8,rot:0,hide:1 },
      { x:50,y:50,scale:.3,z:-900,blur:8,rot:0,hide:1 },
      { x:50,y:50,scale:.3,z:-900,blur:8,rot:0,hide:1 },
      { x:50,y:50,scale:.3,z:-900,blur:8,rot:0,hide:1 },
      { x:50,y:50,scale:.3,z:-900,blur:8,rot:0,hide:1 },
    ],
  },
  draft: {
    hero: { x:50, y:50, scale:.66, z:60, blur:0, rot:0 },
    scatter: [
      { x:22, y:32, scale:.5, z:-120, blur:0,   rot:0 },
      { x:50, y:32, scale:.5, z:-120, blur:0,   rot:0 },
      { x:78, y:32, scale:.5, z:-120, blur:0,   rot:0 },
      { x:22, y:72, scale:.5, z:-120, blur:0,   rot:0 },
      { x:78, y:72, scale:.5, z:-120, blur:0,   rot:0 },
      { x:14, y:52, scale:.42,z:-260, blur:1.4, rot:0 },
      { x:86, y:52, scale:.42,z:-260, blur:1.4, rot:0 },
    ],
  },
};

/* ── Mount hero + scatter cards ──────────────────── */
function buildVoid(){
  // hero (roster[0], celestial)
  window.mountCard(document.getElementById('heroCard'), {
    ...SS.roster[0], tier:'celestial', flippable:false, rotateOnIdle:true, tiltStrength:13, glowIntensity:78, glowSpread:110,
  });
  // scatter holders
  const scat = document.getElementById('scatter');
  const used = SS.roster.slice(1);
  SS.scatterEls = [];
  for(let i=0;i<7;i++){
    const holder = document.createElement('div');
    holder.className='scard';
    const mount = document.createElement('div');
    holder.appendChild(mount);
    scat.appendChild(holder);
    const r = used[i % used.length];
    window.mountCard(mount, { ...r, flippable:false, tiltStrength:8, glowIntensity:55, glowSpread:70, rotateOnIdle:false });
    SS.scatterEls.push(holder);
  }
}

/* ── Deep-dive card (Section 3) ──────────────────── */
SS.deepRoot = null;
SS.deepBack = false;
function buildDeep(){
  SS.deepRoot = window.mountCard(document.getElementById('deepCard'), {
    ...SS.roster[5], tier:'celestial', tiltStrength:0, rotateOnIdle:false, glowIntensity:70, glowSpread:95, showBack:false,
  });
}
SS.flipDeep = function(back){
  SS.deepBack = back;
  window.mountCard(document.getElementById('deepCard'), {
    ...SS.roster[5], tier:'celestial', tiltStrength: SS.deepInteractive?12:0, rotateOnIdle:false,
    glowIntensity:70, glowSpread:95, showBack:back,
  });
};
SS.setDeepInteractive = function(on){
  SS.deepInteractive = on;
  window.mountCard(document.getElementById('deepCard'), {
    ...SS.roster[5], tier:'celestial', tiltStrength:on?13:0, rotateOnIdle:false,
    glowIntensity:on?82:70, glowSpread:95, showBack:SS.deepBack,
  });
};

/* ── Map grid SVG — retired; real Mapbox overworld now renders the city ── */
function buildMapGrid(){
  const svg = document.getElementById('mapGrid');
  if(!svg) return;
  const W=1600,H=900; let p='';
  for(let x=0;x<=W;x+=80){ const o=(x/W*0.5+0.1).toFixed(2); p+=`<line x1="${x}" y1="0" x2="${x}" y2="${H}" stroke="rgba(255,255,255,${x%240===0?0.12:0.05})" stroke-width="1"/>`; }
  for(let y=0;y<=H;y+=80){ p+=`<line x1="0" y1="${y}" x2="${W}" y2="${y}" stroke="rgba(255,255,255,${y%240===0?0.12:0.05})" stroke-width="1"/>`; }
  // a couple of diagonal 'avenues'
  p+=`<line x1="0" y1="640" x2="1600" y2="160" stroke="rgba(196,30,30,0.10)" stroke-width="2"/>`;
  p+=`<line x1="160" y1="900" x2="1280" y2="0" stroke="rgba(255,255,255,0.06)" stroke-width="1.5"/>`;
  svg.innerHTML=p;
}

/* ── Feed items (Section 4) ──────────────────────── */
SS.feed = [
  { type:'ARCHETYPE UNLOCK', pill:'FLAMETHROWER', color:'#F4C20D', icon:'flame',
    html:'Play <b>10 games</b> as a wing scorer \u2192 unlock <b>Flamethrower</b>.' },
  { type:'TIER PROMOTION', pill:'CRYSTALLINE', color:'#14B8A6', icon:'target',
    html:'Reach <b>500 XP</b> \u2192 your card evolves from <b>Satin</b> to <b>Crystalline</b>.' },
  { type:'BADGE EARNED', pill:'SPLASHER', color:'#A8DADC', icon:'ball',
    html:'3-point rate above <b>40%</b> \u2192 the <b>Splasher</b> badge attaches to your card.' },
  { type:'HEALTH SYSTEM', pill:'DECAY RISK', color:'#E02222', icon:'bolt',
    html:'Miss <b>2 weeks</b> \u2192 Shield decays and high-intensity queues gray out. Stay active.' },
  { type:'COURT MASTERY', pill:'HOME COURT', color:'#D4AF37', icon:'eye',
    html:'Play <b>20 games</b> at one court \u2192 claim the <b>Home Court</b> badge for the city to see.' },
];
const FEED_ICONS = {
  flame:'<path d="M12 2c2 5 7 7 7 13a7 7 0 0 1-14 0c0-5 5-8 7-13z"/>',
  target:'<g fill="none" stroke="currentColor" stroke-width="1.6"><circle cx="12" cy="12" r="8"/><circle cx="12" cy="12" r="3.4"/></g>',
  ball:'<g fill="none" stroke="currentColor" stroke-width="1.6"><circle cx="12" cy="12" r="8"/><path d="M4 12h16M12 4v16M6 6c4 3 4 9 0 12M18 6c-4 3-4 9 0 12"/></g>',
  bolt:'<path d="M13 2 5 14h5l-1 8 9-12h-5z"/>',
  eye:'<g fill="none" stroke="currentColor" stroke-width="1.6"><path d="M2 12s4-6 10-6 10 6 10 6-4 6-10 6-10-6-10-6z"/><circle cx="12" cy="12" r="2.6"/></g>',
};
function buildFeed(){
  const wrap = document.getElementById('feedStream');
  wrap.innerHTML = SS.feed.map(f=>`
    <div class="item">
      <span class="scan"></span>
      <div class="ic" style="color:${f.color}"><svg viewBox="0 0 24 24" fill="currentColor">${FEED_ICONS[f.icon]}</svg></div>
      <div class="body">
        <div class="tagrow"><span class="etype">${f.type}</span><span class="pill" style="color:${f.color}">${f.pill}</span></div>
        <h3>${f.html}</h3>
      </div>
    </div>`).join('');
}

/* ── Carousel (Section 5) ────────────────────────── */
SS.carHues = [];
function buildCarousel(){
  const track = document.getElementById('carTrack');
  const nav = document.getElementById('carNav');
  SS.roster.forEach((r,i)=>{
    const slide=document.createElement('div'); slide.className='cslide'; slide.dataset.i=i;
    const mount=document.createElement('div'); mount.className='cmount';
    const meta=document.createElement('div'); meta.className='cmeta';
    const arch = window.ARCHETYPES[r.archetype]||{};
    SS.carHues[i]=arch.hue||'#C41E1E';
    meta.innerHTML=`<div class="nm">${(arch.name||'').replace(/^The /,'')}</div>
      <div class="ds">${SS.archDesc[r.archetype]||''}</div>
      <div class="claim" data-scroll="#cta">Claim this archetype <span>→</span></div>`;
    slide.appendChild(mount); slide.appendChild(meta); track.appendChild(slide);
    window.mountCard(mount, { ...r, flippable:false, staticRender:true, tiltStrength:0, glowIntensity:64, glowSpread:80, rotateOnIdle:false });
    const dot=document.createElement('i'); dot.dataset.i=i; if(i===0)dot.classList.add('on'); nav.appendChild(dot);
  });
}

/* ── CTA generated card ──────────────────────────── */
SS.genCard = function(){
  const keys = Object.keys(window.ARCHETYPES);
  const k = keys[Math.floor(Math.random()*keys.length)];
  const tiers=['satin','crystalline','prismatic','celestial'];
  const t = tiers[Math.floor(Math.random()*tiers.length)];
  const holder=document.getElementById('genCard');
  holder.innerHTML='<div></div>';
  window.mountCard(holder.firstChild, {
    playerName:'rookie_'+Math.floor(Math.random()*900+100), archetype:k, tier:t,
    xpProgress:Math.random()*.4, xp:Math.floor(Math.random()*8000),
    stats:{record:'0-0',offRtg:'\u2014',defRtg:'\u2014'},
    rotateOnIdle:true, tiltStrength:12, glowIntensity:72, glowSpread:100,
  });
  return { k, t };
};

/* ── Build everything ────────────────────────────── */
SS.buildAll = function(){
  buildVoid(); buildDeep(); buildMapGrid(); buildFeed(); buildCarousel();
  window.dispatchEvent(new CustomEvent('ss-cards-ready'));
};

if(window.React && window.ReactDOM){ SS.buildAll(); }
else window.addEventListener('DOMContentLoaded', SS.buildAll);
