/* depth.jsx — shared dimensional primitives for the Arbiter V3 board.
   Exports: Shards, ACore, BrandMark, Arrow, Divider, Callout. */

// seeded PRNG so shard layouts are stable across renders
function mulberry(seed){return function(){let t=(seed+=0x6D2B79F5);t=Math.imul(t^t>>>15,t|1);t^=t+Math.imul(t^t>>>7,t|61);return((t^t>>>14)>>>0)/4294967296;};}

// ---- shard glyphs (3 forms for variety) ----
function shardSVG(form, gid, rnd){
  if(form==='glass'){
    const p=`${4+rnd()*6},${2+rnd()*4} ${30+rnd()*8},${8+rnd()*6} ${22+rnd()*8},${30+rnd()*8} ${2+rnd()*5},${22+rnd()*6}`;
    return (
      <svg viewBox="0 0 40 40">
        <polygon points={p} fill="rgba(31,195,167,0.10)" stroke="#1fc3a7" strokeWidth="1.1"/>
        <polygon points={p} fill="none" stroke="rgba(255,255,255,0.5)" strokeWidth="0.5" transform="translate(-0.6,-0.6)"/>
      </svg>
    );
  }
  if(form==='lit'){
    const cx=15+rnd()*6, cy=14+rnd()*6;
    return (
      <svg viewBox="0 0 40 40">
        <defs>
          <radialGradient id={gid} cx="34%" cy="30%" r="75%">
            <stop offset="0" stopColor="#dff3ee"/>
            <stop offset="0.45" stopColor="#7f9b97"/>
            <stop offset="1" stopColor="#3a4847"/>
          </radialGradient>
        </defs>
        <polygon points={`${cx},3 32,12 34,27 20,36 6,28 4,13`} fill={`url(#${gid})`}/>
        <ellipse cx="14" cy="12" rx="4" ry="2.6" fill="rgba(255,255,255,0.45)"/>
      </svg>
    );
  }
  // flat matte gray
  const g=['#8a8f92','#9a9fa2','#7c8184','#b8bcbe'][Math.floor(rnd()*4)];
  const p=`${5+rnd()*7},${3+rnd()*5} ${28+rnd()*9},${6+rnd()*7} ${20+rnd()*9},${31+rnd()*7}`;
  return (<svg viewBox="0 0 40 40"><polygon points={p} fill={g}/></svg>);
}

// ---- parallax shard field ----
// zone: 'full' | 'inflow' (stream toward right) ; density scales count.
function Shards({seed=7, count=14, zone='full', region=[0,0,100,100], intensity=60}){
  const rnd=React.useMemo(()=>mulberry(seed),[seed]);
  const items=React.useMemo(()=>{
    const speedK=1+(intensity-50)/90;           // higher intensity => shorter durations
    const [rx,ry,rw,rh]=region;
    return Array.from({length:count}).map((_,i)=>{
      const r=rnd();
      const depth=r<0.45?'far':r<0.78?'mid':'near';
      const base=depth==='near'?44:depth==='mid'?30:18;
      const size=base+rnd()*base*0.7;
      const form=rnd()<0.4?'glass':rnd()<0.7?'lit':'flat';
      const left=rx+rnd()*rw, top=ry+rnd()*rh;
      const baseDur=(depth==='near'?16:depth==='mid'?11:7);
      const dur=(baseDur/speedK)*(0.8+rnd()*0.5);
      const dx=(zone==='inflow'?160+rnd()*180:(rnd()*44-22));
      const dy=(zone==='inflow'?(rnd()*30-15):(rnd()*36-18));
      const rot=(rnd()*70-35)*(zone==='inflow'?2.4:1);
      return {i,depth,size,form,left,top,dur,delay:-rnd()*dur,dx,dy,rot,gid:`shg-${seed}-${i}`,
        o:(depth==='near'?0.85:depth==='mid'?0.6:0.34)};
    });
  },[rnd,count,zone,region,intensity]);
  return (
    <div className="shardfield" aria-hidden="true">
      {items.map(s=>(
        <div key={s.i} className={`shard ${zone==='inflow'?'shard-in':''} ${s.depth}`}
          style={{left:`${s.left}%`,top:`${s.top}%`,width:s.size,height:s.size,
            '--dur':`${s.dur}s`,'--delay':`${s.delay}s`,'--dx':`${s.dx}px`,'--dy':`${s.dy}px`,'--rot':`${s.rot}deg`,'--o':s.o}}>
          {shardSVG(s.form,s.gid,mulberry(s.i*97+seed))}
        </div>
      ))}
    </div>
  );
}

