/* trade.jsx — Full trading app. Refactored: flex body, bounded heights, pro polish. */

const { useState: trUseState, useEffect: trUseEffect, useRef: trUseRef, useMemo: trUseMemo, useLayoutEffect: trUseLayoutEffect } = React;

// ── Top nav ─────────────────────────────────────────────────────────────────
function TopNav({ onLogoClick }) {
  const items = [
    { label: 'Markets', active: true },
  ];
  const status = window.TR.status;
  return (
    <div className="h-[36px] hl-b flex items-center px-4 bg-bg shrink-0">
      <button onClick={onLogoClick} className="flex items-center gap-2.5 mr-7 hover:opacity-80">
        <span className="w-[8px] h-[8px] rounded-full bg-emerald" style={{ boxShadow: '0 0 8px rgba(16,185,129,0.6)' }} />
        <span className="font-sans font-bold tracking-[0.32em] text-[11px]">TRINIUM</span>
      </button>
      <nav className="flex items-center">
        {items.map(it => (
          <a key={it.label} href="#"
            className={[
              'h-[36px] px-3.5 inline-flex items-center font-mono text-[10.5px] tracking-[0.14em] uppercase',
              it.active ? 'text-text' : 'text-text-2 hover:text-text'
            ].join(' ')}
            style={it.active ? { boxShadow: 'inset 0 -2px 0 0 #10B981' } : undefined}
          >{it.label}</a>
        ))}
      </nav>
      <div className="ml-auto flex items-center gap-5">
        <div className="flex items-center gap-2">
          <span className="w-1.5 h-1.5 rounded-full bg-green live-dot" />
          <span className="font-mono text-[10px] tracking-[0.12em] text-text-2">WS · {status.ws}</span>
        </div>
        <div className="flex items-center gap-2">
          <span className="font-mono text-[10px] tracking-[0.12em] text-text-3">LAT</span>
          <span className="font-mono text-[10.5px] text-emerald">{status.latency.toFixed(2)} ms</span>
        </div>
        <button className="h-[26px] px-3 border border-emerald/40 bg-emerald/[0.10] text-emerald font-mono text-[10.5px] tracking-[0.14em] uppercase hover:bg-emerald/[0.18]">
          Connect
        </button>
      </div>
    </div>
  );
}

// ── Market header (64px) ────────────────────────────────────────────────────
function MarketHeader({ market, prices, onOpenPicker, countdown }) {
  const yesPct = Math.round((prices ? prices.yes : 0.64) * 100);
  const resolveLabel = market.settleAt;
  return (
    <div className="h-[64px] hl-b px-4 flex items-center justify-between bg-bg shrink-0 gap-6">
      <div className="flex items-center gap-4 min-w-0">
        <div className="flex items-center gap-1.5 shrink-0">
          <button
            onClick={onOpenPicker}
            className="inline-flex items-center gap-2 h-[26px] pl-1 pr-2.5 rounded-full bg-bg-3 border border-line-3 hover:bg-bg-hover hover:border-emerald/40 transition-colors"
            aria-label="Change market"
          >
            <window.MarketIcon coin={market.coin} size={20} />
            <span className="font-mono text-[11px] tracking-[0.12em] uppercase text-text">{market.coin ? market.coin.sym : 'BTC'}</span>
            <svg width="8" height="5" viewBox="0 0 8 5" fill="none"><path d="M1 1l3 3 3-3" stroke="currentColor" strokeWidth="1.2" /></svg>
          </button>
          <Tag tone="emerald">{market.duration}</Tag>
          <Tag>{market.kind}</Tag>
        </div>
        <div className="flex flex-col gap-1 min-w-0">
          <div className="font-sans text-[20px] leading-none tracking-[-0.01em] text-text truncate">
            Will {market.coin ? market.coin.sym : 'BTC'} close above{' '}
            <span className="text-amber font-semibold">{market.strike.toLocaleString(undefined, { maximumFractionDigits: market.strike >= 1000 ? 0 : market.strike >= 10 ? 2 : 4 })}</span>{' '}
            at <span className="text-text font-semibold">{resolveLabel}</span>?
          </div>
          <div className="flex items-center gap-4 font-mono text-[10px] text-text-3">
            <span>SPOT <span className="text-text-2">{market.spot.toLocaleString(undefined, { maximumFractionDigits: market.spot >= 1000 ? 1 : market.spot >= 10 ? 2 : 4 })}</span></span>
            <span>24H <span className={market.change24 >= 0 ? 'text-green' : 'text-red'}>{market.change24 >= 0 ? '+' : ''}{market.change24.toFixed(2)}%</span></span>
            <span>VOL <span className="text-text-2">{window.TR.fmtUsd(market.vol24, 0)}</span></span>
            <span>OI <span className="text-text-2">{window.TR.fmtUsd(market.oi, 0)}</span></span>
            <span>VENUE <span className="text-text-2">TRINIUM</span></span>
          </div>
        </div>
      </div>

      {/* Implied probability strip (Kalshi DNA) */}
      <div className="flex items-center gap-3 shrink-0">
        <div className="flex flex-col items-end gap-1">
          <div className="font-mono text-[9.5px] tracking-[0.16em] uppercase text-text-3">Implied probability</div>
          <div className="flex items-center gap-2">
            <span className="font-mono text-[10.5px] text-green tracking-[0.06em]">YES {yesPct}%</span>
            <div className="w-[140px] h-[6px] bg-bg-2 border border-line-2 flex overflow-hidden">
              <div className="h-full bg-green" style={{ width: `${yesPct}%` }} />
              <div className="h-full bg-red" style={{ width: `${100 - yesPct}%` }} />
            </div>
            <span className="font-mono text-[10.5px] text-red tracking-[0.06em]">{100 - yesPct}% NO</span>
          </div>
        </div>
      </div>

      {/* Countdown */}
      <div className="flex flex-col items-end gap-1 shrink-0">
        <div className="flex items-center gap-2">
          <span className="w-1 h-1 rounded-full bg-amber em-pulse" />
          <span className="font-mono text-[9.5px] tracking-[0.16em] uppercase text-text-3">Resolves in</span>
        </div>
        <div className="flex items-baseline gap-2">
          <div className="font-mono font-semibold text-[24px] leading-none text-amber tracking-[0.04em]">
            {countdown ? countdown : '—'}
          </div>
          <span className="font-mono text-[9.5px] tracking-[0.14em] uppercase text-text-3">@ {market.settleAt.replace(' UTC','')} UTC</span>
        </div>
      </div>
    </div>
  );
}

