/* panel.jsx — Kalshi-faithful trade panel. */

const { useState: tpUseState, useEffect: tpUseEffect, useMemo: tpUseMemo, useRef: tpUseRef } = React;

// ── Brand colors per coin ──────────────────────────────────────────────────
const COIN_COLORS = {
  BTC:  '#F7931A',
  ETH:  '#627EEA',
  SOL:  '#9945FF',
  HYPE: '#10B981',
  AAVE: '#B6509E',
  LIT:  '#6D4FEC',
  ZEC:  '#ECB244',
  DOGE: '#C2A633',
  ARB:  '#28A0F0',
  AVAX: '#E84142',
  XAU:  '#E8A33D',
  XAG:  '#9CA3AF',
  WTI:  '#3F3F46',
};

// Public icon CDN. Falls back to a colored letter glyph if the symbol isn't available.
function coinIconUrl(sym) {
  if (!sym) return null;
  return `https://assets.coincap.io/assets/icons/${sym.toLowerCase()}@2x.png`;
}

// ── Per-coin market icon ──────────────────────────────────────────────────
// CoinCap PNGs already include their own colored circular background, so we
// don't paint a coloured tile behind them — that was making the icons look
// double-stacked. We only fall back to the coloured letter tile if the image
// fails to load.
function MarketIcon({ coin, size = 44 }) {
  const sym = (coin && coin.sym) || 'BTC';
  const bg = COIN_COLORS[sym] || '#666';
  const glyph = sym === 'BTC' ? '₿' : sym === 'ETH' ? 'Ξ' : sym[0];
  const fontSize = Math.round(size * 0.46);
  const radius = Math.round(size * 0.5); // full circle for image clip
  const [imgFailed, setImgFailed] = tpUseState(false);
  const url = coinIconUrl(sym);
  if (url && !imgFailed) {
    return (
      <img
        src={url}
        alt={sym}
        onError={() => setImgFailed(true)}
        style={{ width: size, height: size, borderRadius: radius, display: 'block' }}
        className="shrink-0"
      />
    );
  }
  return (
    <div
      className="flex items-center justify-center shrink-0"
      style={{ width: size, height: size, background: bg, color: '#fff', borderRadius: radius }}
    >
      <span className="font-sans font-bold leading-none" style={{ fontSize }}>{glyph}</span>
    </div>
  );
}

// ── Floating-label field card ───────────────────────────────────────────────
function FieldCard({ label, sub, value, onChange, suffix, inputRef, disabled, valueAlign = 'right', children }) {
  return (
    <div className={`bg-bg-3 border border-panel-3 rounded-lg px-4 py-2.5 transition-colors focus-within:border-emerald/60 ${disabled ? 'opacity-60' : ''}`}>
      <div className="flex items-center justify-between gap-3">
        <div className="flex flex-col gap-0.5 min-w-0">
          <div className="flex items-center gap-1.5">
            <span className="font-sans text-[13px] text-text">{label}</span>
          </div>
          {sub && <span className="font-sans text-[10.5px] text-text-3">{sub}</span>}
        </div>
        {children !== undefined ? (
          children
        ) : (
          <div className={`flex items-baseline gap-2 ${valueAlign === 'right' ? 'justify-end' : ''}`}>
            <input
              ref={inputRef}
              value={value}
              onChange={onChange}
              disabled={disabled}
              className="bg-transparent font-mono text-[22px] text-text disabled:text-text-2 text-right w-[110px]"
            />
            {suffix && <span className="font-mono text-[11px] text-text-3 shrink-0">{suffix}</span>}
          </div>
        )}
      </div>
    </div>
  );
}

// ── Up / Down big rounded pills (live ticking) ─────────────────────────────
function UpDownPills({ side, setSide, prices }) {
  const Pill = ({ which, price }) => {
    const isYes = which === 'YES';
    const active = side === which;
    const fg = isYes ? 'text-green' : 'text-red';
    const borderColor = isYes ? 'border-green' : 'border-red';
    const fill = active
      ? (isYes ? 'bg-green/[0.10]' : 'bg-red/[0.10]')
      : 'bg-transparent hover:bg-bg-hover';
    return (
      <button
        onClick={() => setSide(which)}
        className={[
          'flex-1 h-[42px] rounded-lg transition-colors flex items-center justify-center gap-2',
          borderColor, fill,
        ].join(' ')}
        style={{ borderWidth: '1.5px', borderStyle: 'solid' }}
      >
        <span className={`font-sans text-[15px] font-medium ${fg}`}>{isYes ? 'Up' : 'Down'}</span>
        <span className={`font-sans text-[15px] font-semibold ${fg}`}>
          {(price * 100).toFixed(1)}¢
        </span>
      </button>
    );
  };

  return (
    <div className="flex gap-2">
      <Pill which="YES" price={prices.yes} />
      <Pill which="NO"  price={prices.no} />
    </div>
  );
}

