// ── Trading View ──────────────────────────────────────────────
const { useState: useStT, useEffect: useEfT, useRef: useRfT } = React;
const CT = window.SC;
const ELY_BLUE_T = '#5CC8E6';

const tradingStyle = document.createElement('style');
tradingStyle.textContent = `
  @keyframes slideInFromRight {
    from { transform: translateX(100%); opacity: 0; }
    to   { transform: translateX(0);    opacity: 1; }
  }
`;
if (!document.getElementById('trading-style')) {
  tradingStyle.id = 'trading-style';
  document.head.appendChild(tradingStyle);
}

// Live chart — static, hover crosshair reveals values
function LiveChart({ market, isMobile }) {
  window.useMarketDrift();
  const W = 520, H = isMobile ? 195 : 150, pad = { t:10, r:44, b:24, l:10 };
  const cW = W - pad.l - pad.r, cH = H - pad.t - pad.b;

  const buildSeries = (baseSeries) => baseSeries.map(s => {
    const base = [...s.data];
    while (base.length < 60) {
      const last = base[base.length - 1];
      const d = (Math.random() * 1.2 - 0.55);
      base.push(Math.max(2, Math.min(98, +(last + d).toFixed(1))));
    }
    return { ...s, data: base.slice(-60) };
  });

  const baseSeries = market.chartSeries || [{ label:'Probability', color: CT.blue, data: Array(30).fill(0).map((_,i) => 33 + Math.sin(i/4)*6) }];
  const [series] = useStT(() => buildSeries(baseSeries));
  const [hoverIdx, setHoverIdx] = useStT(null);

  const drift = window.MARKET_PROB[market.id] || {};

  const allVals = series.flatMap(s => s.data);
  const minY = Math.max(0, Math.min(...allVals) - 4);
  const maxY = Math.min(100, Math.max(...allVals) + 6);
  const n = series[0]?.data.length || 1;
  const toX = i => pad.l + (i / (n - 1)) * cW;
  const toY = v => pad.t + cH - ((v - minY) / (maxY - minY)) * cH;
  const makePath = data => data.map((v, i) => `${i===0?'M':'L'}${toX(i).toFixed(1)},${toY(v).toFixed(1)}`).join(' ');
  const areaPath = data => `${makePath(data)} L${toX(n-1)},${H-pad.b} L${toX(0)},${H-pad.b} Z`;

  // Grid lines at each outcome's live drifted value, colored by series
  const outcomeGrids = series.map((s, i) => {
    const val = drift.outcomes?.[i] != null ? drift.outcomes[i]
      : (s.data.length > 0 ? s.data[s.data.length - 1] : 0);
    return { val: Math.round(val), color: s.color };
  });
  const primary = series[0];
  const displayIdx = hoverIdx !== null ? hoverIdx : n - 1;
  const primaryVal = primary?.data[displayIdx] ?? 0;
  const prevVal = primary?.data[Math.max(0, displayIdx - 1)] ?? primaryVal;
  const endColor = primaryVal >= prevVal ? CT.green : CT.red;

  const handleMouseMove = (e) => {
    const rect = e.currentTarget.getBoundingClientRect();
    const svgX = (e.clientX - rect.left) / rect.width * W;
    const idx = Math.max(0, Math.min(n - 1, Math.round((svgX - pad.l) / cW * (n - 1))));
    setHoverIdx(idx);
  };

  return (
    <div style={{ position: 'relative', width: '100%' }}>
      <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', display: 'block', cursor: 'crosshair', touchAction: 'none' }}
        onMouseMove={handleMouseMove}
        onMouseLeave={() => setHoverIdx(null)}
        onTouchMove={(e) => { e.preventDefault(); const touch = e.touches[0]; const rect = e.currentTarget.getBoundingClientRect(); const svgX = (touch.clientX - rect.left) / rect.width * W; const idx = Math.max(0, Math.min(n-1, Math.round((svgX - pad.l) / cW * (n-1)))); setHoverIdx(idx); }}
        onTouchEnd={() => setHoverIdx(null)}>
        <defs>
          {series.map((s, i) => (
            <linearGradient key={i} id={`liveGrad${i}`} x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor={s.color} stopOpacity={i === 0 ? "0.22" : "0.10"} />
              <stop offset="90%" stopColor={s.color} stopOpacity="0" />
            </linearGradient>
          ))}
          {series.map((s, i) => {
            const r = i === 0 ? 8 : 6;
            const cx = toX(displayIdx);
            const cy = toY(s.data[displayIdx]);
            return (
              <clipPath key={`clip${i}`} id={`imgClip${i}`}>
                <circle cx={cx} cy={cy} r={r} />
              </clipPath>
            );
          })}
          {series.map((s, i) => {
            const outcomeImg = market.outcomes?.[i]?.img;
            if (!outcomeImg) return null;
            return (
              <pattern key={`tpat${i}`} id={`tooltipPat${i}`}
                patternUnits="objectBoundingBox" patternContentUnits="objectBoundingBox"
                width="1" height="1">
                <image href={outcomeImg} x="0" y="0" width="1" height="1" preserveAspectRatio="xMidYMid slice"/>
              </pattern>
            );
          })}
        </defs>

        {outcomeGrids.map(({val, color}, i) => {
          const vy = toY(val);
          if (vy < pad.t - 2 || vy > H - pad.b + 2) return null;
          return (
            <g key={i}>
              <line x1={pad.l} y1={vy} x2={W-pad.r} y2={vy}
                stroke={color} strokeWidth={1} strokeDasharray="3,4" strokeOpacity={0.30} />
              <text x={W-pad.r+5} y={vy+3.5}
                fill={color} fontSize={8.5} opacity={0.75}
                fontFamily="JetBrains Mono, monospace">{val}%</text>
            </g>
          );
        })}

        {series.map((s, i) => (
          <path key={`area${i}`} d={areaPath(s.data)} fill={`url(#liveGrad${i})`} />
        ))}

        {series.map((s, i) => (
          <path key={`line${i}`}
            d={makePath(s.data)}
            stroke={s.color}
            strokeWidth={i === 0 ? 1.8 : 1.2}
            fill="none"
            strokeLinejoin="round"
            strokeLinecap="round"
            opacity={i === 0 ? 1 : 0.6}
          />
        ))}

        {hoverIdx !== null && (
          <line
            x1={toX(hoverIdx)} y1={pad.t}
            x2={toX(hoverIdx)} y2={H - pad.b}
            stroke="rgba(255,255,255,0.2)" strokeWidth={1} strokeDasharray="3,4"
          />
        )}

        {series.map((s, i) => {
          const cx = toX(displayIdx);
          const cy = toY(s.data[displayIdx]);
          const color = i === 0 ? endColor : s.color;
          const r = i === 0 ? 8 : 6;
          const outcomeImg = market.outcomes?.[i]?.img;
          return (
            <g key={`end${i}`}>
              <circle cx={cx} cy={cy} r={r + 1.5} fill="#0C0C12" />
              <circle cx={cx} cy={cy} r={r} fill={color} />
              {outcomeImg && (
                <image href={outcomeImg} x={cx - r} y={cy - r} width={r * 2} height={r * 2}
                  clipPath={`url(#imgClip${i})`} preserveAspectRatio="xMidYMid slice" />
              )}
              {i === 0 && hoverIdx === null && (
                <circle cx={cx} cy={cy} r={r + 5} fill="none"
                  stroke={color} strokeOpacity={0.35} strokeWidth={1}>
                  <animate attributeName="r" values={`${r};${r + 9};${r}`} dur="1.8s" repeatCount="indefinite" />
                  <animate attributeName="stroke-opacity" values="0.5;0;0.5" dur="1.8s" repeatCount="indefinite" />
                </circle>
              )}
            </g>
          );
        })}

        {hoverIdx !== null && (() => {
          const cx = toX(hoverIdx);
          const boxW = 120;
          const boxH = 10 + series.length * 14;
          const bx = cx + boxW + 10 > W - pad.r ? cx - boxW - 6 : cx + 6;
          const topDataVal = Math.max(...series.map(s => s.data[hoverIdx] || 0));
          const by = Math.max(pad.t, Math.min(toY(topDataVal) - 6, H - pad.b - boxH));
          return (
            <g>
              <rect x={bx} y={by} width={boxW} height={boxH} rx={4}
                fill="rgba(8,8,14,0.92)" stroke="rgba(255,255,255,0.09)" strokeWidth={0.5}/>
              {series.map((s, i) => {
                const val = s.data[hoverIdx];
                if (val == null) return null;
                const color = i === 0 ? endColor : s.color;
                const cy = by + 6 + i * 14 + 4;
                const hasImg = !!market.outcomes?.[i]?.img;
                return (
                  <g key={i}>
                    {hasImg ? (
                      <>
                        <circle cx={bx + 8} cy={cy} r={5} fill={`url(#tooltipPat${i})`}/>
                        <circle cx={bx + 8} cy={cy} r={5} fill="none" stroke={color} strokeWidth={0.8} strokeOpacity={0.7}/>
                      </>
                    ) : (
                      <circle cx={bx + 8} cy={cy} r={3} fill={color}/>
                    )}
                    <text x={bx + (hasImg ? 19 : 16)} y={cy + 4}
                      fill="rgba(255,255,255,0.6)" fontSize={7.5}
                      fontFamily="JetBrains Mono, monospace">{s.label}</text>
                    <text x={bx + boxW - 4} y={cy + 4}
                      textAnchor="end" fill={color} fontSize={8} fontWeight={700}
                      fontFamily="JetBrains Mono, monospace"
                      style={{ fontVariantNumeric: 'tabular-nums' }}>
                      {val.toFixed(1)}%
                    </text>
                  </g>
                );
              })}
            </g>
          );
        })()}
        {hoverIdx === null && primary && (() => {
          const lastVal = primary.data[n - 1];
          const cx = toX(n - 1);
          const cy = toY(lastVal);
          const labelX = Math.min(cx, W - pad.r - 20);
          return (
            <g>
              <rect x={labelX - 20} y={cy - 16} width={40} height={14}
                rx={3} fill="rgba(12,12,18,0.9)" stroke={endColor} strokeOpacity={0.4} strokeWidth={0.5} />
              <text x={labelX} y={cy - 6}
                textAnchor="middle" fill={endColor}
                fontSize={8.5} fontWeight={700}
                fontFamily="JetBrains Mono, monospace"
                style={{ fontVariantNumeric: 'tabular-nums' }}>
                {lastVal.toFixed(1)}%
              </text>
            </g>
          );
        })()}
      </svg>

      <div style={{ position: 'absolute', top: 8, left: 10, display: 'flex', alignItems: 'center', gap: 5 }}>
        <span style={{
          width: 5, height: 5, borderRadius: '50%',
          background: ELY_BLUE_T, boxShadow: `0 0 6px ${ELY_BLUE_T}`,
          animation: 'pulse 1.4s ease-in-out infinite', display: 'block',
        }} />
        <span className="mono" style={{
          fontSize: 8.5, color: ELY_BLUE_T,
          letterSpacing: '1.4px', fontWeight: 600, textTransform: 'uppercase',
        }}>Live</span>
      </div>
    </div>
  );
}