// ── Position strip (52px) ───────────────────────────────────────────────────
function PositionStrip({ position }) {
  return (
    <div className="h-[52px] hl-t px-4 flex items-center bg-bg-1 shrink-0 gap-0">
      <div className="flex items-center gap-2 pr-5 hl-r" style={{ paddingRight: '20px' }}>
        <span className="font-mono text-[9.5px] tracking-[0.16em] uppercase text-text-3">Position</span>
        <span className={`font-mono text-[14px] ${position.side === 'YES' ? 'text-green' : 'text-red'}`}>
          {position.side === 'YES' ? '+' : '−'}{position.size}
        </span>
        <span className="font-mono text-[11px] text-text-2">{position.side}</span>
      </div>
      <div className="flex-1 grid grid-cols-6 gap-5 px-5">
        <KV k="Entry"      v={position.entry.toFixed(4)} />
        <KV k="Mark"       v={position.mark.toFixed(4)}  />
        <KV k="uPnL"       v={window.TR.fmtUsd(position.upnl, 2)} tone="green" />
        <KV k="If Wins"    v={`+${window.TR.fmtUsd(position.ifWins, 2)}`} tone="green" />
        <KV k="If Loses"   v={`−${window.TR.fmtUsd(Math.abs(position.ifLoses), 2)}`} tone="red" />
        <KV k="Equity"     v={window.TR.fmtUsd(position.equity, 2)} />
      </div>
      <div className="flex items-center gap-1.5 pl-5 hl-l" style={{ paddingLeft: '20px' }}>
        <button className="h-[26px] px-3 border border-line-3 bg-bg-2 hover:bg-bg-hover font-mono text-[10px] tracking-[0.14em] uppercase text-text-2 hover:text-text">
          Flatten
        </button>
        <button className="h-[26px] px-3 border border-line-3 bg-bg-2 hover:bg-bg-hover font-mono text-[10px] tracking-[0.14em] uppercase text-text-2 hover:text-text">
          Reduce 50%
        </button>
      </div>
    </div>
  );
}

