/* ============================================================
   SMC PerpDesk — Mobile-first Swiggy-style React SPA
   ============================================================ */

const { useState, useEffect, useMemo, useRef, useCallback } = React
const { motion, AnimatePresence } = window['framerMotion'] || window['Motion'] || window['framer-motion'] || window.framerMotion || {}
// framer-motion UMD attaches to window.framerMotion under different builds; pick whichever exists
const FM = window.framerMotion || window.Motion || (window['framer-motion']) || {}
const M = FM.motion || {}
const Presence = FM.AnimatePresence || (({children}) => <>{children}</>)

// ----------------------- Utility helpers -----------------------
const fmtUsd = (n, d = 2) => {
  if (n === null || n === undefined || isNaN(n)) return '—'
  const abs = Math.abs(n)
  if (abs >= 1e9) return `$${(n / 1e9).toFixed(2)}B`
  if (abs >= 1e6) return `$${(n / 1e6).toFixed(2)}M`
  if (abs >= 1e3) return `$${(n / 1e3).toFixed(2)}K`
  return `$${n.toLocaleString(undefined, { maximumFractionDigits: d })}`
}
const fmtNum = (n, d = 2) => {
  if (n === null || n === undefined || isNaN(n)) return '—'
  return Number(n).toLocaleString(undefined, { maximumFractionDigits: d })
}
const pct = (n, d = 2) => `${n >= 0 ? '+' : ''}${Number(n).toFixed(d)}%`

const apiGet = async (path) => {
  const r = await fetch(path)
  if (!r.ok) throw new Error(`HTTP ${r.status}`)
  return r.json()
}

// ----------------------- LocalStorage hooks -----------------------
const useLocalStorage = (key, initial) => {
  const [v, setV] = useState(() => {
    try {
      const raw = localStorage.getItem(key)
      return raw ? JSON.parse(raw) : initial
    } catch { return initial }
  })
  useEffect(() => {
    try { localStorage.setItem(key, JSON.stringify(v)) } catch {}
  }, [key, v])
  return [v, setV]
}

// ----------------------- Security Gate -----------------------
const PASSWORD = 'Nitishpoem'

function SecurityGate({ onUnlock }) {
  const [pw, setPw] = useState('')
  const [shake, setShake] = useState(false)
  const [show, setShow] = useState(false)
  const inputRef = useRef(null)

  useEffect(() => { inputRef.current?.focus() }, [])

  const submit = (e) => {
    e?.preventDefault()
    if (pw === PASSWORD) { onUnlock() }
    else {
      setShake(true); setTimeout(() => setShake(false), 450)
    }
  }

  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center bg-surface-900/92 backdrop-blur-xl px-5">
      <div className="absolute inset-0 -z-10 opacity-50"
           style={{background:'radial-gradient(60% 50% at 50% 30%, rgba(252,98,18,0.25), transparent 70%)'}}/>
      <M.div
        initial={{ y: 24, opacity: 0, scale: .96 }}
        animate={{ y: 0, opacity: 1, scale: 1, x: shake ? [0,-12,12,-8,8,-4,4,0] : 0 }}
        transition={{ duration: .45 }}
        className="glass w-full max-w-sm rounded-3xl p-6 shadow-card"
      >
        <div className="flex items-center gap-3 mb-4">
          <div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-brand-400 to-brand-600 flex items-center justify-center shadow-pop">
            <i className="fa-solid fa-shield-halved text-white text-xl"></i>
          </div>
          <div>
            <div className="text-[11px] uppercase tracking-widest text-brand-300">Security Gate</div>
            <div className="text-lg font-bold">SMC PerpDesk</div>
          </div>
        </div>
        <p className="text-sm text-white/70 mb-5 leading-relaxed">
          This terminal is restricted. Enter the access key to unlock institutional signal routing,
          Polymarket flow, and real-time SMC/ICT analysis.
        </p>
        <form onSubmit={submit} className="space-y-3">
          <div className="relative">
            <input
              ref={inputRef}
              type={show ? 'text' : 'password'}
              value={pw}
              onChange={(e) => setPw(e.target.value)}
              placeholder="Enter access key…"
              className="w-full bg-surface-700/70 border border-white/10 rounded-2xl px-4 py-3.5 text-base font-medium pr-12 placeholder:text-white/30"
              autoComplete="off"
              autoCapitalize="off"
              spellCheck="false"
            />
            <button type="button" onClick={() => setShow(v => !v)}
              className="absolute right-3 top-1/2 -translate-y-1/2 w-9 h-9 rounded-xl bg-white/5 flex items-center justify-center text-white/70">
              <i className={`fa-solid ${show ? 'fa-eye-slash' : 'fa-eye'}`}></i>
            </button>
          </div>
          <button type="submit"
            className="tap w-full py-3.5 rounded-2xl text-base font-bold bg-gradient-to-r from-brand-500 to-brand-600 shadow-pop">
            <i className="fa-solid fa-lock-open mr-2"></i> Unlock Terminal
          </button>
        </form>
        <div className="mt-5 flex items-center justify-between text-[11px] text-white/45">
          <span><i className="fa-solid fa-circle text-emerald-400 mr-1.5 text-[8px]"></i>No data fetched until unlock</span>
          <span>v1.0</span>
        </div>
      </M.div>
    </div>
  )
}

// ----------------------- Header / Search bar -----------------------
function Header({ symbol, onOpenSearch }) {
  return (
    <div className="sticky top-0 z-40 sticky-blur px-4 pt-3 pb-2.5 border-b border-white/5">
      <div className="flex items-center justify-between mb-2.5">
        <div className="flex items-center gap-2">
          <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-brand-400 to-brand-600 flex items-center justify-center shadow-pop">
            <i className="fa-solid fa-bolt text-white"></i>
          </div>
          <div className="leading-tight">
            <div className="text-[13px] font-bold">SMC PerpDesk</div>
            <div className="text-[10px] text-white/50 -mt-0.5 flex items-center gap-1">
              <span className="relative w-1.5 h-1.5 rounded-full bg-emerald-400 live-dot"></span>
              Real-time · No mocks
            </div>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <button className="tap w-9 h-9 rounded-xl bg-surface-700/70 border border-white/10 flex items-center justify-center">
            <i className="fa-solid fa-bell text-sm text-white/80"></i>
          </button>
          <button className="tap w-9 h-9 rounded-xl bg-surface-700/70 border border-white/10 flex items-center justify-center">
            <i className="fa-solid fa-user text-sm text-white/80"></i>
          </button>
        </div>
      </div>
      <button onClick={onOpenSearch}
        className="tap w-full text-left flex items-center gap-3 bg-surface-700/70 border border-white/10 rounded-2xl px-4 py-3">
        <i className="fa-solid fa-magnifying-glass text-brand-300"></i>
        <span className="text-[13px] text-white/60 truncate">
          Search perps · current: <span className="text-white font-semibold">{symbol}</span>
        </span>
        <span className="ml-auto text-[10px] uppercase tracking-widest text-brand-300 font-bold">scan</span>
      </button>
    </div>
  )
}

