// ── Markets View ──────────────────────────────────────────────
const { useState: useMkt, useEffect: useEfMkt, useRef: useRfMkt } = React;
const CM = window.SC;

const mktStyle = document.createElement('style');
mktStyle.textContent = `
  @keyframes mkt-card-in {
    from { opacity: 0; transform: translateY(10px); }
    to   { opacity: 1; transform: translateY(0); }
  }
  /* Outer wrapper: owns the entry animation only */
  .market-card {
    animation: mkt-card-in 0.45s cubic-bezier(0.16,1,0.3,1) both;
    animation-delay: calc(var(--card-index, 0) * 50ms);
    position: relative;
  }
  /* Inner card: owns hover transform only — no animation conflict */
  .market-card-inner {
    height: 100%;
    box-sizing: border-box;
    will-change: transform;
    backface-visibility: hidden;
    isolation: isolate;
    box-shadow: 0 2px 14px rgba(0,0,0,0.24), 0 0 0 1px rgba(255,255,255,0.03);
  }
  .market-card-clickable {
    cursor: pointer;
    transition: box-shadow 0.22s ease-out, transform 0.22s cubic-bezier(0.34,1.20,0.64,1);
  }
  .market-card-clickable:hover {
    transform: translateY(-6px) scale(1.025);
    box-shadow: 0 18px 48px rgba(0,0,0,0.48), 0 0 0 1px rgba(92,200,230,0.28), 0 0 32px rgba(92,200,230,0.14);
  }
  .market-card-clickable:active { transform: translateY(-2px) scale(1.01); }
  .market-card-static {
    cursor: default;
    transition: box-shadow 0.22s ease-out, transform 0.22s ease-out;
  }
  .market-card-static:hover {
    transform: translateY(-4px) scale(1.015);
    box-shadow: 0 12px 32px rgba(0,0,0,0.36), 0 0 0 1px rgba(255,255,255,0.08);
  }
  .market-card-static:active { transform: translateY(-1px) scale(1.005); }
  .price-flash-up   { animation: flashUp 0.35s ease; }
  .price-flash-down { animation: flashDown 0.35s ease; }
  @keyframes flashUp   { 0% { background: rgba(92,212,168,0.22); border-radius: 3px; } 100% { background: transparent; } }
  @keyframes flashDown { 0% { background: rgba(232,101,101,0.22); border-radius: 3px; } 100% { background: transparent; } }

  /* Gold ring — child element, independent animation, no conflict with parent */
  .first-card-gold-ring {
    position: absolute; inset: -2px; border-radius: 12px;
    pointer-events: none; z-index: 0;
    animation: goldBorderPulse 2.2s ease-in-out infinite;
  }
  @keyframes goldBorderPulse {
    0%, 100% {
      border: 1.5px solid rgba(200,145,50,0.40);
      box-shadow:
        0 0 8px rgba(200,145,50,0.18),
        0 0 18px rgba(200,145,50,0.08);
    }
    50% {
      border: 1.5px solid rgba(255,215,80,0.82);
      box-shadow:
        0 0 14px rgba(255,210,70,0.42),
        0 0 32px rgba(255,195,50,0.18),
        inset 0 0 10px rgba(255,215,70,0.06);
    }
  }

  /* Create market ring — child element */
  .create-market-ring {
    position: absolute; inset: -1px; border-radius: 11px;
    pointer-events: none; z-index: 0;
    animation: createBorderPulse 3.5s ease-in-out 0.8s infinite;
  }
  @keyframes createBorderPulse {
    0%, 100% { border: 1px solid rgba(92,200,230,0.13); box-shadow: none; }
    50%       { border: 1px solid rgba(92,200,230,0.28); box-shadow: 0 0 16px rgba(92,200,230,0.07); }
  }

  /* Hint overlay — fades in on static card hover */
  .market-hint-overlay {
    position: absolute;
    bottom: 0; left: 0; right: 0;
    padding: 22px 10px 8px;
    border-radius: 0 0 9px 9px;
    background: linear-gradient(to top, rgba(5,6,16,0.97) 0%, rgba(5,6,16,0.72) 55%, transparent 100%);
    opacity: 0;
    transform: translateY(4px);
    transition: opacity 0.22s ease, transform 0.22s ease;
    pointer-events: none;
    z-index: 3;
  }
  .market-card-static:hover .market-hint-overlay {
    opacity: 1;
    transform: translateY(0);
  }

  /* CreateMarketCard — entry only, hover via transition */
  .create-market-card {
    cursor: pointer;
    animation: mkt-card-in 0.45s cubic-bezier(0.16,1,0.3,1) calc(4 * 50ms) both;
    transition: background 0.18s ease-out, border-color 0.18s ease-out, box-shadow 0.18s ease-out;
  }
  .create-market-card:hover {
    box-shadow: 0 6px 26px rgba(0,0,0,0.28), 0 0 0 1px rgba(92,200,230,0.22);
    border-color: rgba(92,200,230,0.26) !important;
  }
`;
if (!document.getElementById('mkt-style')) { mktStyle.id = 'mkt-style'; document.head.appendChild(mktStyle); }