// ── Status bar (24px) ──────────────────────────────────────────────────────
function StatusBar() {
  const status = window.TR.status;
  const now = useClock();
  return (
    <div className="h-[24px] hl-t px-4 flex items-center gap-4 bg-bg shrink-0 font-mono text-[9.5px] tracking-[0.12em] uppercase text-text-3">
      <span>BUILD <span className="text-text-2">{status.build}</span></span>
      <span className="text-line-3">·</span>
      <span>WS <span className="text-green">{status.ws}</span></span>
      <span className="text-line-3">·</span>
      <span>FILLS 24H <span className="text-text-2">{status.fills24.toLocaleString()}</span></span>
      <span className="text-line-3">·</span>
      <span>ACTIVE <span className="text-text-2">{status.activeOrders}</span></span>
      <span className="ml-auto" />
      <span>SERVER <span className="text-text-2">{status.region}</span></span>
      <span className="text-line-3">·</span>
      <span>LAT <span className="text-emerald">{status.latency.toFixed(2)} ms</span></span>
      <span className="text-line-3">·</span>
      <span>{utcClock(now)} UTC</span>
    </div>
  );
}

// ── Chart bar above the chart pane ─────────────────────────────────────────
function ChartBar({ timeframe, setTimeframe, market, onOpenPicker }) {
  return (
    <div className="h-[32px] hl-b px-3 flex items-center justify-between bg-bg shrink-0">
      <div className="flex items-center gap-3">
        <Segmented options={['1m','5m','15m','1h']} value={timeframe} onChange={setTimeframe} />
      </div>
      <div className="flex items-center gap-3 font-mono text-[10px] text-text-3">
        <span className="flex items-center gap-1.5"><span className="w-2 h-2 bg-green" /> YES</span>
        <span className="flex items-center gap-1.5"><span className="w-2 h-2 bg-red" /> NO</span>
        <span className="text-line-3">·</span>
        <span className="flex items-center gap-1.5"><span className="w-2 h-[2px] bg-amber" /> STRIKE {market.strike.toLocaleString(undefined, { maximumFractionDigits: market.strike >= 1000 ? 0 : market.strike >= 10 ? 2 : 4 })}</span>
      </div>
    </div>
  );
}

// ── ChartColumn ─────────────────────────────────────────────────────────────
function ChartColumn({ market, timeframe, setTimeframe, onOpenPicker }) {
  const ref = trUseRef(null);
  const [size, setSize] = trUseState({ w: 0, h: 0 });

  trUseLayoutEffect(() => {
    if (!ref.current) return;
    const measure = () => {
      if (!ref.current) return;
      // offsetWidth/Height are in layout pixels — unaffected by the parent stage's transform: scale().
      const w = ref.current.offsetWidth, h = ref.current.offsetHeight;
      if (w > 0 && h > 0) setSize({ w, h });
    };
    measure();
    // Fallback re-measures in case layout settled after mount
    const t1 = setTimeout(measure, 0);
    const t2 = setTimeout(measure, 50);
    const t3 = setTimeout(measure, 200);
    const ro = new ResizeObserver(measure);
    ro.observe(ref.current);
    return () => { ro.disconnect(); clearTimeout(t1); clearTimeout(t2); clearTimeout(t3); };
  }, []);

  const [tf, setTf] = trUseState('15s');

  return (
    <div className="flex flex-col h-full min-h-0 hl-r overflow-hidden">
      <ChartBar timeframe={timeframe} setTimeframe={setTimeframe} market={market} onOpenPicker={onOpenPicker} />
      <div ref={ref} className="flex-1 min-h-0 overflow-hidden">
        {size.w > 0 && size.h > 0 && (
          <ChartStack key={`${market.asset}-${timeframe}`} width={size.w} height={size.h} market={market} timeframe={timeframe} />
        )}
      </div>
    </div>
  );
}