function TradePanel({ market, selectedOutcome, side, setSide, isMobile }) {
  const [amount, setAmount] = useStT('3690');
  const [leverage, setLeverage] = useStT(2);
  const [buyState, setBuyState] = useStT('idle'); // idle, processing, executed
  const [recTab, setRecTab] = useStT('Favorites');
  const [showWaitlistStrip, setShowWaitlistStrip] = useStT(false);

  const drift = window.MARKET_PROB[market.id] || {};
  const outcomeIndex = market.outcomes ? market.outcomes.indexOf(selectedOutcome) : 0;
  const idx = outcomeIndex < 0 ? 0 : outcomeIndex;
  const driftedPct = drift.outcomes?.[idx] != null ? drift.outcomes[idx] : (drift.pct != null ? drift.pct : (selectedOutcome?.pct||33));
  const pct = side==='yes' ? driftedPct : 100 - driftedPct;
  const FEE = 0.025;
  const amt = parseFloat(amount) || 0;
  const position = amt * leverage;
  const price = Math.max(0.01, pct / 100);
  const shares = amt > 0 ? Math.floor(position * (1 - FEE) / price) : 0;
  const payout = shares;
  const profit = payout - amt;

  const handleBuy = () => {
    setBuyState('processing');
    setTimeout(() => {
      setBuyState('executed');
      setTimeout(() => {
        setBuyState('idle');
        setShowWaitlistStrip(true);
      }, 1200);
    }, 600);
  };

  useEfT(() => {
    if (!showWaitlistStrip) return;
    const t = setTimeout(() => setShowWaitlistStrip(false), 4500);
    return () => clearTimeout(t);
  }, [showWaitlistStrip]);

  const p = isMobile ? '0 10px' : '0 12px'; // horizontal padding shorthand
  return (
    <div style={isMobile
      ? {width:'100%',flex:'1 0 auto',background:CT.appBg,borderLeft:'none',borderTop:`1px solid ${CT.border}`,
          display:'flex',flexDirection:'column',overflow:'hidden',position:'relative'}
      : {width:250,flexShrink:0,background:CT.appBg,borderLeft:`1px solid ${CT.border}`,
          display:'flex',flexDirection:'column',overflow:'hidden',position:'relative'}}>
      <div style={{padding:isMobile?'5px 10px':'8px 12px',borderBottom:`1px solid ${CT.border}`,display:'flex',alignItems:'center',gap:8}}>
        {selectedOutcome?.img?<img src={selectedOutcome.img} style={{width:20,height:20,borderRadius:'50%',objectFit:'cover'}}/>
          :<window.MarketThumb market={market} size={20}/>}
        <div>
          <div className="mono" style={{fontSize:7,color:CT.muted,letterSpacing:1,textTransform:'uppercase'}}>Selected</div>
          <div style={{fontSize:10,fontWeight:700,color:'#fff',letterSpacing:'-0.01em'}}>{selectedOutcome?.name||'Yes'}</div>
        </div>
      </div>
      <div style={{padding:isMobile?'4px 10px':'6px 12px',borderBottom:`1px solid ${CT.border}`,display:'flex',alignItems:'center',justifyContent:'space-between'}}>
        <div style={{display:'flex',gap:2}}>
          {['Buy','Sell'].map(t=>(
            <button key={t} style={{padding:'3px 10px',borderRadius:5,border:'none',
              background:t==='Buy'?'rgba(255,255,255,0.08)':'none',
              color:t==='Buy'?'#fff':CT.muted,fontSize:10,fontWeight:t==='Buy'?700:500,
              cursor:'pointer',fontFamily:window.BRAND_FONT,letterSpacing:'-0.01em'}}>{t}</button>
          ))}
        </div>
        <button style={{background:'none',border:`1px solid ${CT.border}`,color:CT.muted,
          fontSize:9,padding:'2px 7px',borderRadius:5,cursor:'pointer',fontFamily:window.BRAND_FONT}}>Market</button>
      </div>
      <div style={{padding:isMobile?'5px 10px':'7px 12px',display:'flex',gap:5}}>
        <button onClick={()=>setSide('yes')}
          style={{flex:1,padding:isMobile?'5px 0':'7px 0',borderRadius:6,fontWeight:700,fontSize:11,cursor:'pointer',
            fontFamily:window.BRAND_FONT,border:`1.5px solid ${side==='yes'?CT.green:'transparent'}`,
            background:side==='yes'?'rgba(109,208,169,0.22)':CT.greenDim,color:CT.green,
            transition:'all .2s',fontVariantNumeric:'tabular-nums',letterSpacing:'-0.01em'}}>
          Yes {Math.round(driftedPct)}¢</button>
        <button onClick={()=>setSide('no')}
          style={{flex:1,padding:isMobile?'5px 0':'7px 0',borderRadius:6,fontWeight:700,fontSize:11,cursor:'pointer',
            fontFamily:window.BRAND_FONT,border:`1.5px solid ${side==='no'?CT.red:'transparent'}`,
            background:side==='no'?'rgba(229,115,115,0.22)':CT.redDim,color:CT.red,
            transition:'all .2s',fontVariantNumeric:'tabular-nums',letterSpacing:'-0.01em'}}>
          No {100-Math.round(driftedPct)}¢</button>
      </div>
      <div style={{padding:isMobile?`0 10px 5px`:' 0 12px 7px'}}>
        <div className="mono" style={{fontSize:7,color:CT.muted,marginBottom:3,letterSpacing:1,textTransform:'uppercase'}}>Amount</div>
        <div style={{background:'rgba(255,255,255,0.03)',border:`1px solid ${CT.border}`,borderRadius:6,padding:'4px 8px',display:'flex',alignItems:'center'}}>
          <span style={{fontSize:10,color:CT.muted,marginRight:3}}>$</span>
          <input value={amount} onChange={e=>setAmount(e.target.value.replace(/[^0-9.]/g,''))}
            style={{background:'none',border:'none',color:'#fff',fontSize:isMobile?14:16,fontWeight:700,
              width:'100%',fontFamily:window.BRAND_FONT,outline:'none',fontVariantNumeric:'tabular-nums',letterSpacing:'-0.02em'}}/>
        </div>
        <div style={{display:'flex',gap:3,marginTop:3}}>
          {[1,20,100,'MAX'].map(v=>(
            <button key={v} onClick={()=>setAmount(v==='MAX'?'10000':String(parseInt(amount||0)+Number(v)))}
              style={{flex:1,padding:'3px 0',borderRadius:4,border:`1px solid ${CT.border}`,
                background:'rgba(255,255,255,0.02)',color:CT.muted,fontSize:9,fontWeight:500,cursor:'pointer',
                fontFamily:window.BRAND_FONT}}>
              {v==='MAX'?'MAX':`+$${v}`}</button>
          ))}
        </div>
      </div>
      <div style={{padding:isMobile?'0 10px 5px':'0 12px 8px'}}>
        <div style={{display:'flex',justifyContent:'space-between',marginBottom:3}}>
          <span className="mono" style={{fontSize:7,color:CT.muted,letterSpacing:1,textTransform:'uppercase'}}>Max Leverage</span>
          <span style={{fontSize:9,fontWeight:700,color:'#fff',fontVariantNumeric:'tabular-nums'}}>{leverage}x</span>
        </div>
        <input type="range" min={1} max={3} value={leverage} onChange={e=>setLeverage(+e.target.value)}
          style={{width:'100%',height:3,borderRadius:2,cursor:'pointer',
            background:`linear-gradient(to right,${CT.green} ${(leverage-1)/2*100}%,${CT.border} ${(leverage-1)/2*100}%)`}}/>
      </div>
      <div style={{padding:isMobile?'0 10px 5px':'0 12px 8px'}}>
        <button onClick={handleBuy} disabled={buyState!=='idle'}
          style={{width:'100%',padding:isMobile?'8px 0':'10px 0',borderRadius:7,border:'none',
            background: buyState==='executed' ? CT.green : (buyState==='processing' ? 'rgba(255,255,255,0.12)' : '#fff'),
            color: buyState==='executed' ? '#0C0C12' : (buyState==='processing' ? '#fff' : '#0C0C12'),
            fontSize:12,fontWeight:800,cursor:buyState==='idle'?'pointer':'default',fontFamily:window.BRAND_FONT,
            transition:'all .25s',display:'flex',alignItems:'center',justifyContent:'center',gap:7,letterSpacing:'-0.01em'}}>
          {buyState==='idle' && 'Buy'}
          {buyState==='processing' && (<>
            <svg width={12} height={12} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2.5}
              style={{animation:'spin 0.8s linear infinite'}}>
              <path d="M21 12a9 9 0 1 1-6.22-8.56" strokeLinecap="round"/>
            </svg>
            Processing…
          </>)}
          {buyState==='executed' && (<>
            Executed on MegaETH
            <span className="mono" style={{fontSize:8,background:'rgba(12,12,18,0.2)',padding:'2px 5px',borderRadius:3,fontWeight:700}}>&lt; 10ms</span>
          </>)}
        </button>
      </div>
      <div style={{padding:isMobile?'4px 10px 5px':'6px 12px 8px',borderTop:`1px solid ${CT.border}`}}>
        {[
          ['Cost', `$${Math.round(amt).toLocaleString()}`],
          ...(leverage > 1 ? [['Position', `$${Math.round(position).toLocaleString()}`]] : []),
          ['Shares', `${shares.toLocaleString()} ${side==='yes'?'YES':'NO'}`],
        ].map(([k,v])=>(
          <div key={k} style={{display:'flex',justifyContent:'space-between',fontSize:9,marginBottom:2}}>
            <span style={{color:CT.muted}}>{k}</span>
            <span style={{color:'#fff',fontVariantNumeric:'tabular-nums'}}>{v}</span>
          </div>
        ))}
        <div style={{display:'flex',justifyContent:'space-between',fontSize:isMobile?9.5:10.5,marginTop:3}}>
          <span style={{color:CT.muted}}>To win</span>
          <span style={{color:CT.green,fontWeight:700,fontVariantNumeric:'tabular-nums'}}>${payout.toLocaleString()}</span>
        </div>
        <div style={{display:'flex',justifyContent:'space-between',fontSize:9,marginTop:2}}>
          <span style={{color:CT.muted}}>Profit</span>
          <span style={{color:profit>=0?CT.green:CT.red,fontWeight:600,fontVariantNumeric:'tabular-nums'}}>
            {profit>=0?'+':'-'}${Math.abs(Math.round(profit)).toLocaleString()}
          </span>
        </div>
      </div>
      {/* Recommended section — hidden on mobile to save space */}
      <div style={{borderTop:`1px solid ${CT.border}`,padding:'0 12px',flex:1,minHeight:0,overflow:'hidden',...(isMobile?{display:'none'}:{})}}>
        <div style={{display:'flex',gap:0,padding:'6px 0 4px',borderBottom:`1px solid ${CT.border}`}}>
          {['Favorites','Live Feed','Community'].map((t)=>(
            <button key={t} onClick={()=>setRecTab(t)}
              style={{background:'none',border:'none',color:recTab===t?'#fff':CT.muted,
                fontSize:9,fontWeight:recTab===t?700:400,cursor:'pointer',fontFamily:window.BRAND_FONT,
                padding:'0 0',marginRight:12,borderBottom:recTab===t?`2px solid #fff`:'2px solid transparent',letterSpacing:'-0.01em'}}>
              {t}
            </button>
          ))}
        </div>
        {recTab==='Favorites'&&(market.recommended||[]).map((r,i)=>(
          <div key={i} style={{display:'flex',alignItems:'center',gap:7,padding:'6px 0',borderBottom:`1px solid ${CT.border}`,cursor:'pointer'}}>
            <img src={r.img} style={{width:22,height:22,borderRadius:5,objectFit:'cover',flexShrink:0}}/>
            <span style={{flex:1,fontSize:9.5,color:'rgba(255,255,255,0.72)',lineHeight:1.4,letterSpacing:'-0.01em'}}>{r.title}</span>
            <span style={{fontSize:9,fontWeight:700,color:CT.green,flexShrink:0,fontVariantNumeric:'tabular-nums'}}>{r.pct}%</span>
          </div>
        ))}
        {recTab==='Live Feed' && <LivePanelFeed market={market}/>}
        {recTab==='Community' && <CommunityChat/>}
      </div>
      {showWaitlistStrip && (
        <div style={{
          position:'fixed', bottom:80, right:0, zIndex:2000,
          background:'rgba(8,10,18,0.96)', backdropFilter:'blur(16px)',
          border:`1px solid ${ELY_BLUE_T}44`, borderRight:'none',
          borderRadius:'12px 0 0 12px',
          padding:'11px 18px 11px 14px',
          display:'flex', flexDirection:'column', gap:4,
          animation:'slideInFromRight 0.4s cubic-bezier(0.16,1,0.3,1)',
          cursor:'pointer', maxWidth:220,
        }}
          onClick={() => { window.dispatchEvent(new Event('ev-open-waitlist')); setShowWaitlistStrip(false); }}>
          <span style={{fontSize:11,color:'rgba(255,255,255,0.75)',fontWeight:500,letterSpacing:'-0.01em',lineHeight:1.4}}>Trading opens at launch.</span>
          <span style={{fontSize:11,color:ELY_BLUE_T,fontWeight:700,letterSpacing:'-0.01em',display:'flex',alignItems:'center',gap:4}}>
            Join Waitlist →
          </span>
        </div>
      )}
    </div>
  );
}