function DriftPct({ value }) {
  const animated = window.useAnimatedNumber(value, 320);
  const prev = useRfMkt(value);
  const [flash, setFlash] = useMkt('');
  useEfMkt(() => {
    if (value !== prev.current) {
      setFlash(value > prev.current ? 'price-flash-up' : 'price-flash-down');
      prev.current = value;
      const t = setTimeout(() => setFlash(''), 400);
      return () => clearTimeout(t);
    }
  }, [value]);
  return (
    <span className={flash} style={{
      fontSize: 11, fontWeight: 600, color: CM.muted, flexShrink: 0,
      minWidth: 30, textAlign: 'right', fontVariantNumeric: 'tabular-nums',
      borderRadius: 3, padding: '0 2px',
    }}>
      {Math.round(animated)}%
    </span>
  );
}

function OutcomeRow({ outcome, drifted }) {
  const [sel, setSel] = useMkt(null);
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 5, padding: '2.5px 0' }}>
      <span style={{
        flex: 1, fontSize: 10.5, color: 'rgba(255,255,255,0.6)',
        overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        minWidth: 0, letterSpacing: '-0.01em',
      }}>{outcome.name}</span>
      <DriftPct value={drifted != null ? drifted : outcome.pct} />
      <button
        onClick={() => setSel(s => s === 'yes' ? null : 'yes')}
        style={{
          padding: '2px 7px', borderRadius: 4,
          border: sel === 'yes' ? `1px solid ${CM.green}` : '1px solid transparent',
          background: sel === 'yes' ? 'rgba(92,212,168,0.28)' : CM.greenDim,
          color: CM.green,
          fontSize: 10, fontWeight: 700, cursor: 'pointer',
          fontFamily: window.BRAND_FONT, flexShrink: 0,
          transform: sel === 'yes' ? 'scale(1.06)' : 'scale(1)',
          boxShadow: sel === 'yes' ? '0 0 8px rgba(92,212,168,0.35)' : 'none',
          transition: 'all 0.15s ease-out',
        }}>Yes</button>
      <button
        onClick={() => setSel(s => s === 'no' ? null : 'no')}
        style={{
          padding: '2px 7px', borderRadius: 4,
          border: sel === 'no' ? `1px solid ${CM.red}` : '1px solid transparent',
          background: sel === 'no' ? 'rgba(232,101,101,0.28)' : CM.redDim,
          color: CM.red,
          fontSize: 10, fontWeight: 700, cursor: 'pointer',
          fontFamily: window.BRAND_FONT, flexShrink: 0,
          transform: sel === 'no' ? 'scale(1.06)' : 'scale(1)',
          boxShadow: sel === 'no' ? '0 0 8px rgba(232,101,101,0.35)' : 'none',
          transition: 'all 0.15s ease-out',
        }}>No</button>
    </div>
  );
}