// ── Composed TradePanel (Kalshi layout) ────────────────────────────────────
function TradePanel({ tradePanelState }) {
  const s = tradePanelState;
  const numericSize = parseFloat(s.size) || 0;
  const numericPrice = parseFloat(s.price) || 0;
  const total = numericPrice * numericSize;
  const isTaker = s.orderType === 'Market' || s.orderType === 'IOC';
  const fee = total * (isTaker ? window.TR.fees.taker : window.TR.fees.maker);
  const isYes = s.side === 'YES';
  const direction = s.direction || 'Buy';

  // Display price in cents for the limit field (Kalshi convention)
  const cents = Math.round((parseFloat(s.price) || 0) * 100);
  const setCents = (v) => {
    const n = parseInt(String(v).replace(/[^\d]/g, ''), 10);
    if (Number.isNaN(n)) s.setPrice('');
    else s.setPrice(String(Math.min(99, Math.max(1, n)) / 100));
  };

  return (
    <div className="flex flex-col h-full bg-panel">
      {/* Title bar */}
      <div className="h-[36px] px-3 flex items-center justify-between hl-b shrink-0">
        <span className="font-mono text-[10.5px] tracking-[0.18em] uppercase text-text">TRADE</span>
        <span className="font-mono text-[9.5px] tracking-[0.12em] uppercase text-text-3 inline-flex items-center gap-1.5 h-[20px] px-2 rounded-full bg-bg-3 border border-panel-3">USDC · ETH-L2</span>
      </div>

      {/* Compact Kalshi-style card stack — fits without scroll */}
      <div className="flex-1 min-h-0 overflow-hidden p-2">
        <div className="bg-panel-2 border border-panel-3 rounded-lg p-2.5 flex flex-col gap-2 h-full">

          {/* Header row — icon + market label + action context */}
          <div className="flex items-center gap-2.5">
            <MarketIcon coin={s.market && s.market.coin} size={36} />
            <div className="flex flex-col gap-0.5 min-w-0">
              <div className="font-sans text-[11px] text-text-2 truncate">
                {(s.market && s.market.coin ? s.market.coin.sym : 'BTC')} {s.market ? s.market.duration.toLowerCase().replace('min',' min').replace('hr',' hr') : '5 min'} · <span className="text-text">${(s.market ? s.market.strike : 103247).toLocaleString(undefined, { maximumFractionDigits: (s.market && s.market.strike >= 1000) ? 0 : (s.market && s.market.strike >= 10) ? 2 : 4 })} target</span>
              </div>
              <div className="font-sans text-[12.5px] font-medium truncate">
                <span className={isYes ? 'text-green' : 'text-red'}>{direction} {isYes ? 'Yes' : 'No'}</span>
              </div>
            </div>
          </div>

          {/* Buy/Sell pill toggle + Order type dropdown */}
          <div className="flex items-center justify-between">
            <div className="inline-flex h-[26px] gap-1.5">
              {['Buy', 'Sell'].map(d => {
                const active = direction === d;
                return (
                  <button
                    key={d}
                    onClick={() => s.setDirection && s.setDirection(d)}
                    className={[
                      'px-3 h-full rounded-lg font-sans text-[11.5px] transition-colors border',
                      active ? 'bg-emerald/[0.15] text-emerald border-emerald/50' : 'bg-transparent text-text-2 border-line-3 hover:text-text'
                    ].join(' ')}
                  >{d}</button>
                );
              })}
            </div>
            <button
              onClick={() => s.setOrderType(s.orderType === 'Limit' ? 'Market' : 'Limit')}
              className="flex items-center gap-1.5 font-sans text-[11.5px] text-text-2 hover:text-text"
            >
              <span>{s.orderType}</span>
              <svg width="10" height="6" viewBox="0 0 10 6" fill="none">
                <path d="M1 1L5 5L9 1" stroke="currentColor" strokeWidth="1.3" />
              </svg>
            </button>
          </div>

          {/* Up / Down */}
          <UpDownPills side={s.side} setSide={s.setSide} prices={s.prices} />

          {/* Contracts field */}
          <FieldCard
            label="Contracts"
            sub="Max payout 1.00 per share"
            value={s.size}
            onChange={(e) => s.setSize(e.target.value)}
            suffix=""
          />

          {/* Quick size pills */}
          <div className="grid grid-cols-4 gap-1.5 -mt-0.5">
            {['25%','50%','75%','MAX'].map(q => (
              <button
                key={q}
                onClick={() => {
                  const max = 2000;
                  const mult = q === 'MAX' ? 1 : parseInt(q) / 100;
                  s.setSize(String(Math.round(max * mult)));
                }}
                className="h-[22px] rounded-lg font-sans text-[10.5px] text-text-2 hover:text-text bg-bg-2 border border-line-3"
              >{q}</button>
            ))}
          </div>

          {/* Limit price (cents) */}
          {s.orderType !== 'Market' && (
            <FieldCard
              label="Limit price (¢)"
              sub={`Mid ${(isYes ? s.prices.yes : s.prices.no).toFixed(4)}`}
              value={cents}
              onChange={(e) => setCents(e.target.value)}
            />
          )}

          {/* Expiration row — compact */}
          <div className="bg-bg-3 border border-panel-3 rounded-lg px-3 py-2">
            <div className="flex items-center justify-between gap-2">
              <span className="font-sans text-[11.5px] text-text">Expiration</span>
              <div className="flex gap-1 items-center">
                {[
                  { label: 'GTC', v: 'GTC' },
                  { label: 'IOC', v: 'IOC' },
                  { label: 'FOK', v: 'FOK' },
                ].map(opt => {
                  const active = s.tif === opt.v;
                  return (
                    <button
                      key={opt.v}
                      onClick={() => s.setTif(opt.v)}
                      className={[
                        'h-[22px] px-2.5 rounded-lg font-sans text-[11px] border transition-colors',
                        active ? 'bg-text/[0.92] text-bg border-text/0' : 'bg-bg-3 text-text-2 border-line-3 hover:text-text'
                      ].join(' ')}
                    >{opt.label}</button>
                  );
                })}
              </div>
            </div>
          </div>

          {/* Resting order option — compact, inline */}
          <label className="px-1 flex items-center justify-between cursor-pointer">
            <span className="font-sans text-[11.5px] text-text-2">Submit as resting order only</span>
            <input
              type="checkbox"
              checked={s.reduceOnly}
              onChange={e => s.setReduceOnly(e.target.checked)}
              className="appearance-none w-[14px] h-[14px] rounded border border-line-3 bg-bg-3 checked:bg-emerald checked:border-emerald cursor-pointer"
            />
          </label>

          {/* Total + outcome (compact) */}
          <div className="px-1 flex flex-col gap-1">
            <div className="flex items-center justify-between">
              <span className="font-sans text-[11px] text-text-2">Total cost</span>
              <span className="font-mono text-[12px] text-text">{window.TR.fmtUsd(total, 2)}</span>
            </div>
            <div className="flex items-center justify-between">
              <span className="font-sans text-[11px] text-text-2">{isTaker ? 'Taker fee' : 'Maker rebate'}</span>
              <span className={`font-mono text-[12px] ${!isTaker ? 'text-green' : 'text-text-2'}`}>
                {!isTaker ? '−' : ''}{window.TR.fmtUsd(Math.abs(fee), 2)} <span className="text-text-3">· {isTaker ? '+20 bps' : '−10 bps'}</span>
              </span>
            </div>
            <div className="flex items-center justify-between">
              <span className="font-sans text-[11px] text-green">If YES wins</span>
              <span className="font-mono text-[12px] text-green">+{window.TR.fmtUsd(isYes ? (1 - s.prices.yes) * numericSize : s.prices.yes * numericSize, 2)}</span>
            </div>
            <div className="flex items-center justify-between">
              <span className="font-sans text-[11px] text-red">If NO wins</span>
              <span className="font-mono text-[12px] text-red">−{window.TR.fmtUsd(isYes ? s.prices.yes * numericSize : (1 - s.prices.yes) * numericSize, 2)}</span>
            </div>
          </div>

          {/* Review CTA */}
          <button
            onClick={s.onSubmit}
            className={[
              'h-[40px] w-full rounded-lg font-sans text-[13px] font-medium transition-[filter,transform] mt-auto',
              isYes
                ? 'bg-green/[0.18] hover:bg-green/[0.28] text-green'
                : 'bg-red/[0.18]   hover:bg-red/[0.28]   text-red',
              s.flashing ? 'brightness-125 scale-[0.99]' : '',
            ].join(' ')}
          >
            Review
          </button>

          {/* Keyboard hints */}
          <div className="flex items-center justify-center gap-1.5 font-mono text-[8.5px] tracking-[0.08em] uppercase text-text-3">
            <kbd className="px-1 h-[13px] inline-flex items-center rounded border border-line-3 text-text-2">B</kbd>
            <span>side</span>
            <span className="text-line-3">·</span>
            <kbd className="px-1 h-[13px] inline-flex items-center rounded border border-line-3 text-text-2">Enter</kbd>
            <span>submit</span>
            <span className="text-line-3">·</span>
            <kbd className="px-1 h-[13px] inline-flex items-center rounded border border-line-3 text-text-2">Esc</kbd>
            <span>clear</span>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { TradePanel, UpDownPills, FieldCard, MarketIcon, COIN_COLORS });