// ── Full TradeApp ──────────────────────────────────────────────────────────
function TradeApp({ onHome }) {
  const [timeframe, setTimeframe] = trUseState('1m');
  const [coinSym, setCoinSym] = trUseState('BTC');
  const [pickerOpen, setPickerOpen] = trUseState(false);

  // Live resolve time — next boundary of the timeframe's duration, recomputed each second
  const [nowTick, setNowTick] = trUseState(0);
  trUseEffect(() => {
    const id = setInterval(() => setNowTick(t => t + 1), 1000);
    return () => clearInterval(id);
  }, []);
  const market = trUseMemo(() => {
    const base = window.TR.marketForCoin(coinSym, timeframe);
    const minutes = { '1m': 1, '5m': 5, '15m': 15, '1h': 60 }[timeframe] || 5;
    const ms = minutes * 60 * 1000;
    const now = new Date();
    const resolve = new Date(Math.ceil((now.getTime() + 500) / ms) * ms);
    const hh = String(resolve.getUTCHours()).padStart(2, '0');
    const mm = String(resolve.getUTCMinutes()).padStart(2, '0');
    return { ...base, settleAt: `${hh}:${mm} UTC`, resolveMs: resolve.getTime() };
    // eslint-disable-next-line
  }, [coinSym, timeframe, nowTick]);

  // Real-time countdown string — always bounded by the timeframe's duration.
  const countdown = trUseMemo(() => {
    const remain = Math.max(0, market.resolveMs - Date.now());
    const mins = Math.floor(remain / 60000);
    const secs = Math.floor((remain % 60000) / 1000);
    return `${mins}:${String(secs).padStart(2, '0')}`;
    // eslint-disable-next-line
  }, [market.resolveMs, nowTick]);

  const [side, setSide] = trUseState('YES');
  const [direction, setDirection] = trUseState('Buy');
  const [orderType, setOrderType] = trUseState('Limit');
  const [tif, setTif] = trUseState('GTC');
  const [reduceOnly, setReduceOnly] = trUseState(false);
  const [margin, setMargin] = trUseState('Cross');
  const [price, setPrice] = trUseState('0.6400');
  const [size, setSize] = trUseState('500');
  const [flashing, setFlashing] = trUseState(false);

  // Live ticking YES/NO prices — base mid varies per (coin, timeframe)
  const baseYes = trUseMemo(() => window.TR.impliedYesFor(market.coin, timeframe), [market.coin, timeframe]);
  const tfMid = Math.round(baseYes * 10000) / 10000;
  const [prices, setPrices] = trUseState({ yes: tfMid, no: Math.round((1 - tfMid) * 10000) / 10000 });
  trUseEffect(() => {
    setPrices({ yes: tfMid, no: Math.round((1 - tfMid) * 10000) / 10000 });
    setPrice(tfMid.toFixed(4));
    // eslint-disable-next-line
  }, [coinSym, timeframe]);
  trUseEffect(() => {
    const id = setInterval(() => {
      setPrices(prev => {
        const yes = Math.max(0.05, Math.min(0.95, prev.yes + (Math.random() - 0.5) * 0.008));
        const yesR = Math.round(yes * 10000) / 10000;
        return { yes: yesR, no: Math.round((1 - yesR) * 10000) / 10000 };
      });
    }, 1200);
    return () => clearInterval(id);
  }, []);

  const onSubmit = () => {
    setFlashing(true);
    setTimeout(() => setFlashing(false), 240);
  };

  trUseEffect(() => {
    const h = (e) => {
      const tag = (e.target.tagName || '').toLowerCase();
      if (tag === 'input' || tag === 'textarea') return;
      if (e.key === 'b' || e.key === 'B') { setSide(s => s === 'YES' ? 'NO' : 'YES'); e.preventDefault(); }
      else if (e.key === 'Enter') { onSubmit(); e.preventDefault(); }
      else if (e.key === 'Escape') {
        setPrice(''); setSize(''); e.preventDefault();
      }
    };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, []);

  const tradePanelState = {
    side, setSide, direction, setDirection, orderType, setOrderType, tif, setTif,
    reduceOnly, setReduceOnly, margin, setMargin,
    price, setPrice, size, setSize, onSubmit, flashing,
    prices, market,
  };

  return (
    <div className="relative flex flex-col h-full w-full bg-bg text-text overflow-hidden">
      <TopNav onLogoClick={onHome} />
      <MarketHeader market={market} prices={prices} onOpenPicker={() => setPickerOpen(true)} countdown={countdown} />

      {/* Body — flex with explicit widths */}
      <div className="flex-1 min-h-0 flex overflow-hidden">
        <div className="flex-1 min-w-0 h-full">
          <ChartColumn market={market} timeframe={timeframe} setTimeframe={setTimeframe} onOpenPicker={() => setPickerOpen(true)} />
        </div>
        <div className="w-[340px] hl-r h-full overflow-hidden bg-panel">
          <OrderBook key={`${coinSym}-${timeframe}`} timeframe={timeframe} coin={market.coin} />
        </div>
        <div className="w-[360px] h-full overflow-hidden bg-panel">
          <TradePanel tradePanelState={tradePanelState} />
        </div>
      </div>

      <div className="h-[24px] hl-t bg-bg shrink-0" />

      <MarketPicker
        open={pickerOpen}
        onClose={() => setPickerOpen(false)}
        currentSym={coinSym}
        onPick={(c) => setCoinSym(c.sym)}
      />
    </div>
  );
}

Object.assign(window, { TradeApp, TopNav, MarketHeader, PositionStrip, StatusBar, ChartBar, ChartColumn });