function LivePanelFeed({ market }) {
  const outcomes = market?.outcomes || [];
  const [entries, setEntries] = useStT(() => [
    { id: 1, name: 'republic.mega', action: 'bought YES', outcome: outcomes[0]?.name || null, amount: 240 },
    { id: 2, name: '0x8b2…11',      action: 'sold NO',    outcome: outcomes[1]?.name || null, amount: 680 },
  ]);
  useEfT(() => {
    let id = 10;
    const schedule = () => setTimeout(() => {
      const name = window.ACTIVITY_NAMES[Math.floor(Math.random()*window.ACTIVITY_NAMES.length)];
      const action = window.ACTIVITY_ACTIONS[Math.floor(Math.random()*window.ACTIVITY_ACTIONS.length)];
      const amount = Math.round(40 + Math.random()*2360);
      const outs = market?.outcomes || [];
      const outcome = outs.length ? outs[Math.floor(Math.random() * outs.length)].name : null;
      setEntries(prev => [{id:++id,name,action,outcome,amount}, ...prev.slice(0,5)]);
      t = schedule();
    }, 5000 + Math.random()*3000);
    let t = schedule();
    return () => clearTimeout(t);
  }, []);
  return (
    <div style={{padding:'10px 0',display:'flex',flexDirection:'column',gap:9}}>
      {entries.map(e => {
        const isBuy = e.action.startsWith('bought');
        return (
          <div key={e.id} style={{display:'flex',alignItems:'flex-start',gap:6,fontSize:10,fontFamily:window.BRAND_FONT,animation:'mkt-card-in 0.3s ease'}}>
            <span className="mono" style={{color:'rgba(255,255,255,0.6)',fontSize:9.5,flex:1,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{e.name}</span>
            <div style={{display:'flex',flexDirection:'column',alignItems:'flex-end',flexShrink:0,gap:1}}>
              <span style={{color:isBuy?CT.green:CT.red,fontWeight:600,fontSize:10}}>{e.action}</span>
              {e.outcome && <span style={{color:'rgba(255,255,255,0.38)',fontSize:8.5}}>{e.outcome}</span>}
            </div>
            <span style={{color:'#fff',fontWeight:700,fontSize:10,fontVariantNumeric:'tabular-nums',flexShrink:0}}>${e.amount.toLocaleString()}</span>
          </div>
        );
      })}
    </div>
  );
}

function CommunityChat() {
  const msgs = [
    {user:'0xDegen',           msg:'Bad Bunnz is pumping hard. Loaded up at 28%.',     t:'2m'},
    {user:'alphatrader.mega',  msg:'Nacci Cartel volume catching up — watch the spread', t:'4m'},
    {user:'kaleidoscope.mega', msg:'Megalio floor moving too, big week incoming',        t:'7m'},
    {user:'republic.mega',     msg:'MegaETH NFT week edge is real, floor prices rising', t:'12m'},
    {user:'nightowl.mega',     msg:'Anyone else watching the Bad Bunnz floor?',          t:'18m'},
  ];
  return (
    <div style={{padding:'10px 0',display:'flex',flexDirection:'column',gap:9}}>
      {msgs.map((m,i)=>(
        <div key={i} style={{display:'flex',gap:7,alignItems:'flex-start'}}>
          <div style={{width:20,height:20,borderRadius:'50%',background:`hsl(${i*60+180},30%,30%)`,
            flexShrink:0,fontSize:9,display:'flex',alignItems:'center',justifyContent:'center',color:'#fff',fontWeight:700}}>
            {m.user[m.user.startsWith('0x')?2:0].toUpperCase()}
          </div>
          <div style={{flex:1,minWidth:0}}>
            <div style={{display:'flex',gap:6,alignItems:'center'}}>
              <span style={{fontSize:10,fontWeight:700,color:'rgba(255,255,255,0.78)',letterSpacing:'-0.01em'}}>{m.user}</span>
              <span className="mono" style={{fontSize:8.5,color:CT.muted}}>{m.t}</span>
            </div>
            <div style={{fontSize:10.5,color:'rgba(255,255,255,0.58)',marginTop:2,lineHeight:1.5}}>{m.msg}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

function TradingView({ market, isMobile }) {
  const [selectedOutcome, setSelectedOutcome] = useStT(() => market?.outcomes?.[0] || null);
  const [side, setSide] = useStT('yes');

  useEfT(() => {
    setSelectedOutcome(market?.outcomes?.[0] || null);
    setSide('yes');
  }, [market?.id]);

  if (!market) return (
    <div style={{flex:1,display:'flex',alignItems:'center',justifyContent:'center',color:CT.muted,fontSize:13}}>Select a market to trade</div>
  );
  const drift = window.MARKET_PROB[market.id] || {};
  return (
    <div style={{flex:1,display:'flex',flexDirection:'column',overflow:'hidden',minHeight:0}}>
      <window.AppFilterBar style={isMobile ? {overflow:'hidden'} : undefined}/>
      <div style={{flex:1,display:'flex',overflow:isMobile?'auto':'hidden',minHeight:0,flexDirection:isMobile?'column':'row'}}>
        <div style={{flex:isMobile?'0 0 auto':1,overflow:'hidden',padding:isMobile?'8px 10px':'10px 14px',display:'flex',flexDirection:'column',gap:0}}>
          <div style={{display:'flex',gap:10,alignItems:'flex-start',marginBottom:6}}>
            <window.MarketThumb market={market} size={isMobile ? 28 : 36}/>
            <div style={{flex:1}}>
              <h2 style={{fontSize:isMobile?11:14,fontWeight:800,color:'#fff',lineHeight:1.2,letterSpacing:'-0.02em',margin:0}}>{market.title}</h2>
              <div style={{display:'flex',gap:10,marginTop:3,fontSize:isMobile?8:9.5,color:CT.muted,alignItems:'center'}}>
                {market.label && <span style={{color:'#fff',fontWeight:600}}>{market.label}</span>}
                {market.ends && <><span>·</span><span>{market.ends}</span></>}
                <span>·</span>
                <span className="mono" style={{color:CT.muted,fontSize:10}}>{market.volume} VOL</span>
              </div>
            </div>
          </div>
          <div style={{display:'flex',gap:12,marginBottom:4,flexWrap:'wrap'}}>
            {(market.chartSeries||[]).map((s,i)=>{
              const driftedPct = (drift.outcomes && drift.outcomes[i] != null)
                ? drift.outcomes[i]
                : (s.data && s.data.length > 0 ? s.data[s.data.length-1] : 0);
              return (
              <span key={s.label} style={{fontSize:10,display:'flex',alignItems:'center',gap:4,color:s.color,fontWeight:600,letterSpacing:'-0.01em'}}>
                <span style={{width:6,height:6,borderRadius:'50%',background:s.color}}/>
                {s.label} <span style={{fontVariantNumeric:'tabular-nums'}}>{Math.round(driftedPct)}%</span>
              </span>
            );})}
          </div>
          <div style={{
            background:'linear-gradient(160deg,rgba(6,8,20,0.98) 0%,rgba(10,12,28,0.96) 100%)',
            borderRadius:8,padding:isMobile?'4px 4px 2px':'6px 6px 4px',marginBottom:isMobile?4:6,
            border:'1px solid rgba(255,255,255,0.07)',
            boxShadow:'0 2px 24px rgba(0,0,0,0.55),inset 0 1px 0 rgba(255,255,255,0.05)',
            backdropFilter:'blur(20px)',
          }}>
            <LiveChart market={market} isMobile={isMobile}/>
          </div>
          <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:8,gap:6}}>
            <div style={{display:'flex',gap:10,fontSize:10,color:CT.muted,alignItems:'center'}}>
              <span style={{display:'flex',alignItems:'center',gap:5}}>
                <img src="images/logo-usdm.png" style={{width:14,height:14,objectFit:'contain',borderRadius:'50%'}}/>
                <span style={{color:CT.blue,fontWeight:600}}>Earn USDm</span>
              </span>
              <span style={{display:'flex',alignItems:'center',gap:2}}>
                <window.EventlyLogoSVG size={20}/>
                <span style={{fontWeight:500}}>Earn</span>
                <span style={{fontWeight:800,color:ELY_BLUE_T}}>ELY</span>
              </span>
            </div>
            <div style={{display:'flex',gap:2}}>
              {['1H','1D','1W','1M','All'].map(t=>(
                <button key={t} style={{padding:isMobile?'3px 6px':'4px 9px',borderRadius:5,border:'none',
                  background:t==='All'?'rgba(255,255,255,0.1)':'none',
                  color:t==='All'?'#fff':CT.muted,fontSize:isMobile?9:10,cursor:'pointer',fontFamily:window.BRAND_FONT,fontWeight:600}}>{t}</button>
              ))}
            </div>
          </div>
          <div style={{...(isMobile?{flex:'0 0 auto',overflow:'visible'}:{flex:1,minHeight:0,overflowY:'auto'})}}>
            <div style={{display:'flex',justifyContent:'space-between',padding:isMobile?'3px 0':'4px 0',borderBottom:`1px solid ${CT.border}`,marginBottom:2}}>
              <span className="mono" style={{fontSize:isMobile?8:9,color:CT.dim,fontWeight:600,textTransform:'uppercase',letterSpacing:0.8}}>Outcomes</span>
              <span className="mono" style={{fontSize:isMobile?8:9,color:CT.dim,fontWeight:600,textTransform:'uppercase',letterSpacing:0.8}}>Chance</span>
            </div>
            {(market.outcomes||[]).map((o,i)=>{
              const p = drift.outcomes ? drift.outcomes[i] : o.pct;
              const isSelected = selectedOutcome === o;
              return (
              <div key={i} onClick={() => { setSelectedOutcome(o); setSide('yes'); }}
                style={{display:'flex',alignItems:'center',gap:8,padding:isMobile?'4px 0':'6px 0',borderBottom:`1px solid ${CT.border}`,
                  cursor:'pointer',borderRadius:4,
                  background: isSelected ? 'rgba(255,255,255,0.04)' : 'transparent',
                  transition:'background 0.15s'}}>
                <div style={{width:24,height:24,borderRadius:'50%',background:'#1a1a22',flexShrink:0,overflow:'hidden'}}>
                  {o.img&&<img src={o.img} style={{width:'100%',height:'100%',objectFit:'cover'}}/>}
                </div>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontSize:isMobile?9:11,fontWeight:600,color: isSelected ? '#fff' : 'rgba(255,255,255,0.78)',letterSpacing:'-0.01em'}}>{o.name}</div>
                  {o.party&&<div style={{fontSize:9,color:CT.muted}}>{o.party}</div>}
                </div>
                <span style={{fontSize:12,fontWeight:700,color:'#fff',fontVariantNumeric:'tabular-nums'}}>{Math.round(p)}%</span>
                <button onClick={e=>{e.stopPropagation();setSelectedOutcome(o);setSide('yes');}}
                  style={{padding:isMobile?'3px 6px':'4px 8px',borderRadius:5,border:'none',background:CT.greenDim,color:CT.green,fontSize:isMobile?9:10,fontWeight:700,cursor:'pointer',fontFamily:window.BRAND_FONT}}>Yes {Math.round(p)}¢</button>
                <button onClick={e=>{e.stopPropagation();setSelectedOutcome(o);setSide('no');}}
                  style={{padding:isMobile?'3px 6px':'4px 8px',borderRadius:5,border:'none',background:CT.redDim,color:CT.red,fontSize:isMobile?9:10,fontWeight:700,cursor:'pointer',fontFamily:window.BRAND_FONT}}>No {100-Math.round(p)}¢</button>
              </div>
            );})}
          </div>
        </div>
        <TradePanel market={market} selectedOutcome={selectedOutcome} side={side} setSide={setSide} isMobile={isMobile}/>
      </div>
    </div>
  );
}

Object.assign(window, { TradingView, LiveChart, TradePanel });