// ----------------------- Bottom Nav -----------------------
const TABS = [
  { id: 'home', label: 'Signal', icon: 'fa-bullseye' },
  { id: 'scan', label: 'Scanner', icon: 'fa-radar' },
  { id: 'poly', label: 'Polymarket', icon: 'fa-chart-pie' },
  { id: 'stats', label: 'Stats', icon: 'fa-chart-line' },
]
function BottomNav({ tab, setTab }) {
  return (
    <div className="bottom-nav fixed bottom-0 left-0 right-0 z-40 bg-surface-900/95 backdrop-blur-xl border-t border-white/5">
      <div className="grid grid-cols-4 max-w-md mx-auto">
        {TABS.map(t => {
          const active = tab === t.id
          return (
            <button key={t.id} onClick={() => setTab(t.id)}
              className="tap relative py-2.5 flex flex-col items-center justify-center">
              <div className={`w-11 h-7 rounded-full flex items-center justify-center transition ${active ? 'bg-brand-500/20' : ''}`}>
                <i className={`fa-solid ${t.icon === 'fa-radar' ? 'fa-satellite-dish' : t.icon} text-[15px] ${active ? 'text-brand-400' : 'text-white/55'}`}></i>
              </div>
              <span className={`text-[10px] mt-0.5 font-semibold ${active ? 'text-brand-300' : 'text-white/55'}`}>{t.label}</span>
              {active && <M.div layoutId="navdot" className="absolute -top-px h-[2px] w-10 bg-brand-400 rounded-full" />}
            </button>
          )
        })}
      </div>
    </div>
  )
}

// ----------------------- Search / Symbol picker -----------------------
function SymbolSearch({ open, onClose, onPick }) {
  const [q, setQ] = useState('')
  const [list, setList] = useState([])
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (!open) return
    setLoading(true)
    apiGet('/api/futures/top').then(r => setList(r.data || [])).finally(() => setLoading(false))
  }, [open])

  const filtered = useMemo(() => {
    const s = q.trim().toUpperCase()
    if (!s) return list
    return list.filter(x => x.symbol.includes(s))
  }, [q, list])

  if (!open) return null
  return (
    <Presence>
      <M.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
        className="fixed inset-0 z-50 bg-surface-900/95 backdrop-blur-xl">
        <div className="max-w-md mx-auto h-full flex flex-col">
          <div className="flex items-center gap-2 p-3 border-b border-white/5">
            <button className="tap w-9 h-9 rounded-xl bg-surface-700/70 flex items-center justify-center" onClick={onClose}>
              <i className="fa-solid fa-arrow-left"></i>
            </button>
            <input
              autoFocus
              value={q}
              onChange={(e) => setQ(e.target.value)}
              placeholder="Search BTCUSDT, ETHUSDT…"
              className="flex-1 bg-surface-700/70 rounded-xl px-4 py-2.5 text-sm border border-white/10"
            />
          </div>
          <div className="flex-1 overflow-y-auto p-3 space-y-2">
            {loading && <div className="text-center text-white/50 py-8">Loading top perps…</div>}
            {!loading && filtered.map(x => (
              <M.button
                whileTap={{ scale: 0.98 }}
                key={x.symbol}
                onClick={() => { onPick(x.symbol); onClose() }}
                className="w-full glass rounded-2xl p-3.5 flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-full bg-gradient-to-br from-surface-600 to-surface-700 flex items-center justify-center font-bold text-[11px]">
                    {x.symbol.replace('USDT', '').slice(0, 4)}
                  </div>
                  <div className="text-left">
                    <div className="font-semibold text-sm">{x.symbol}</div>
                    <div className="text-[11px] text-white/50">Vol {fmtUsd(x.volume)}</div>
                  </div>
                </div>
                <div className="text-right">
                  <div className="text-sm font-mono">{fmtNum(x.lastPrice, x.lastPrice < 1 ? 6 : 2)}</div>
                  <div className={`text-[11px] font-bold ${x.priceChangePercent >= 0 ? 'text-emerald-400' : 'text-rose-400'}`}>
                    {pct(x.priceChangePercent)}
                  </div>
                </div>
              </M.button>
            ))}
          </div>
        </div>
      </M.div>
    </Presence>
  )
}

// ----------------------- Top movers carousel -----------------------
function TopMovers({ onPick }) {
  const [list, setList] = useState([])
  useEffect(() => {
    apiGet('/api/futures/top').then(r => setList((r.data || []).slice(0, 14))).catch(() => {})
  }, [])
  return (
    <div className="px-4 mt-4">
      <div className="flex items-center justify-between mb-2">
        <div className="text-[11px] uppercase tracking-widest text-white/55 font-bold">Top by Volume</div>
        <span className="text-[10px] text-brand-300 font-bold">Binance Futures</span>
      </div>
      <div className="flex gap-2.5 overflow-x-auto no-scrollbar snap-x-mandatory pb-1 -mx-4 px-4">
        {list.length === 0 && Array.from({length:6}).map((_,i) => (
          <div key={i} className="snap-start shrink-0 w-36 h-24 shimmer rounded-2xl" />
        ))}
        {list.map(x => (
          <M.button whileTap={{ scale: 0.96 }} key={x.symbol} onClick={() => onPick(x.symbol)}
            className="snap-start shrink-0 w-36 glass rounded-2xl p-3 text-left">
            <div className="flex items-center justify-between">
              <div className="text-[11px] font-bold text-white/90">{x.symbol.replace('USDT','')}</div>
              <span className={`text-[10px] font-bold ${x.priceChangePercent>=0?'text-emerald-400':'text-rose-400'}`}>{pct(x.priceChangePercent,1)}</span>
            </div>
            <div className="font-mono text-base font-bold mt-1.5">{fmtNum(x.lastPrice, x.lastPrice<1?5:2)}</div>
            <div className="text-[10px] text-white/45 mt-0.5">Vol {fmtUsd(x.volume)}</div>
          </M.button>
        ))}
      </div>
    </div>
  )
}

// ----------------------- Timeframe Switcher -----------------------
const TFS = ['5m','15m','1h','4h','1d']
function TFSwitcher({ value, onChange }) {
  return (
    <div className="flex gap-1.5 bg-surface-800/80 border border-white/5 p-1 rounded-2xl">
      {TFS.map(tf => (
        <button key={tf} onClick={() => onChange(tf)}
          className={`tap flex-1 py-2 text-[12px] font-bold rounded-xl transition ${value===tf?'bg-brand-500 text-white shadow-pop':'text-white/60'}`}>
          {tf}
        </button>
      ))}
    </div>
  )
}

