import { useEffect } from 'react'
import { useStore } from '@/store'
import { useTradingStore } from '@/store/tradingStore'

function fmtBal(b) {
  return b.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

export function PortfolioScreen() {
  const { balance, active, history, setScreen, syncFromBackend } = useStore()
  const { selectAssetBySymbol } = useTradingStore()

  useEffect(() => {
    syncFromBackend()
  }, [])
  const wins = history.filter((h) => h.win).length
  const winRate = history.length ? (wins / history.length) * 100 : 0
  const totalProfit = history.reduce((s, h) => s + (h.win ? h.profit : -h.amount), 0)

  return (
    <div className="scr">
      <h2>Portfolio</h2>
      <div className="sub">Your trading performance</div>
      <div className="stat-row">
        <div className="stat"><div className="k">Balance</div><div className="v up">${fmtBal(balance)}</div></div>
        <div className="stat"><div className="k">Win Rate</div><div className="v">{winRate.toFixed(1)}%</div></div>
        <div className="stat">
          <div className="k">Net P&amp;L</div>
          <div className={'v ' + (totalProfit >= 0 ? 'up' : 'down')}>
            {totalProfit >= 0 ? '+' : '−'}${Math.abs(totalProfit).toFixed(2)}
          </div>
        </div>
      </div>

      {active.length > 0 && (
        <>
          <div className="section-title">Active Trades · {active.length}</div>
          {active.map((t) => {
            const remaining = Math.max(0, Math.ceil((t.expiresAt - Date.now()) / 1000))
            return (
              <div key={t.id} className="row" onClick={() => { selectAssetBySymbol(t.asset); setScreen('trade') }}>
                <div className="ic" style={{
                  background: t.dir === 'UP' ? 'rgba(31,224,122,.16)' : 'rgba(255,77,94,.16)',
                  color: t.dir === 'UP' ? 'var(--green)' : 'var(--red)',
                }}>{t.dir === 'UP' ? '↑' : '↓'}</div>
                <div>
                  <div className="name">{t.asset}</div>
                  <div className="meta">{t.dir} · ${t.amount}</div>
                </div>
                <div className="right">
                  <div className="px mono">{remaining}s</div>
                  <div className="meta">pending</div>
                </div>
              </div>
            )
          })}
        </>
      )}

      <div className="section-title">Trade History</div>
      {history.map((h) => (
        <div key={h.id} className="hist">
          <div className={'res ' + (h.win ? 'win' : 'loss')}>{h.win ? '✓' : '✕'}</div>
          <div>
            <div className="name">
              {h.asset} <span className={h.dir === 'UP' ? 'up' : 'down'} style={{ fontSize: 12 }}>{h.dir === 'UP' ? '↑' : '↓'}</span>
            </div>
            <div className="meta">{h.ago}</div>
          </div>
          <div className={'pnl ' + (h.win ? 'up' : 'down')}>
            {h.win ? '+$' + h.profit.toFixed(2) : '-$' + h.amount.toFixed(2)}
          </div>
        </div>
      ))}
    </div>
  )
}