function BinaryButtons() {
  const [sel, setSel] = useMkt(null);
  return (
    <div style={{ display: 'flex', gap: 5, flex: 1 }}>
      <button
        onClick={() => setSel(s => s === 'yes' ? null : 'yes')}
        style={{
          flex: 1, padding: '6px 0', borderRadius: 6,
          border: sel === 'yes' ? `1px solid ${CM.green}` : '1px solid transparent',
          background: sel === 'yes' ? 'rgba(92,212,168,0.26)' : CM.greenDim,
          color: CM.green,
          fontSize: 11, fontWeight: 700, cursor: 'pointer',
          fontFamily: window.BRAND_FONT,
          boxShadow: sel === 'yes' ? '0 0 10px rgba(92,212,168,0.28)' : 'none',
          transition: 'background 0.15s ease-out, border-color 0.15s ease-out, box-shadow 0.15s ease-out',
        }}>Yes</button>
      <button
        onClick={() => setSel(s => s === 'no' ? null : 'no')}
        style={{
          flex: 1, padding: '6px 0', borderRadius: 6,
          border: sel === 'no' ? `1px solid ${CM.red}` : '1px solid transparent',
          background: sel === 'no' ? 'rgba(232,101,101,0.26)' : CM.redDim,
          color: CM.red,
          fontSize: 11, fontWeight: 700, cursor: 'pointer',
          fontFamily: window.BRAND_FONT,
          boxShadow: sel === 'no' ? '0 0 10px rgba(232,101,101,0.28)' : 'none',
          transition: 'background 0.15s ease-out, border-color 0.15s ease-out, box-shadow 0.15s ease-out',
        }}>No</button>
    </div>
  );
}

function MarketCard({ market, onSelect, idx, isFirst }) {
  window.useMarketDrift();
  const drift = window.MARKET_PROB[market?.id] || {};
  if (!market) return null;

  return (
    <div className="market-card" style={{ '--card-index': idx }}>
      {isFirst && <div className="first-card-gold-ring" />}
      <div
        className={`market-card-inner ${isFirst ? 'market-card-clickable' : 'market-card-static'}`}
        style={{
          background: CM.card,
          border: `1px solid ${CM.border}`,
          borderRadius: 10, padding: '10px 12px',
          display: 'flex', flexDirection: 'column', gap: 0,
          position: 'relative', overflow: 'hidden',
        }}
        onClick={() => isFirst && onSelect && onSelect(market)}
      >
      {isFirst && (
        <div style={{
          position: 'absolute', top: 7, right: 9,
          fontSize: 9, color: 'rgba(212,160,96,0.65)',
          fontWeight: 700, letterSpacing: 0.3,
          fontFamily: window.BRAND_FONT, pointerEvents: 'none',
          zIndex: 2,
        }}>Try it →</div>
      )}

      <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start', marginBottom: 7 }}>
        <window.MarketThumb market={market} size={38} showBorder />
        <span style={{
          fontSize: 11.5, fontWeight: 600, color: '#fff', lineHeight: 1.35, flex: 1,
          letterSpacing: '-0.015em',
          overflow: 'hidden', display: '-webkit-box',
          WebkitLineClamp: 3, WebkitBoxOrient: 'vertical',
        }}>
          {market.title}
        </span>
      </div>

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
        {market.type === 'multi' && market.outcomes && (
          <div style={{ display: 'flex', flexDirection: 'column', marginBottom: 6 }}>
            {market.outcomes.slice(0, 2).map((o, i) => (
              <OutcomeRow key={i} outcome={o} drifted={drift.outcomes ? drift.outcomes[i] : o.pct} />
            ))}
          </div>
        )}
        {market.type === 'binary' && (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6, gap: 6 }}>
            <BinaryButtons />
            <window.CircleProgress pct={drift.pct != null ? drift.pct : market.pct} size={42} />
          </div>
        )}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          paddingTop: 6, borderTop: `1px solid ${CM.border}`, marginTop: 'auto',
        }}>
          <span className="mono" style={{ fontSize: 9.5, color: CM.dim, letterSpacing: 0.3 }}>
            {market.volume} VOL
          </span>
          <svg width={12} height={12} viewBox="0 0 24 24" fill="none"
            stroke="rgba(255,255,255,0.22)" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
            <path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/>
          </svg>
        </div>
      </div>

      {!isFirst && market.hint && (
        <div className="market-hint-overlay">
          <span style={{
            fontSize: 8.5, color: 'rgba(255,255,255,0.58)', lineHeight: 1.45,
            fontFamily: window.BRAND_FONT, display: 'block', fontStyle: 'italic',
            letterSpacing: '-0.005em',
          }}>{market.hint}</span>
        </div>
      )}
      </div>
    </div>
  );
}