// ----------------------- Trade Card -----------------------
function TradeCard({ data, symbol, tf }) {
  if (!data) return null
  const s = data.signal
  const sm = data.summary
  const m = data.market || {}
  const isLong = s.side === 'LONG'
  const isShort = s.side === 'SHORT'
  const noTrade = s.side === 'NO_TRADE'
  const glow = isLong ? 'trade-glow-long' : isShort ? 'trade-glow-short' : 'trade-glow-flat'
  const pillCls = isLong ? 'pill-long' : isShort ? 'pill-short' : 'pill-flat'

  const dec = (sm.lastPrice || 0) < 1 ? 6 : (sm.lastPrice || 0) < 100 ? 4 : 2

  return (
    <M.div initial={{ y: 18, opacity: 0 }} animate={{ y: 0, opacity: 1 }} transition={{ duration: .35 }}
      className={`mt-4 mx-4 rounded-3xl glass p-4 ${glow}`}>
      {/* Header */}
      <div className="flex items-start justify-between">
        <div>
          <div className="text-[10px] uppercase tracking-widest text-white/55 font-bold">Next Trade · Perp Futures</div>
          <div className="text-xl font-extrabold mt-0.5">{symbol} <span className="text-white/40 text-sm font-bold">· {tf}</span></div>
        </div>
        <div className={`px-3 py-1.5 rounded-full text-[11px] font-extrabold tracking-wider ${pillCls}`}>
          {s.side}
        </div>
      </div>

      {/* Confidence */}
      <div className="mt-3">
        <div className="flex items-center justify-between text-[11px] text-white/55 mb-1">
          <span>Confidence</span>
          <span className="font-bold text-white">{s.confidence}/100</span>
        </div>
        <div className="h-1.5 bg-white/5 rounded-full overflow-hidden">
          <M.div initial={{ width: 0 }} animate={{ width: `${s.confidence}%` }} transition={{ duration: .8 }}
            className={`h-full ${isLong?'bg-emerald-400':isShort?'bg-rose-400':'bg-white/30'}`}/>
        </div>
      </div>

      {/* Price levels */}
      <div className="mt-4 grid grid-cols-1 gap-1.5">
        <div className="level-row bg-surface-700/60">
          <span className="text-[12px] text-white/65"><i className="fa-solid fa-arrow-right-to-bracket text-brand-300 mr-2"></i>Entry</span>
          <span className="font-mono text-[14px] font-bold tick">{fmtNum(s.entry, dec)}</span>
        </div>
        <div className="level-row bg-rose-500/10 border border-rose-500/20">
          <span className="text-[12px] text-rose-300"><i className="fa-solid fa-shield-halved mr-2"></i>Stop Loss</span>
          <span className="font-mono text-[14px] font-bold tick text-rose-300">{fmtNum(s.stop, dec)}</span>
        </div>
        <div className="level-row bg-emerald-500/10 border border-emerald-500/20">
          <span className="text-[12px] text-emerald-300"><i className="fa-solid fa-flag mr-2"></i>TP1 · RR {s.rr1}</span>
          <span className="font-mono text-[14px] font-bold tick text-emerald-300">{fmtNum(s.tp1, dec)}</span>
        </div>
        <div className="level-row bg-emerald-500/10 border border-emerald-500/20">
          <span className="text-[12px] text-emerald-300"><i className="fa-solid fa-flag-checkered mr-2"></i>TP2 · RR {s.rr2}</span>
          <span className="font-mono text-[14px] font-bold tick text-emerald-300">{fmtNum(s.tp2, dec)}</span>
        </div>
      </div>

      {/* Reasons */}
      <div className="mt-4 grid grid-cols-1 gap-1.5">
        <div className="text-[11px] uppercase tracking-widest text-white/55 font-bold">Institutional Logic</div>
        {s.reasons.map((r, i) => (
          <div key={i} className="text-[12.5px] leading-relaxed flex gap-2">
            <i className="fa-solid fa-square-caret-right text-brand-400 mt-0.5"></i>
            <span className="text-white/85">{r}</span>
          </div>
        ))}
      </div>

      {/* Context chips */}
      <div className="mt-3 flex flex-wrap gap-1.5">
        <Chip label={`Trend: ${sm.trend}`} tone={sm.trend==='bullish'?'green':sm.trend==='bearish'?'red':'gray'}/>
        <Chip label={`Zone: ${sm.premiumDiscount}`} tone={sm.premiumDiscount==='discount'?'green':sm.premiumDiscount==='premium'?'red':'gray'}/>
        <Chip label={`FVGs: ${sm.counts.unmitigatedFVGs}`} />
        <Chip label={`OBs: ${sm.counts.orderBlocks}`} />
        <Chip label={`Sweeps: ${sm.counts.sweeps}`} />
      </div>

      {/* Save / Track */}
      <SignalTracker signal={s} summary={sm} symbol={symbol} tf={tf}/>

      {/* Market microstructure */}
      <div className="mt-4 grid grid-cols-2 gap-2">
        <Mini label="Open Interest (USD)" value={m.openInterest?.openInterestUsd ? fmtUsd(parseFloat(m.openInterest.openInterestUsd)) : (m.openInterest?.openInterest ? fmtNum(parseFloat(m.openInterest.openInterest)) : '—')} />
        <Mini label="Funding (next)"
          value={m.funding?.fundingRate ? `${(parseFloat(m.funding.fundingRate)*100).toFixed(4)}%` : '—'}
          tone={m.funding?.fundingRate ? (parseFloat(m.funding.fundingRate)>0?'green':'red') : 'gray'}/>
        <Mini label="Top Trader L/S" value={m.topTraderAccountRatio?.longShortRatio ? fmtNum(parseFloat(m.topTraderAccountRatio.longShortRatio),2) : '—'}
          tone={m.topTraderAccountRatio?.longShortRatio ? (parseFloat(m.topTraderAccountRatio.longShortRatio)>1?'green':'red') : 'gray'}/>
        <Mini label="OI Vol (period)" value={m.topTraderPositionRatio?.openInterest ? fmtNum(parseFloat(m.topTraderPositionRatio.openInterest)) : '—'}/>
        <Mini label="Taker Buy/Sell" value={m.takerBuySell?.buySellRatio ? fmtNum(parseFloat(m.takerBuySell.buySellRatio),2) : '—'}
          tone={m.takerBuySell?.buySellRatio ? (parseFloat(m.takerBuySell.buySellRatio)>1?'green':'red') : 'gray'}/>
        <Mini label="Mark Price"
          value={m.funding?.markPrice ? fmtNum(parseFloat(m.funding.markPrice), 2) : '—'}/>
      </div>
    </M.div>
  )
}

function Chip({ label, tone='gray' }) {
  const map = {
    green: 'bg-emerald-500/15 text-emerald-300 border-emerald-500/25',
    red:   'bg-rose-500/15 text-rose-300 border-rose-500/25',
    gray:  'bg-white/5 text-white/70 border-white/10',
  }
  return <span className={`px-2 py-1 rounded-full text-[10.5px] font-bold border ${map[tone]}`}>{label}</span>
}