// ---- dimensional Arbiter "A" core (extruded + glow halo + glass face) ----
const A_PATH="M60 14 L22 106 L42 106 L60 60 L78 106 L98 106 Z";
let _acoreN=0;
function ACore({size=120, depth=8, glass=true}){
  const uid=React.useMemo(()=>`ac${_acoreN++}`,[]);
  const layers=Array.from({length:depth});
  return (
    <div className="acore" style={{width:size,height:size}}>
      <div className="glowhalo"></div>
      {layers.map((_,k)=>{
        const t=(depth-k);
        const shade=`hsl(170 70% ${14+k*2}%)`;
        return (
          <svg key={k} className="layer" viewBox="0 0 120 120"
            style={{transform:`translate(${t*0.5}px, ${t*1.05}px)`,zIndex:1}}>
            <path d={A_PATH} fill={shade}/>
          </svg>
        );
      })}
      <svg className="face" viewBox="0 0 120 120">
        <defs>
          <linearGradient id={`${uid}f`} x1="0" y1="0" x2="0.25" y2="1">
            <stop offset="0" stopColor="#6ff0d8"/>
            <stop offset="0.5" stopColor="#1fc3a7"/>
            <stop offset="1" stopColor="#0b6457"/>
          </linearGradient>
          <clipPath id={`${uid}c`}><path d={A_PATH}/></clipPath>
        </defs>
        <path d={A_PATH} fill={`url(#${uid}f)`}/>
        {/* left-edge bevel highlight */}
        <path d="M60 14 L22 106 L30 106 L60 32 Z" fill="rgba(255,255,255,0.35)"/>
        {glass &&
          <g clipPath={`url(#${uid}c)`}>
            <rect x="-60" y="-30" width="60" height="200" fill="rgba(255,255,255,0.5)" transform="rotate(12 60 60)">
              <animate attributeName="x" values="-70;150;150" dur="5.5s" repeatCount="indefinite"/>
            </rect>
          </g>}
        <path d={A_PATH} fill="none" stroke="rgba(255,255,255,0.4)" strokeWidth="1"/>
      </svg>
    </div>
  );
}

// flat brand mark for nav/footer
function BrandMark({size=26, glow=true, color="#1fc3a7"}){
  return (<svg width={size} height={size} viewBox="0 0 120 120" fill="none" style={glow?{filter:"drop-shadow(0 0 6px rgba(31,195,167,.6))"}:null}>
    <path d={A_PATH} fill={color}/></svg>);
}

