if (window.CSX_EARN_LIVE === undefined) window.CSX_EARN_LIVE = true;
/* Shared chrome: Nav, Ticker, Footer, Wordmark, helpers. Exposes to window. */

const CSX_API = 'https://api.treeofwally.com/api/v1/public';
const CSX_PUBLIC_BOARDS = ['nba', 'nfl', 'newsmakers', 'podcasts'];
const CSX_TEAM_COLORS = {"76ers":["#006BB6","#ED174C"],"Bucks":["#00471B","#EEE1C6"],"Cavaliers":["#860038","#FDBB30"],"Celtics":["#007A33","#BA9653"],"Clippers":["#C8102E","#1D428A"],"Grizzlies":["#5D76A9","#12173F"],"Heat":["#98002E","#F9A01B"],"Jazz":["#002B5C","#F9A01B"],"Knicks":["#F58426","#006BB6"],"Lakers":["#552583","#FDB927"],"Mavericks":["#00538C","#B8C4CA"],"Nuggets":["#0E2240","#FEC524"],"Pacers":["#002D62","#FDBB30"],"Pistons":["#C8102E","#1D42BA"],"Raptors":["#CE1141","#FFFFFF"],"Rockets":["#CE1141","#C4CED4"],"Spurs":["#8A8D8F","#141414"],"Suns":["#1D1160","#E56020"],"Thunder":["#007AC1","#EF3B24"],"Timberwolves":["#0C2340","#78BE20"],"Trail Blazers":["#E03A3E","#FFFFFF"],"Warriors":["#1D428A","#FFC72C"],"Wizards":["#002B5C","#E31837"],"Kansas City Chiefs":["#E31837","#FFB81C"],"Buffalo Bills":["#00338D","#C60C30"],"Baltimore Ravens":["#241773","#9E7C0C"],"New England Patriots":["#002244","#C60C30"],"Philadelphia Eagles":["#004C54","#A5ACAF"],"San Francisco 49ers":["#AA0000","#B3995D"],"Dallas Cowboys":["#003594","#869397"],"Detroit Lions":["#0076B6","#B0B7BC"],"Miami Dolphins":["#008E97","#005778"],"Los Angeles Chargers":["#0080C6","#FFC20E"],"Cincinnati Bengals":["#FB4F14","#000000"],"Minnesota Vikings":["#4F2683","#FFC62F"],"Green Bay Packers":["#203731","#FFB612"],"Tennessee Titans":["#0C2340","#4B92DB"],"Houston Texans":["#03202F","#A71930"],"Pittsburgh Steelers":["#FFB612","#101820"],"Las Vegas Raiders":["#000000","#A5ACAF"],"Seattle Seahawks":["#002244","#69BE28"],"Denver Broncos":["#FB4F14","#002244"],"Atlanta Falcons":["#A71930","#000000"],"Jacksonville Jaguars":["#101820","#D7A22A"],"Tampa Bay Buccaneers":["#D50A0A","#FF7900"],"Los Angeles Rams":["#003594","#FFA300"],"Chicago Bears":["#0B162A","#C83803"],"New York Giants":["#0B2265","#A71930"],"New York Jets":["#125740","#000000"],"Arizona Cardinals":["#97233F","#000000"],"Carolina Panthers":["#0085CA","#101820"],"Cleveland Browns":["#311D00","#FF3C00"],"Indianapolis Colts":["#002C5F","#A2AAAD"],"New Orleans Saints":["#D3BC8D","#101820"],"Washington Commanders":["#5A1414","#FFB612"]};

async function csxJson(path) {
  const res = await fetch(`${CSX_API}/${path}`);
  if (!res.ok) throw new Error(`${path} ${res.status}`);
  const body = await res.json();
  if (body && body.success === false) throw new Error(`${path} failed`);
  return body && body.data !== undefined ? body.data : body;
}