function Mini({ label, value, tone='gray' }) {
  const map = {
    green: 'text-emerald-300', red: 'text-rose-300', gray: 'text-white'
  }
  return (
    <div className="bg-surface-700/55 border border-white/5 rounded-2xl px-3 py-2.5">
      <div className="text-[10px] uppercase tracking-widest text-white/45 font-bold">{label}</div>
      <div className={`font-mono text-[13px] font-bold mt-0.5 ${map[tone]}`}>{value}</div>
    </div>
  )
}

// ----------------------- Signal Tracker (saves to localStorage) -----------------------
function SignalTracker({ signal, summary, symbol, tf }) {
  const [tracked, setTracked] = useLocalStorage('smc:tracked', [])
  const id = `${symbol}-${tf}-${signal.generatedAt}`
  const exists = tracked.some(t => t.id === id)

  const save = () => {
    if (signal.side === 'NO_TRADE') return
    if (exists) return
    const item = {
      id, symbol, tf,
      side: signal.side,
      entry: signal.entry, stop: signal.stop, tp1: signal.tp1, tp2: signal.tp2,
      rr1: signal.rr1, rr2: signal.rr2,
      confidence: signal.confidence,
      reasons: signal.reasons,
      generatedAt: signal.generatedAt,
      status: 'open',
      result: null,
      closedAt: null,
      closedPrice: null,
    }
    setTracked([item, ...tracked].slice(0, 200))
  }

  return (
    <div className="mt-4 flex gap-2">
      <button onClick={save} disabled={signal.side==='NO_TRADE' || exists}
        className={`tap flex-1 py-3 rounded-2xl text-[13px] font-extrabold ${
          signal.side==='NO_TRADE' || exists
            ? 'bg-white/5 text-white/40'
            : 'bg-gradient-to-r from-brand-500 to-brand-600 shadow-pop'
        }`}>
        <i className={`fa-solid ${exists?'fa-check':'fa-bookmark'} mr-2`}></i>
        {exists ? 'Tracking' : 'Track Signal'}
      </button>
      <button onClick={() => navigator?.clipboard?.writeText(JSON.stringify({symbol, tf, ...signal}, null, 2))}
        className="tap py-3 px-4 rounded-2xl bg-surface-700/70 border border-white/10 text-[13px] font-bold">
        <i className="fa-solid fa-copy mr-1.5"></i>Copy
      </button>
    </div>
  )
}

// ----------------------- Home View (Signal) -----------------------
function HomeView({ symbol, setSymbol, tf, setTf, onOpenSearch }) {
  const [data, setData] = useState(null)
  const [loading, setLoading] = useState(true)
  const [err, setErr] = useState(null)
  const fetchSignal = useCallback(async () => {
    setLoading(true); setErr(null)
    try {
      const j = await apiGet(`/api/signal?symbol=${symbol}&interval=${tf}`)
      setData(j)
    } catch (e) { setErr(e.message) } finally { setLoading(false) }
  }, [symbol, tf])

  useEffect(() => { fetchSignal() }, [fetchSignal])
  // auto-refresh every 60s
  useEffect(() => {
    const id = setInterval(fetchSignal, 60000)
    return () => clearInterval(id)
  }, [fetchSignal])

  return (
    <>
      <Header symbol={symbol} onOpenSearch={onOpenSearch} />
      <TopMovers onPick={(s) => setSymbol(s)} />

      <div className="px-4 mt-4">
        <div className="flex items-center justify-between mb-2">
          <div className="text-[11px] uppercase tracking-widest text-white/55 font-bold">Timeframe</div>
          <button onClick={fetchSignal} className="tap text-[11px] font-bold text-brand-300">
            <i className="fa-solid fa-rotate mr-1"></i>Refresh
          </button>
        </div>
        <TFSwitcher value={tf} onChange={setTf}/>
      </div>

      {loading && (
        <div className="mt-4 mx-4 rounded-3xl glass p-4 space-y-3">
          <div className="h-6 w-40 shimmer rounded-md"/>
          <div className="h-12 shimmer rounded-2xl"/>
          <div className="h-12 shimmer rounded-2xl"/>
          <div className="h-12 shimmer rounded-2xl"/>
        </div>
      )}
      {err && <div className="mt-4 mx-4 rounded-2xl bg-rose-500/10 border border-rose-500/20 p-3 text-rose-300 text-sm">Error: {err}</div>}
      {!loading && data && <TradeCard data={data} symbol={symbol} tf={tf}/>}

      <SMCBreakdown data={data} loading={loading}/>
      <div className="h-28"/>
    </>
  )
}

function SMCBreakdown({ data, loading }) {
  if (loading || !data) return null
  const sm = data.summary
  return (
    <div className="mt-5 mx-4">
      <div className="text-[11px] uppercase tracking-widest text-white/55 font-bold mb-2">SMC / ICT Map</div>
      <div className="glass rounded-3xl p-4 space-y-3">
        <div className="grid grid-cols-3 gap-2">
          <Mini label="Trend" value={sm.trend}/>
          <Mini label="Zone" value={sm.premiumDiscount}/>
          <Mini label="Last Price" value={fmtNum(sm.lastPrice, sm.lastPrice<1?6:2)}/>
        </div>
        <div className="grid grid-cols-3 gap-2">
          <Mini label="Range High" value={fmtNum(sm.dealingRange.high, sm.lastPrice<1?6:2)}/>
          <Mini label="Equilibrium" value={fmtNum(sm.dealingRange.mid, sm.lastPrice<1?6:2)}/>
          <Mini label="Range Low" value={fmtNum(sm.dealingRange.low, sm.lastPrice<1?6:2)}/>
        </div>

        <Section title="Recent Liquidity Sweeps" empty={sm.recentSweeps?.length===0}>
          {sm.recentSweeps.map((s,i)=>(
            <div key={i} className="flex items-center justify-between py-1.5 text-[12px]">
              <span className={`font-bold ${s.type==='buy_side'?'text-rose-300':'text-emerald-300'}`}>
                <i className={`fa-solid ${s.type==='buy_side'?'fa-arrow-up':'fa-arrow-down'} mr-1`}></i>
                {s.type==='buy_side'?'BSL Sweep':'SSL Sweep'}
              </span>
              <span className="font-mono">{fmtNum(s.level, sm.lastPrice<1?6:2)}</span>
            </div>
          ))}
        </Section>

        <Section title="Latest Structure (BOS/CHoCH)" empty={sm.recentStructure?.length===0}>
          {sm.recentStructure.map((s,i)=>(
            <div key={i} className="flex items-center justify-between py-1.5 text-[12px]">
              <span className={`font-bold ${s.direction==='bullish'?'text-emerald-300':'text-rose-300'}`}>
                {s.type} · {s.direction}
              </span>
              <span className="font-mono">{fmtNum(s.level, sm.lastPrice<1?6:2)}</span>
            </div>
          ))}
        </Section>

        <Section title={`Unmitigated FVGs (${sm.counts.unmitigatedFVGs})`} empty={sm.recentFVGs?.length===0}>
          {sm.recentFVGs.filter(f=>!f.mitigated).slice(-5).map((f,i)=>(
            <div key={i} className="flex items-center justify-between py-1.5 text-[12px]">
              <span className={`font-bold ${f.type==='bullish'?'text-emerald-300':'text-rose-300'}`}>{f.type.toUpperCase()} FVG</span>
              <span className="font-mono">{fmtNum(f.bottom, sm.lastPrice<1?6:2)} – {fmtNum(f.top, sm.lastPrice<1?6:2)}</span>
            </div>
          ))}
        </Section>

        <Section title="Order Blocks" empty={sm.recentOBs?.length===0}>
          {sm.recentOBs.slice(-5).map((o,i)=>(
            <div key={i} className="flex items-center justify-between py-1.5 text-[12px]">
              <span className={`font-bold ${o.type==='bullish'?'text-emerald-300':'text-rose-300'}`}>
                {o.type.toUpperCase()} OB · {o.strength.toFixed(2)}%
              </span>
              <span className="font-mono">{fmtNum(o.bottom, sm.lastPrice<1?6:2)} – {fmtNum(o.top, sm.lastPrice<1?6:2)}</span>
            </div>
          ))}
        </Section>
      </div>
    </div>
  )
}