function Arrow({w=16}){return(<svg viewBox="0 0 16 16" width={w} height={w} fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M3 8h10M9 4l4 4-4 4"/></svg>);}

// data-stream divider with traveling packet
function Divider({dark=false}){
  return (
    <div className="divider" aria-hidden="true">
      <svg viewBox="0 0 1200 4" preserveAspectRatio="none">
        <line x1="0" y1="2" x2="1200" y2="2" stroke={dark?"rgba(31,195,167,.3)":"var(--teal)"} strokeWidth="1" opacity={dark?".4":".18"}/>
        <circle r="3" fill={dark?"#1fc3a7":"var(--teal)"}>
          <animateMotion dur="4s" repeatCount="indefinite" path="M0 2 L1200 2"/>
        </circle>
      </svg>
    </div>
  );
}

// floating liquid-glass data callout
function Callout({label, value, sub, style}){
  return (
    <div className="lg-dark" style={{borderRadius:12,padding:'.7rem .9rem',position:'absolute',...style}}>
      <div style={{fontFamily:"'Geist Mono',monospace",fontSize:'.56rem',letterSpacing:'.06em',textTransform:'uppercase',color:'var(--teal-bright)',marginBottom:'.2rem',position:'relative',zIndex:2}}>{label}</div>
      <div style={{fontSize:'1.35rem',fontWeight:600,color:'#f4f7f6',letterSpacing:'-.02em',position:'relative',zIndex:2,fontVariantNumeric:'tabular-nums'}}>{value}</div>
      {sub&&<div style={{fontSize:'.6rem',color:'rgba(238,242,241,.6)',marginTop:'.15rem',position:'relative',zIndex:2}}>{sub}</div>}
    </div>
  );
}

// ---- gravity shard field: asteroids pulled into a target point (the A) ----
function GravityShards({count=22, target=[46,50], seed=7, intensity=60}){
  const ref=React.useRef(null);
  const [dim,setDim]=React.useState({w:1240,h:720});
  React.useEffect(()=>{
    const el=ref.current; if(!el) return;
    const measure=()=>{const w=el.offsetWidth,h=el.offsetHeight; if(w&&h) setDim({w,h});};
    measure();
    let ro; if('ResizeObserver' in window){ ro=new ResizeObserver(measure); ro.observe(el); }
    window.addEventListener('resize',measure);
    return ()=>{ if(ro) ro.disconnect(); window.removeEventListener('resize',measure); };
  },[]);
  const rnd=React.useMemo(()=>mulberry(seed),[seed]);
  const items=React.useMemo(()=>{
    const speedK=1+(intensity-50)/90;
    return Array.from({length:count}).map((_,i)=>{
      const r=rnd();
      const depth=r<0.45?'far':r<0.78?'mid':'near';
      const base=depth==='near'?46:depth==='mid'?30:18;
      const size=base+rnd()*base*0.6;
      const form=rnd()<0.45?'glass':rnd()<0.72?'lit':'flat';
      let sx=-10+rnd()*50;
      // carve a clear horizontal channel for the headline: shards spawning over the
      // left (where the headline lives) are pushed into the upper / lower bands.
      let sy;
      if(sx<42){ sy = rnd()<0.5 ? (3+rnd()*23) : (74+rnd()*23); }
      else { sy = 16+rnd()*68; }
      const baseDur=(depth==='near'?13:depth==='mid'?10:7.5)/speedK;
      const dur=baseDur*(0.85+rnd()*0.4);
      return {i,depth,size,form,sx,sy,dur,delay:-rnd()*dur,gid:`gs-${seed}-${i}`,
        o:(depth==='near'?0.92:depth==='mid'?0.6:0.32),rot:(rnd()*140-70)};
    });
  },[rnd,count,intensity]);
  const tx=target[0]/100*dim.w, ty=target[1]/100*dim.h;
  return (
    <div className="gravityfield" ref={ref} aria-hidden="true">
      {items.map(s=>{
        const spawnX=s.sx/100*dim.w, spawnY=s.sy/100*dim.h;
        return (
          <div key={s.i} className={`gshard ${s.depth}`}
            style={{left:`${s.sx}%`,top:`${s.sy}%`,width:s.size,height:s.size,
              '--gtx':`${tx-spawnX}px`,'--gty':`${ty-spawnY}px`,'--gdur':`${s.dur}s`,
              '--gdelay':`${s.delay}s`,'--go':s.o,'--grot':`${s.rot}deg`}}>
            {shardSVG(s.form,s.gid,mulberry(s.i*131+seed))}
          </div>
        );
      })}
    </div>
  );
}

// single glass shard — green outline, faint teal fill, specular edge (sense of weight)
function GlassShard({gid, rnd}){
  const a=`${4+rnd()*5},${3+rnd()*4}`, b=`${28+rnd()*8},${6+rnd()*5}`, c=`${23+rnd()*7},${30+rnd()*6}`, d=`${3+rnd()*5},${22+rnd()*6}`;
  const pts=`${a} ${b} ${c} ${d}`;
  return (
    <svg viewBox="0 0 40 40">
      <defs><linearGradient id={gid} x1="0" y1="0" x2="1" y2="1">
        <stop offset="0" stopColor="rgba(31,195,167,0.24)"/>
        <stop offset="0.6" stopColor="rgba(31,195,167,0.09)"/>
        <stop offset="1" stopColor="rgba(20,40,38,0.10)"/>
      </linearGradient></defs>
      <polygon points={pts} fill={`url(#${gid})`} stroke="#1fc3a7" strokeWidth="1.1" strokeLinejoin="round"/>
      <polygon points={pts} fill="none" stroke="rgba(190,255,240,0.5)" strokeWidth="0.5" strokeLinejoin="round" transform="translate(-0.4,-0.5)"/>
    </svg>
  );
}

// converging triangular river: wide at the off-frame left, narrowing into the apex (the A)
function GravityRiver({lanes=8, perLane=5, apex=[46,50], sizeMin=15, sizeMax=34, speed=1, seed=3, weight='mid'}){
  const ref=React.useRef(null);
  const [dim,setDim]=React.useState({w:1240,h:720});
  React.useEffect(()=>{ const el=ref.current; if(!el)return;
    const m=()=>{const w=el.offsetWidth,h=el.offsetHeight; if(w&&h)setDim({w,h});};
    m(); let ro; if('ResizeObserver' in window){ro=new ResizeObserver(m);ro.observe(el);} window.addEventListener('resize',m);
    return ()=>{if(ro)ro.disconnect();window.removeEventListener('resize',m);}; },[]);
  const rnd=React.useMemo(()=>mulberry(seed),[seed]);
  const items=React.useMemo(()=>{
    const out=[]; const topY=8, botY=92;
    for(let l=0;l<lanes;l++){
      const laneY = topY + (botY-topY)*(l/(lanes-1));
      const baseDur = (10/speed) * (0.9 + (l%2)*0.05);
      for(let k=0;k<perLane;k++){
        const jY = laneY + (rnd()*5-2.5);
        const sx = -6 - rnd()*9;
        const size = sizeMin + rnd()*(sizeMax-sizeMin);
        const dur = baseDur*(0.92+rnd()*0.16);
        const delay = -((k/perLane)*dur) - rnd()*0.35;
        const rot = rnd()*26-13;
        out.push({id:`${l}-${k}`, sx, sy:jY, size, dur, delay, rot, gid:`rg-${seed}-${l}-${k}`, prng:mulberry(l*53+k*7+seed)});
      }
    }
    return out;
  },[rnd,lanes,perLane,sizeMin,sizeMax,speed,seed]);
  const tx=apex[0]/100*dim.w, ty=apex[1]/100*dim.h;
  const wclass = weight==='near'?'w-near':weight==='far'?'w-far':'w-mid';
  return (
    <div className="gravityfield" ref={ref} aria-hidden="true">
      {items.map(s=>{
        const spawnX=s.sx/100*dim.w, spawnY=s.sy/100*dim.h;
        return (
          <div key={s.id} className={`rshard ${wclass}`}
            style={{left:`${s.sx}%`,top:`${s.sy}%`,width:s.size,height:s.size,
              '--gtx':`${tx-spawnX}px`,'--gty':`${ty-spawnY}px`,'--gdur':`${s.dur}s`,'--gdelay':`${s.delay}s`,'--go':0.85,'--grot':`${s.rot}deg`}}>
            <GlassShard gid={s.gid} rnd={s.prng}/>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window,{Shards,GravityShards,GravityRiver,GlassShard,ACore,BrandMark,Arrow,Divider,Callout});