function csxBuildMarket(ticker, overview) {
  const rate = parseFloat(overview.reference.omega_per_wally) * parseFloat(overview.reference.usd_per_omega);
  const figures = (ticker.persons || [])
    .filter(p => CSX_PUBLIC_BOARDS.includes(p.board) && p.price > 0)
    .map(p => {
      const change = p.unit_price_percentage_change || 0;
      const capUsd = p.price * 1e7 * rate;
      return { id:p.id, handle:p.username, name:`${p.first_name || ''} ${p.last_name || ''}`.trim() || p.username,
        board:p.board, price:p.price, change, capUsd, moveUsd: capUsd * change / 100,
        pool: p.house_ask_units || 0, roster: p.roster || null };
    })
    .sort((a, b) => b.capUsd - a.capUsd);
  const top50 = figures.slice(0, 50);
  const movers = top50.filter(f => f.change !== 0).sort((a, b) => Math.abs(b.moveUsd) - Math.abs(a.moveUsd)).slice(0, 6);
  const gainers = top50.filter(f => f.change > 0);
  const hero = gainers.length ? gainers.reduce((a, b) => b.moveUsd > a.moveUsd ? b : a) : figures[0];
  const open = figures.filter(f => f.pool > 0);
  const boards = new Set(figures.map(f => f.board));
  return {
    rate, figures, ticker: figures.slice(0, 16), movers, hero,
    listed: figures.length, boards: boards.size,
    capUsd: figures.reduce((s, f) => s + f.capUsd, 0),
    capWallys: figures.reduce((s, f) => s + f.price * 1e7, 0),
    ipoOpen: open.length,
    ipoPoolShares: open.reduce((s, f) => s + f.pool, 0),
    ipoPoolUsd: open.reduce((s, f) => s + f.pool * f.price, 0) * rate,
    usdPerOmega: parseFloat(overview.reference.usd_per_omega),
  };
}

let csxMarketPromise = null;
function csxMarket() {
  if (!csxMarketPromise) {
    csxMarketPromise = Promise.all([csxJson('ticker?l=500'), csxJson('exchange/overview')])
      .then(([ticker, overview]) => csxBuildMarket(ticker, overview));
  }
  return csxMarketPromise;
}

function useCSXMarket() {
  const [state, setState] = React.useState({ market:null, failed:false });
  React.useEffect(() => {
    let live = true;
    csxMarket().then(market => live && setState({ market, failed:false }), () => live && setState({ market:null, failed:true }));
    return () => { live = false; };
  }, []);
  return state;
}

async function csxPriceHistory(figure) {
  const data = await csxJson(`users/${figure.id}/price-history?period=7d`);
  return (data.points || []).map(pt => pt.price / 1e5).concat([figure.price]);
}

const csxFmt = {
  price: v => v >= 0.01 ? v.toFixed(2) : v.toFixed(5),
  change: c => `${c > 0 ? '+' : ''}${c.toFixed(2)}%`,
  usd: n => n >= 1e9 ? `$${(n / 1e9).toFixed(2)}B` : n >= 1e6 ? `$${(n / 1e6).toFixed(1)}M` : `$${Math.round(n).toLocaleString()}`,
  wallys: n => n >= 1e9 ? `ω ${(n / 1e9).toFixed(2)}B` : `ω ${(n / 1e6).toFixed(1)}M`,
  shares: n => `${(n / 1e6).toFixed(1)}M`,
  initials: f => f.name.split(' ').map(x => x[0]).join('').slice(0, 2).toUpperCase(),
};

function CSXTile({ figure, size=48, radius=10 }) {
  const roster = figure.roster;
  const colors = roster && CSX_TEAM_COLORS[roster.team];
  const jersey = colors && typeof roster.jersey === 'number';
  const base = { width:size, height:size, flexShrink:0, display:'flex', alignItems:'center', justifyContent:'center', fontWeight:700, color:'#fff' };
  if (jersey) {
    return <div style={{...base, borderRadius:radius, background:colors[0], color:colors[1], fontFamily:"'Geist Mono', monospace", fontWeight:500, fontSize:size*0.38, boxShadow:'inset 0 0 0 1px rgba(255,255,255,0.12)'}}>{roster.jersey}</div>;
  }
  return <div style={{...base, borderRadius:'50%', background:'linear-gradient(135deg, var(--purple-2), var(--green))', fontFamily:"'Fraunces', serif", fontSize:size*0.36}}>{csxFmt.initials(figure)}</div>;
}

function CSXChange({ change, size=12 }) {
  if (!change) return null;
  const up = change > 0;
  return <span className="mono" style={{fontSize:size, fontWeight:600, color: up ? 'var(--green)' : 'var(--red)', padding:'3px 8px', background: up ? 'rgba(61,208,122,0.12)' : 'rgba(239,75,92,0.12)', borderRadius:6}}>{csxFmt.change(change)}</span>;
}