function CreateMarketCard({ onOpenWaitlist }) {
  return (
    <div
      className="create-market-card"
      style={{
        gridColumn: 'span 2',
        background: 'linear-gradient(135deg, rgba(92,200,230,0.07) 0%, rgba(92,212,168,0.03) 50%, rgba(92,200,230,0.06) 100%)',
        border: '1px solid rgba(92,200,230,0.22)',
        borderRadius: 10, padding: '14px 16px',
        display: 'flex', flexDirection: 'column',
        justifyContent: 'space-between', gap: 8,
        position: 'relative', overflow: 'hidden',
        minHeight: 0,
      }}
      onClick={onOpenWaitlist}
    >
      <div className="create-market-ring" />
      <div style={{
        position: 'absolute', top: -48, right: -48,
        width: 180, height: 180, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(92,200,230,0.1) 0%, transparent 70%)',
        pointerEvents: 'none',
      }} />
      <div style={{
        position: 'absolute', right: -16, top: '50%',
        transform: 'translateY(-50%)',
        opacity: 0.07, pointerEvents: 'none', zIndex: 0,
      }}>
        <window.EventlyLogoSVG size={150} />
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 7, position: 'relative', zIndex: 1 }}>
        <span style={{
          fontSize: 10, fontWeight: 700, color: 'var(--blue)',
          fontFamily: window.BRAND_FONT, letterSpacing: '-0.01em',
        }}>Community Markets</span>
        <span style={{
          background: 'rgba(112,186,210,0.12)', color: 'var(--blue)',
          fontSize: 8, fontWeight: 700, padding: '2px 6px', borderRadius: 8,
          fontFamily: 'JetBrains Mono, monospace',
          letterSpacing: '0.1em', textTransform: 'uppercase',
          border: '1px solid rgba(112,186,210,0.22)',
        }}>Beta</span>
      </div>

      <div style={{ position: 'relative', zIndex: 1 }}>
        <div style={{
          fontSize: 14.5, fontWeight: 800, color: '#fff',
          letterSpacing: '-0.025em', lineHeight: 1.2,
          fontFamily: window.BRAND_FONT, marginBottom: 4,
        }}>
          Create your own market
        </div>
        <p style={{
          fontSize: 11, fontWeight: 400,
          color: 'rgba(255,255,255,0.52)', lineHeight: 1.5,
          margin: 0, letterSpacing: '-0.01em', fontFamily: window.BRAND_FONT,
        }}>
          Create market, share with your community and earn fees
        </p>
      </div>

      <div style={{ position: 'relative', zIndex: 1, display: 'flex', alignItems: 'center', gap: 9 }}>
        <div style={{
          display: 'inline-flex', alignItems: 'center',
          padding: '6px 12px', borderRadius: 100,
          background: 'rgba(112,186,210,0.1)',
          border: '1px solid rgba(112,186,210,0.28)',
          color: 'var(--blue)',
          fontSize: 11, fontWeight: 700,
          fontFamily: window.BRAND_FONT, letterSpacing: '-0.01em',
        }}>
          Join Waitlist
        </div>
        <span style={{
          fontSize: 10, color: 'rgba(255,255,255,0.28)',
          fontFamily: window.BRAND_FONT, letterSpacing: '-0.01em',
        }}>Early access</span>
      </div>
    </div>
  );
}