function Section({ title, empty, children }) {
  return (
    <div className="bg-surface-700/40 rounded-2xl border border-white/5 p-3">
      <div className="text-[10.5px] uppercase tracking-widest text-white/55 font-bold mb-1">{title}</div>
      {empty ? <div className="text-[12px] text-white/40">No data.</div> : <div className="divide-y divide-white/5">{children}</div>}
    </div>
  )
}

// ----------------------- Scanner View -----------------------
function ScanView() {
  const [tf, setTf] = useState('15m')
  const [data, setData] = useState([])
  const [loading, setLoading] = useState(true)
  const [filter, setFilter] = useState('ALL')

  const run = useCallback(async () => {
    setLoading(true)
    try {
      const j = await apiGet(`/api/scan?interval=${tf}&symbols=BTCUSDT,ETHUSDT,SOLUSDT,BNBUSDT,XRPUSDT,DOGEUSDT,ADAUSDT,AVAXUSDT,LINKUSDT,LTCUSDT,ARBUSDT,SUIUSDT,APTUSDT,OPUSDT,TIAUSDT,SEIUSDT,INJUSDT,RNDRUSDT,NEARUSDT,FILUSDT`)
      setData(j.results || [])
    } catch {} finally { setLoading(false) }
  }, [tf])

  useEffect(() => { run() }, [run])

  const filtered = data.filter(x => filter==='ALL' || x.side === filter)

  return (
    <>
      <div className="sticky top-0 z-30 sticky-blur px-4 pt-4 pb-3 border-b border-white/5">
        <div className="flex items-center justify-between mb-3">
          <div>
            <div className="text-[10px] uppercase tracking-widest text-brand-300 font-bold">SMC/ICT Scanner</div>
            <div className="text-lg font-extrabold">Multi-symbol Setups</div>
          </div>
          <button onClick={run} className="tap w-10 h-10 rounded-xl bg-surface-700/70 border border-white/10">
            <i className="fa-solid fa-rotate"></i>
          </button>
        </div>
        <div className="flex gap-2">
          <div className="flex-1"><TFSwitcher value={tf} onChange={setTf}/></div>
        </div>
        <div className="flex gap-1.5 mt-2 overflow-x-auto no-scrollbar">
          {['ALL','LONG','SHORT','NO_TRADE'].map(f => (
            <button key={f} onClick={()=>setFilter(f)}
              className={`tap shrink-0 px-3 py-1.5 rounded-full text-[11px] font-bold border ${filter===f?'bg-brand-500 border-brand-500':'bg-white/5 border-white/10 text-white/70'}`}>
              {f.replace('_',' ')}
            </button>
          ))}
        </div>
      </div>

      <div className="p-4 space-y-2.5">
        {loading && Array.from({length:6}).map((_,i)=>(<div key={i} className="h-24 shimmer rounded-2xl"/>))}
        {!loading && filtered.map(x => (
          <M.div key={x.symbol} initial={{opacity:0,y:8}} animate={{opacity:1,y:0}}
            className="glass rounded-2xl p-3.5 press-tilt">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2.5">
                <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-surface-600 to-surface-700 flex items-center justify-center text-[10px] font-extrabold">
                  {x.symbol.replace('USDT','').slice(0,4)}
                </div>
                <div>
                  <div className="text-sm font-extrabold">{x.symbol}</div>
                  <div className="text-[10.5px] text-white/55">{x.trend} · {x.pd}</div>
                </div>
              </div>
              <div className={`px-2.5 py-1 rounded-full text-[10.5px] font-extrabold ${
                x.side==='LONG'?'pill-long':x.side==='SHORT'?'pill-short':'pill-flat'
              }`}>{x.side?.replace('_',' ')}</div>
            </div>
            {x.side !== 'NO_TRADE' && (
              <div className="mt-3 grid grid-cols-4 gap-1.5 text-[10.5px]">
                <div className="bg-surface-700/60 rounded-lg p-1.5">
                  <div className="text-white/45">Entry</div><div className="font-mono text-[11px] font-bold">{fmtNum(x.entry, x.lastPrice<1?5:2)}</div>
                </div>
                <div className="bg-rose-500/10 rounded-lg p-1.5">
                  <div className="text-rose-300/80">SL</div><div className="font-mono text-[11px] font-bold text-rose-300">{fmtNum(x.stop, x.lastPrice<1?5:2)}</div>
                </div>
                <div className="bg-emerald-500/10 rounded-lg p-1.5">
                  <div className="text-emerald-300/80">TP1</div><div className="font-mono text-[11px] font-bold text-emerald-300">{fmtNum(x.tp1, x.lastPrice<1?5:2)}</div>
                </div>
                <div className="bg-emerald-500/10 rounded-lg p-1.5">
                  <div className="text-emerald-300/80">RR</div><div className="font-mono text-[11px] font-bold text-emerald-300">{x.rr1}</div>
                </div>
              </div>
            )}
            <div className="mt-2 flex items-center justify-between text-[10.5px] text-white/55">
              <span>Last: <span className="font-mono text-white/85">{fmtNum(x.lastPrice, x.lastPrice<1?6:2)}</span></span>
              <span>Conf: <span className="text-white/85 font-bold">{x.confidence||0}</span></span>
            </div>
          </M.div>
        ))}
        {!loading && filtered.length === 0 && (
          <div className="text-center text-white/45 py-12">No setups in this filter.</div>
        )}
      </div>
      <div className="h-28"/>
    </>
  )
}