function CSXSparkline({ points, change, height=70, id }) {
  if (!points || points.length < 2) return <div style={{height}}/>;
  const w = 400, min = Math.min(...points), max = Math.max(...points), range = (max - min) || 1;
  const pts = points.map((v, i) => [i / (points.length - 1) * w, 10 + (1 - (v - min) / range) * (height - 20)]);
  const d = pts.map((p, i) => `${i ? 'L' : 'M'}${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(' ');
  const color = change > 0 ? 'var(--green)' : change < 0 ? 'var(--red)' : 'var(--ink-3)';
  const last = pts[pts.length - 1];
  return (
    <svg viewBox={`0 0 ${w} ${height}`} width="100%" height={height} preserveAspectRatio="none" style={{display:'block'}}>
      <defs><linearGradient id={`csxSpark${id}`} x1="0" x2="0" y1="0" y2="1"><stop offset="0" stopColor={color} stopOpacity="0.28"/><stop offset="1" stopColor={color} stopOpacity="0"/></linearGradient></defs>
      <path d={`${d} L${w} ${height} L0 ${height} Z`} fill={`url(#csxSpark${id})`}/>
      <path d={d} fill="none" stroke={color} strokeWidth="2.5" vectorEffect="non-scaling-stroke"/>
      <circle cx={last[0]} cy={last[1]} r="3.5" fill={color}/>
    </svg>
  );
}

function CSXWordmark({ size=32 }) {
  return (
    <a href="/" className="serif" style={{fontWeight:800, fontSize:size, letterSpacing:'-0.01em', lineHeight:1, display:'inline-block'}}>
      <span style={{color:'var(--ink)'}}>C</span>
      <span style={{color:'var(--ink)'}}>S</span>
      <span style={{color:'var(--purple)'}}>X</span>
    </a>
  );
}

function useCSXIsMobile() {
  const [m, setM] = React.useState(() => window.innerWidth < 768);
  React.useEffect(() => {
    const h = () => setM(window.innerWidth < 768);
    window.addEventListener('resize', h, {passive: true});
    return () => window.removeEventListener('resize', h);
  }, []);
  return m;
}

function CSXNav({ active }) {
  const isMobile = useCSXIsMobile();
  const links = [
    { k:'how',      label:'How it works', href:'/how-it-works.html' },
    { k:'wallys',   label:'Wallys',       href:'/wallys.html' },
    { k:'creators', label:'Creators',     href:'/creators.html' },
    ...(window.CSX_EARN_LIVE ? [{ k:'earn', label:'Earn', href:'/earn.html' }] : []),
  ];
  const linkStyle = (l) => ({
    color: active===l.k ? 'var(--ink)' : 'var(--ink-2)',
    borderBottom: active===l.k ? '1px solid var(--purple)' : '1px solid transparent',
    paddingBottom:4, whiteSpace:'nowrap',
  });
  const enterStyle = {
    padding: isMobile ? '10px 18px' : '10px 22px', background:'var(--purple-2)', color:'#fff', fontSize:13, borderRadius:8, fontWeight:700, display:'inline-block',
    boxShadow:'0 0 0 1px rgba(167,139,250,0.5), 0 8px 24px rgba(124,92,255,0.35)', whiteSpace:'nowrap',
  };
  return (
    <nav style={{
      borderBottom:'1px solid var(--line)',
      background:'rgba(10,10,20,0.85)', backdropFilter:'blur(10px)',
      position:'sticky', top:0, zIndex:50,
    }}>
      <div style={{
        display:'flex', alignItems:'center', justifyContent:'space-between',
        padding: isMobile ? '14px 20px' : '18px 36px',
      }}>
        <div style={{display:'flex', alignItems:'center', gap:40}}>
          <CSXWordmark size={isMobile ? 26 : 28}/>
          {!isMobile && (
            <div style={{display:'flex', gap:26, fontSize:13.5, fontWeight:500}}>
              {links.map(l => <a key={l.k} href={l.href} style={linkStyle(l)}>{l.label}</a>)}
            </div>
          )}
        </div>
        <div style={{display:'flex', alignItems:'center', gap:14}}>
          {!isMobile && (
            <a href="https://app.creatorstockx.com/" style={{padding:'10px 16px', background:'transparent', border:'1px solid var(--line-2)', color:'var(--ink)', fontSize:13, borderRadius:8, fontWeight:500, whiteSpace:'nowrap'}}>Log in</a>
          )}
          <a href="https://app.creatorstockx.com/" style={enterStyle}>Enter CSX →</a>
        </div>
      </div>
      {isMobile && (
        <div style={{display:'flex', gap:22, fontSize:13, fontWeight:500, padding:'0 20px 12px', overflowX:'auto', scrollbarWidth:'none'}}>
          {links.map(l => <a key={l.k} href={l.href} style={linkStyle(l)}>{l.label}</a>)}
        </div>
      )}
    </nav>
  );
}

function CSXTicker() {
  const { market, failed } = useCSXMarket();
  const strip = { background:'var(--bg-2)', borderTop:'1px solid var(--line)', borderBottom:'1px solid var(--line)', overflow:'hidden', whiteSpace:'nowrap', padding:'10px 0' };
  if (!market) {
    return <div style={strip}><span className="mono" style={{fontSize:12, letterSpacing:'0.04em', color:'var(--ink-3)', paddingLeft:40}}>{failed ? 'Market data unavailable' : 'Loading the market…'}</span></div>;
  }
  const items = [...market.ticker, ...market.ticker];
  return (
    <div style={strip}>
      <div style={{display:'inline-flex', gap:40, animation:'tickerScroll 80s linear infinite', paddingLeft:40}}>
        {items.map((f, i) => (
          <span key={i} className="mono" style={{fontSize:12, letterSpacing:'0.04em'}}>
            <span style={{color:'var(--ink-2)'}}>{f.handle}</span>
            <span style={{color:'var(--wally)', margin:'0 8px'}}>ω</span>
            <span style={{color:'var(--ink)', fontWeight:500}}>{csxFmt.price(f.price)}</span>
            {f.change !== 0 && <span style={{marginLeft:10, color: f.change > 0 ? 'var(--green)' : 'var(--red)'}}>{csxFmt.change(f.change)}</span>}
          </span>
        ))}
      </div>
    </div>
  );
}

function CSXFooter() {
  const isMobile = useCSXIsMobile();
  const cols = [
    { t:'Product',  items:[['Explore','/'],['Wallys','/wallys.html'],['Holdings','https://app.creatorstockx.com/']] },
    { t:'Creators', items:[['Claim your stock','/creators.html'],['Grow your market','/creators.html'],['Creator docs','#'],['Partner program','#']] },
    { t:'Brands',   items:[['Join the network','#'],['Redemption API','#'],['Case studies','#'],['Contact sales','#']] },
    { t:'Company',  items:[['About','#'],['Journal','#'],['Careers','#'],['Press kit','#'],['Privacy','#']] },
  ];
  return (
    <footer style={{background:'var(--bg-2)', borderTop:'1px solid var(--line)', padding: isMobile ? '40px 20px 28px' : '56px 36px 36px'}}>
      <div style={{maxWidth:1200, margin:'0 auto', display:'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : '1.5fr 1fr 1fr 1fr 1fr', gap: isMobile ? 28 : 40, marginBottom:40}}>
        <div style={{gridColumn: isMobile ? '1 / -1' : 'auto'}}>
          <CSXWordmark size={30}/>
          <p className="italic" style={{fontSize:17, color:'var(--ink-2)', marginTop:16, lineHeight:1.4, maxWidth:280}}>
            A loyalty-driven stock market that turns every person into an investable stock.
          </p>
        </div>
        {cols.map(col => (
          <div key={col.t}>
            <div className="mono" style={{fontSize:10, letterSpacing:'0.28em', textTransform:'uppercase', color:'var(--purple)', marginBottom:14}}>{col.t}</div>
            <div style={{display:'flex', flexDirection:'column', gap:10, fontSize:13.5, color:'var(--ink-2)'}}>
              {col.items.map(([label, href]) => <a key={label} href={href} style={{color:'var(--ink-2)'}}>{label}</a>)}
            </div>
          </div>
        ))}
      </div>
      <div style={{maxWidth:1200, margin:'0 auto', display:'flex', justifyContent:'flex-start', alignItems:'center', paddingTop:24, borderTop:'1px solid var(--line)', flexWrap:'wrap', gap:16}}>
        <span className="mono" style={{fontSize:10, letterSpacing:'0.22em', textTransform:'uppercase', color:'var(--ink-3)'}}>© 2026 CreatorStockX · creatorstockx.com</span>
      </div>
    </footer>
  );
}

function CSXEyebrow({ children, align='left' }) {
  return (
    <div className="mono" style={{fontSize:11, letterSpacing:'0.3em', textTransform:'uppercase', color:'var(--purple)', marginBottom:16, textAlign:align}}>
      {children}
    </div>
  );
}

Object.assign(window, { csxMarket, useCSXMarket, csxPriceHistory, csxFmt, CSXTile, CSXChange, CSXSparkline, CSXWordmark, CSXNav, CSXTicker, CSXFooter, CSXEyebrow });