function ActivityFeed() {
  const [entries, setEntries] = useMkt(() => [
    { id: 1, name: 'alphatrader.mega', action: 'bought NO',  market: 'Brent Oil',    amount: 294  },
    { id: 2, name: '0x8b2…11',         action: 'bought YES', market: 'Bad Bunnz',     amount: 2147 },
    { id: 3, name: 'nightowl.mega',    action: 'bought YES', market: 'WLFI Subpoena', amount: 2386 },
    { id: 4, name: '0x91c…aa',         action: 'sold NO',    market: 'Fed Rate Cuts', amount: 316  },
  ]);

  useEfMkt(() => {
    let id = 100;
    const schedule = () => {
      const delay = 4000 + Math.random() * 3000;
      return 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 market = window.ACTIVITY_MARKETS[Math.floor(Math.random() * window.ACTIVITY_MARKETS.length)];
        setEntries(prev => [...prev.slice(-3), { id: ++id, name, action, market, amount }]);
        t = schedule();
      }, delay);
    };
    let t = schedule();
    return () => clearTimeout(t);
  }, []);

  return (
    <div style={{
      padding: '0 14px', height: 30,
      borderTop: `1px solid ${CM.border}`,
      background: 'rgba(255,255,255,0.012)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 14,
      overflow: 'hidden', flexShrink: 0,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 5, flexShrink: 0 }}>
        <span style={{
          width: 5, height: 5, borderRadius: '50%',
          background: '#5CC8E6',
          boxShadow: '0 0 6px rgba(92,200,230,0.9)',
          animation: 'pulse 1.6s ease-in-out infinite',
          display: 'block',
        }} />
        <span className="mono" style={{
          fontSize: 8.5, color: 'rgba(92,200,230,0.55)',
          letterSpacing: '1.2px', fontWeight: 600, textTransform: 'uppercase',
        }}>Live</span>
      </div>
      <div style={{ display: 'flex', gap: 18, overflow: 'hidden', minWidth: 0, alignItems: 'center' }}>
        {entries.map(e => {
          const isBuy = e.action.startsWith('bought');
          return (
            <div key={e.id} style={{
              display: 'flex', alignItems: 'center', gap: 5,
              fontSize: 10, whiteSpace: 'nowrap',
              fontFamily: window.BRAND_FONT,
              animation: 'mkt-card-in 0.3s ease',
              fontVariantNumeric: 'tabular-nums',
            }}>
              <span className="mono" style={{ color: 'rgba(255,255,255,0.42)', fontSize: 9.5 }}>{e.name}</span>
              <span style={{ color: isBuy ? CM.green : CM.red, fontWeight: 600, fontSize: 9.5 }}>{e.action}</span>
              {e.market && <span style={{ color: 'rgba(255,255,255,0.28)', fontSize: 9.5 }}>· {e.market}</span>}
              <span style={{ color: 'rgba(255,255,255,0.7)', fontWeight: 700, fontSize: 9.5 }}>${e.amount.toLocaleString()}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function MarketsView({ onSelectMarket, onOpenWaitlist, isMobile }) {
  const markets = window.SM.filter(m => m.type !== 'promo').slice(0, 10);

  if (isMobile) {
    return (
      <>
        <div style={{ flex: 1, padding: '8px 8px 6px', overflowY: 'auto', overflowX: 'hidden' }}>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, 1fr)',
            gridTemplateRows: 'auto',
            gap: 6,
          }}>
            {markets.slice(0, 4).map((m, idx) => (
              <MarketCard key={m.id} market={m} idx={idx} isFirst={idx === 0} onSelect={onSelectMarket} />
            ))}
            <CreateMarketCard onOpenWaitlist={onOpenWaitlist} />
            {markets.slice(4, 8).map((m, idx) => (
              <MarketCard key={m.id} market={m} idx={idx + 4} isFirst={false} onSelect={null} />
            ))}
          </div>
        </div>
        <ActivityFeed />
      </>
    );
  }

  return (
    <>
      <div style={{ flex: 1, padding: '10px 12px 8px', overflow: 'hidden' }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(4, 1fr)',
          gridTemplateRows: 'repeat(3, 1fr)',
          gap: 8,
          height: '100%',
        }}>
          {markets.slice(0, 4).map((m, idx) => (
            <MarketCard key={m.id} market={m} idx={idx} isFirst={idx === 0} onSelect={onSelectMarket} />
          ))}
          <MarketCard key={markets[4]?.id} market={markets[4]} idx={4} isFirst={false} onSelect={null} />
          <CreateMarketCard onOpenWaitlist={onOpenWaitlist} />
          <MarketCard key={markets[5]?.id} market={markets[5]} idx={5} isFirst={false} onSelect={null} />
          <MarketCard key={markets[6]?.id} market={markets[6]} idx={6} isFirst={false} onSelect={null} />
          <MarketCard key={markets[7]?.id} market={markets[7]} idx={7} isFirst={false} onSelect={null} />
          <MarketCard key={markets[8]?.id} market={markets[8]} idx={8} isFirst={false} onSelect={null} />
          <MarketCard key={markets[9]?.id} market={markets[9]} idx={9} isFirst={false} onSelect={null} />
        </div>
      </div>
      <ActivityFeed />
    </>
  );
}

Object.assign(window, { MarketsView, MarketCard, CreateMarketCard, ActivityFeed });