// ----------------------- Polymarket / Macro View -----------------------
function PolyView() {
  const [overview, setOverview] = useState(null)
  const [poly, setPoly] = useState(null)
  const [trades, setTrades] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    (async () => {
      setLoading(true)
      try {
        const [a,b,c] = await Promise.all([
          apiGet('/api/market/overview').catch(()=>null),
          apiGet('/api/polymarket/markets').catch(()=>null),
          apiGet('/api/polymarket/trades').catch(()=>null),
        ])
        setOverview(a); setPoly(b); setTrades((c?.trades)||[])
      } finally { setLoading(false) }
    })()
  }, [])

  const fg = overview?.fearGreed?.data?.[0]
  const g = overview?.global?.data
  const trending = overview?.trending?.coins || []
  const markets = overview?.markets || []
  const polyMarkets = poly?.markets || []
  const polyEvents = poly?.events || []

  return (
    <>
      <div className="sticky top-0 z-30 sticky-blur px-4 pt-4 pb-3 border-b border-white/5">
        <div className="text-[10px] uppercase tracking-widest text-brand-300 font-bold">Macro Flow</div>
        <div className="text-lg font-extrabold">Polymarket & Crypto Sentiment</div>
      </div>

      <div className="p-4 space-y-4">
        {/* Macro hero strip */}
        <div className="grid grid-cols-3 gap-2">
          <Mini label="Fear & Greed"
            value={fg ? `${fg.value} · ${fg.value_classification}` : (loading?'…':'—')}
            tone={fg ? (parseInt(fg.value)>=60?'green':parseInt(fg.value)<=40?'red':'gray') : 'gray'}/>
          <Mini label="Total Mcap" value={g?.total_market_cap?.usd ? fmtUsd(g.total_market_cap.usd) : (loading?'…':'—')}/>
          <Mini label="BTC Dom"
            value={g?.market_cap_percentage?.btc ? `${g.market_cap_percentage.btc.toFixed(2)}%` : (loading?'…':'—')}/>
        </div>

        {/* Trending coins carousel */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <div className="text-[11px] uppercase tracking-widest text-white/55 font-bold">Trending Now</div>
            <span className="text-[10px] text-brand-300 font-bold">CoinGecko</span>
          </div>
          <div className="flex gap-2 overflow-x-auto no-scrollbar snap-x-mandatory pb-1 -mx-4 px-4">
            {loading && Array.from({length:5}).map((_,i)=>(<div key={i} className="snap-start shrink-0 w-32 h-20 shimmer rounded-2xl"/>))}
            {trending.slice(0,12).map((t,i)=>(
              <div key={i} className="snap-start shrink-0 w-36 glass rounded-2xl p-2.5">
                <div className="flex items-center gap-2">
                  <img src={t.item?.thumb} className="w-7 h-7 rounded-full" alt=""/>
                  <div className="text-[12px] font-bold truncate">{t.item?.symbol}</div>
                </div>
                <div className="text-[10px] text-white/55 truncate mt-1">{t.item?.name}</div>
                <div className="text-[10.5px] mt-1">Rank #{t.item?.market_cap_rank || '—'}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Polymarket events */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <div className="text-[11px] uppercase tracking-widest text-white/55 font-bold">Polymarket Top Events</div>
            <span className="text-[10px] text-brand-300 font-bold">Live</span>
          </div>
          <div className="space-y-2">
            {loading && Array.from({length:4}).map((_,i)=>(<div key={i} className="h-20 shimmer rounded-2xl"/>))}
            {!loading && polyEvents.slice(0,8).map((e,i) => <PolyEventCard key={e.id || i} ev={e}/>)}
          </div>
        </div>

        {/* Polymarket markets */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <div className="text-[11px] uppercase tracking-widest text-white/55 font-bold">Trending Prediction Markets</div>
          </div>
          <div className="space-y-2">
            {loading && Array.from({length:4}).map((_,i)=>(<div key={i} className="h-20 shimmer rounded-2xl"/>))}
            {!loading && polyMarkets.slice(0,12).map((m,i) => <PolyMarketCard key={m.id || i} m={m}/>)}
          </div>
        </div>

        {/* Whale Trades */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <div className="text-[11px] uppercase tracking-widest text-white/55 font-bold">Whale Flow · Recent Polymarket Trades</div>
            <span className="text-[10px] text-brand-300 font-bold">Top traders</span>
          </div>
          <div className="space-y-2">
            {loading && Array.from({length:4}).map((_,i)=>(<div key={i} className="h-16 shimmer rounded-2xl"/>))}
            {!loading && trades.slice(0,30).map((t,i) => <PolyTradeRow key={i} t={t}/>)}
            {!loading && trades.length === 0 && <div className="text-white/40 text-sm">No recent trades returned.</div>}
          </div>
        </div>

        {/* Top 30 crypto market */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <div className="text-[11px] uppercase tracking-widest text-white/55 font-bold">Top 30 by Mcap</div>
          </div>
          <div className="space-y-1.5">
            {loading && Array.from({length:6}).map((_,i)=>(<div key={i} className="h-12 shimmer rounded-xl"/>))}
            {!loading && markets.map((m) => (
              <div key={m.id} className="flex items-center justify-between bg-surface-700/45 border border-white/5 rounded-xl px-3 py-2">
                <div className="flex items-center gap-2.5 min-w-0">
                  <img src={m.image} className="w-7 h-7 rounded-full" alt=""/>
                  <div className="min-w-0">
                    <div className="text-[12.5px] font-bold truncate">{m.name}</div>
                    <div className="text-[10px] text-white/45">{m.symbol?.toUpperCase()} · #{m.market_cap_rank}</div>
                  </div>
                </div>
                <div className="text-right shrink-0">
                  <div className="font-mono text-[12.5px] font-bold">${fmtNum(m.current_price, m.current_price<1?6:2)}</div>
                  <div className={`text-[10.5px] font-bold ${m.price_change_percentage_24h>=0?'text-emerald-400':'text-rose-400'}`}>
                    {pct(m.price_change_percentage_24h, 2)}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
      <div className="h-28"/>
    </>
  )
}

function parsePolyOutcomes(m) {
  // Polymarket Gamma returns outcomePrices and outcomes as JSON-string arrays.
  let prices = m.outcomePrices, outcomes = m.outcomes
  if (typeof prices === 'string') { try { prices = JSON.parse(prices) } catch { prices = [] } }
  if (typeof outcomes === 'string') { try { outcomes = JSON.parse(outcomes) } catch { outcomes = [] } }
  return { prices: prices || [], outcomes: outcomes || [] }
}

function PolyMarketCard({ m }) {
  const { prices, outcomes } = parsePolyOutcomes(m)
  const yesIdx = outcomes.findIndex(o => /yes/i.test(o))
  const yesP = yesIdx >= 0 ? parseFloat(prices[yesIdx]) : (prices[0] ? parseFloat(prices[0]) : null)
  const vol = parseFloat(m.volume24hr || m.volume || 0)
  return (
    <M.div whileTap={{scale:.98}} className="glass rounded-2xl p-3 press-tilt">
      <div className="flex items-start justify-between gap-2">
        <div className="text-[12.5px] font-bold leading-snug line-clamp-2">{m.question || m.slug}</div>
        {yesP !== null && !isNaN(yesP) && (
          <div className="shrink-0 px-2.5 py-1 rounded-lg bg-brand-500/15 border border-brand-500/30 text-brand-300 font-extrabold text-[12px] tick">
            {(yesP*100).toFixed(0)}%
          </div>
        )}
      </div>
      <div className="mt-2 flex items-center justify-between text-[10.5px] text-white/55">
        <span><i className="fa-solid fa-fire mr-1 text-brand-400"></i>Vol24h {fmtUsd(vol)}</span>
        <span>{m.endDate ? new Date(m.endDate).toLocaleDateString() : '—'}</span>
      </div>
      {prices.length > 0 && (
        <div className="mt-2 grid gap-1">
          {outcomes.map((o, i) => (
            <div key={i} className="flex items-center justify-between text-[11px]">
              <span className="text-white/75">{o}</span>
              <span className="font-mono font-bold">{(parseFloat(prices[i])*100).toFixed(1)}%</span>
            </div>
          ))}
        </div>
      )}
    </M.div>
  )
}

function PolyEventCard({ ev }) {
  const vol = parseFloat(ev.volume24hr || ev.volume || 0)
  const liq = parseFloat(ev.liquidity || 0)
  return (
    <M.div whileTap={{scale:.98}} className="glass rounded-2xl p-3 press-tilt">
      <div className="flex items-start gap-2.5">
        {ev.image && <img src={ev.image} className="w-10 h-10 rounded-lg object-cover" alt=""/>}
        <div className="min-w-0 flex-1">
          <div className="text-[12.5px] font-bold leading-snug line-clamp-2">{ev.title}</div>
          <div className="mt-1 flex flex-wrap items-center gap-2 text-[10.5px] text-white/55">
            <span><i className="fa-solid fa-fire mr-1 text-brand-400"></i>Vol24h {fmtUsd(vol)}</span>
            <span><i className="fa-solid fa-water mr-1 text-blue-400"></i>Liq {fmtUsd(liq)}</span>
            {ev.endDate && <span>{new Date(ev.endDate).toLocaleDateString()}</span>}
          </div>
        </div>
      </div>
    </M.div>
  )
}

function PolyTradeRow({ t }) {
  const usd = parseFloat(t.size || t.usdcSize || t.usdSize || 0)
  const price = parseFloat(t.price || 0)
  const side = (t.side || t.outcome || '').toLowerCase()
  const isBuy = /buy/.test(side) || /yes/.test(side)
  const ts = t.timestamp ? new Date((t.timestamp.toString().length===10? t.timestamp*1000 : t.timestamp)).toLocaleTimeString() : '—'
  const title = t.title || t.eventSlug || t.market || t.slug || '—'
  return (
    <div className="flex items-center justify-between bg-surface-700/45 border border-white/5 rounded-xl px-3 py-2">
      <div className="min-w-0 flex-1">
        <div className="text-[12px] font-bold truncate">{title}</div>
        <div className="text-[10px] text-white/45">
          {t.proxyWallet ? `${t.proxyWallet.slice(0,6)}…${t.proxyWallet.slice(-4)} · ` : ''}{ts}
        </div>
      </div>
      <div className="text-right shrink-0">
        <div className={`text-[11px] font-extrabold ${isBuy?'text-emerald-300':'text-rose-300'}`}>
          {isBuy?'BUY':'SELL'} {price?`@ ${(price*100).toFixed(0)}¢`:''}
        </div>
        <div className="font-mono text-[11px] font-bold">{fmtUsd(usd)}</div>
      </div>
    </div>
  )
}

// ----------------------- Stats / Performance Analytics -----------------------
function StatsView() {
  const [tracked, setTracked] = useLocalStorage('smc:tracked', [])
  const [busy, setBusy] = useState(false)

  // Resolve open signals using current price
  const resolve = useCallback(async () => {
    if (busy) return
    setBusy(true)
    try {
      const open = tracked.filter(t => t.status === 'open')
      // Group by symbol to minimize calls
      const symbols = Array.from(new Set(open.map(t => t.symbol)))
      const priceMap = {}
      await Promise.all(symbols.map(async s => {
        try {
          const j = await apiGet(`/api/klines?symbol=${s}&interval=1m&limit=2`)
          const last = j.candles?.[j.candles.length-1]
          if (last) priceMap[s] = last.c
        } catch {}
      }))
      const updated = tracked.map(t => {
        if (t.status !== 'open') return t
        const p = priceMap[t.symbol]
        if (!p) return t
        let result = null
        if (t.side === 'LONG') {
          if (p <= t.stop) result = 'loss'
          else if (p >= t.tp1) result = 'win'
        } else if (t.side === 'SHORT') {
          if (p >= t.stop) result = 'loss'
          else if (p <= t.tp1) result = 'win'
        }
        if (result) {
          return { ...t, status: 'closed', result, closedAt: Date.now(), closedPrice: p }
        }
        return { ...t, lastChecked: Date.now(), lastCheckedPrice: p }
      })
      setTracked(updated)
    } finally { setBusy(false) }
  }, [tracked, busy, setTracked])

  // Auto-resolve once on view, then every 90s
  useEffect(() => {
    resolve()
    const id = setInterval(resolve, 90000)
    return () => clearInterval(id)
  }, []) // eslint-disable-line

  const closed = tracked.filter(t => t.status === 'closed')
  const wins = closed.filter(t => t.result === 'win')
  const losses = closed.filter(t => t.result === 'loss')
  const winRate = closed.length ? (wins.length / closed.length) * 100 : 0

  // Streaks
  const sorted = [...closed].sort((a,b) => (a.closedAt||0) - (b.closedAt||0))
  let curStreak = 0, curType = null, bestWin = 0, bestLoss = 0
  for (const t of sorted) {
    if (t.result === curType) curStreak++
    else { curStreak = 1; curType = t.result }
    if (curType === 'win') bestWin = Math.max(bestWin, curStreak)
    else bestLoss = Math.max(bestLoss, curStreak)
  }
  const lastStreak = curStreak
  const lastType = curType

  // R-multiples (TP1 RR vs -1)
  let totalR = 0
  closed.forEach(t => { totalR += t.result === 'win' ? (t.rr1 || 1) : -1 })

  const clearAll = () => {
    if (confirm('Clear all tracked signals?')) setTracked([])
  }

  return (
    <>
      <div className="sticky top-0 z-30 sticky-blur px-4 pt-4 pb-3 border-b border-white/5 flex items-center justify-between">
        <div>
          <div className="text-[10px] uppercase tracking-widest text-brand-300 font-bold">Performance</div>
          <div className="text-lg font-extrabold">Signal Analytics</div>
        </div>
        <div className="flex gap-2">
          <button onClick={resolve} className="tap w-10 h-10 rounded-xl bg-surface-700/70 border border-white/10 flex items-center justify-center">
            <i className={`fa-solid fa-rotate ${busy?'fa-spin':''}`}></i>
          </button>
          <button onClick={clearAll} className="tap w-10 h-10 rounded-xl bg-rose-500/10 border border-rose-500/20 flex items-center justify-center">
            <i className="fa-solid fa-trash text-rose-300"></i>
          </button>
        </div>
      </div>

      <div className="p-4 space-y-4">
        {/* Hero stats */}
        <div className="glass rounded-3xl p-4">
          <div className="text-[11px] uppercase tracking-widest text-white/55 font-bold">Win Rate</div>
          <div className="flex items-end gap-2 mt-1">
            <div className="text-4xl font-extrabold tick">{winRate.toFixed(1)}%</div>
            <div className="text-white/55 text-[12px] mb-1.5">{wins.length}W / {losses.length}L · {closed.length} closed</div>
          </div>
          <div className="mt-3 h-2.5 bg-rose-500/30 rounded-full overflow-hidden">
            <M.div initial={{width:0}} animate={{width:`${winRate}%`}} transition={{duration:.7}}
              className="h-full bg-emerald-400"/>
          </div>
        </div>
        <div className="grid grid-cols-2 gap-2">
          <Mini label="Total Profit Trades" value={String(wins.length)} tone="green"/>
          <Mini label="Total Lost Trades" value={String(losses.length)} tone="red"/>
          <Mini label="Best Win Streak" value={String(bestWin)}/>
          <Mini label="Worst Loss Streak" value={String(bestLoss)}/>
          <Mini label="Current Streak" value={lastType?`${lastStreak} ${lastType}`:'—'}
            tone={lastType==='win'?'green':lastType==='loss'?'red':'gray'}/>
          <Mini label="Net R (TP1)" value={`${totalR>=0?'+':''}${totalR.toFixed(2)}R`}
            tone={totalR>=0?'green':'red'}/>
        </div>

        {/* History */}
        <div>
          <div className="text-[11px] uppercase tracking-widest text-white/55 font-bold mb-2">History</div>
          {tracked.length === 0 && (
            <div className="glass rounded-2xl p-6 text-center text-white/55 text-sm">
              No tracked signals yet. Open the Signal tab and tap <span className="font-bold text-white">Track Signal</span>.
            </div>
          )}
          <div className="space-y-2">
            {tracked.map(t => <HistoryRow key={t.id} t={t} onUpdate={(upd)=>{
              setTracked(tracked.map(x => x.id===upd.id ? upd : x))
            }}/>)}
          </div>
        </div>
      </div>
      <div className="h-28"/>
    </>
  )
}

function HistoryRow({ t, onUpdate }) {
  const isOpen = t.status === 'open'
  const win = t.result === 'win'
  const tone = isOpen ? 'gray' : win ? 'green' : 'red'
  const dec = (t.entry || 0) < 1 ? 6 : 2

  const markWin = () => onUpdate({ ...t, status: 'closed', result: 'win', closedAt: Date.now() })
  const markLoss = () => onUpdate({ ...t, status: 'closed', result: 'loss', closedAt: Date.now() })

  return (
    <div className={`glass rounded-2xl p-3 border ${isOpen?'border-white/10':win?'border-emerald-500/30':'border-rose-500/30'}`}>
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <div className={`px-2 py-0.5 rounded-full text-[10px] font-extrabold ${t.side==='LONG'?'pill-long':'pill-short'}`}>{t.side}</div>
          <div className="text-[12.5px] font-bold">{t.symbol} <span className="text-white/45 font-medium">· {t.tf}</span></div>
        </div>
        <div className={`text-[10.5px] font-extrabold ${isOpen?'text-white/55':win?'text-emerald-300':'text-rose-300'}`}>
          {isOpen ? 'OPEN' : win ? `WIN +${(t.rr1||1).toFixed(2)}R` : 'LOSS -1R'}
        </div>
      </div>
      <div className="mt-2 grid grid-cols-4 gap-1.5 text-[10.5px]">
        <Cell label="Entry" v={fmtNum(t.entry, dec)}/>
        <Cell label="SL" v={fmtNum(t.stop, dec)} tone="red"/>
        <Cell label="TP1" v={fmtNum(t.tp1, dec)} tone="green"/>
        <Cell label="Conf" v={String(t.confidence||0)}/>
      </div>
      <div className="mt-2 flex items-center justify-between text-[10px] text-white/45">
        <span>{new Date(t.generatedAt).toLocaleString()}</span>
        {isOpen && (
          <div className="flex gap-1.5">
            <button onClick={markWin} className="tap px-2 py-1 rounded-md bg-emerald-500/15 text-emerald-300 font-bold border border-emerald-500/25">+ Win</button>
            <button onClick={markLoss} className="tap px-2 py-1 rounded-md bg-rose-500/15 text-rose-300 font-bold border border-rose-500/25">− Loss</button>
          </div>
        )}
        {!isOpen && t.closedPrice && <span>Closed @ {fmtNum(t.closedPrice, dec)}</span>}
      </div>
    </div>
  )
}

function Cell({ label, v, tone='gray' }) {
  const map = {green:'text-emerald-300 bg-emerald-500/10', red:'text-rose-300 bg-rose-500/10', gray:'bg-surface-700/60'}
  return (
    <div className={`rounded-lg p-1.5 ${map[tone]}`}>
      <div className="text-white/55 text-[9.5px]">{label}</div>
      <div className="font-mono text-[11px] font-bold">{v}</div>
    </div>
  )
}

// ----------------------- Root App -----------------------
function App() {
  const [unlocked, setUnlocked] = useLocalStorage('smc:unlocked', false)
  const [tab, setTab] = useState('home')
  const [symbol, setSymbol] = useState('BTCUSDT')
  const [tf, setTf] = useState('15m')
  const [searchOpen, setSearchOpen] = useState(false)

  return (
    <div className="max-w-md mx-auto relative">
      <div className={unlocked ? '' : 'app-locked'}>
        {tab === 'home' && (
          <HomeView
            symbol={symbol} setSymbol={setSymbol}
            tf={tf} setTf={setTf}
            onOpenSearch={() => setSearchOpen(true)}
          />
        )}
        {tab === 'scan' && <ScanView/>}
        {tab === 'poly' && <PolyView/>}
        {tab === 'stats' && <StatsView/>}
        <BottomNav tab={tab} setTab={setTab}/>
        <SymbolSearch open={searchOpen} onClose={() => setSearchOpen(false)} onPick={setSymbol}/>
      </div>
      {!unlocked && <SecurityGate onUnlock={() => setUnlocked(true)}/>}
    </div>
  )
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>)
