import { useCallback, useEffect, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Area, AreaChart, CartesianGrid, ReferenceLine, XAxis, YAxis } from "recharts";
import { motion, useReducedMotion } from "framer-motion";
import PageEnter from "@/components/ui/page-enter";
import Navigation from "@/components/landing/Navigation";
import Footer from "@/components/landing/Footer";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
} from "@/components/ui/chart";
import { apiRequest } from "@/lib/queryClient";
import { getStrategyStatus, startStrategy, stopStrategy } from "@/api/strategy";
import StrategyTimeline from "@/components/StrategyTimeline";
import { toast } from "@/hooks/use-toast";

type PaperFundsResponse = {
  funds: {
    cash?: number;
    net?: number;
  };
};

type PaperPosition = {
  symbol: string;
  qty: number;
  avg_price: number;
  last_price: number;
  pnl: number;
  pnl_pct: number;
};

type PaperPositionsResponse = {
  positions: PaperPosition[];
};

type PaperOrder = {
  id: string;
  symbol: string;
  side: string;
  qty: number;
  price: number;
  status: string;
  timestamp: string;
};

type PaperOrdersResponse = {
  orders: PaperOrder[];
};


type PaperMtmPosition = {
  symbol: string;
  qty: number;
  avg_price: number;
  ltp: number;
  pnl: number;
};

type PaperMtmResponse = {
  ts: string;
  initial_cash: number;
  cash: number;
  positions_value: number;
  positions: PaperMtmPosition[];
  unrealized_pnl: number;
  equity: number;
  price_stale?: boolean;
  price_source?: Record<string, string | null | undefined>;
};

type MarketStatusResponse = {
  status?: "OPEN" | "CLOSED";
  checked_at?: string;
};

const MotionButton = motion(Button);

function formatCurrency(value: number, decimals = 2) {
  return new Intl.NumberFormat("en-IN", {
    style: "currency",
    currency: "INR",
    minimumFractionDigits: decimals,
    maximumFractionDigits: decimals,
  }).format(value || 0);
}

function formatSignedCurrency(value: number, decimals = 2) {
  if (value === 0) {
    return formatCurrency(0, decimals);
  }
  const formatted = formatCurrency(Math.abs(value), decimals);
  return `${value > 0 ? "+" : "-"}${formatted}`;
}

function formatTimestamp(value?: string) {
  if (!value) return "—";
  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) {
    return value;
  }
  return parsed.toLocaleString();
}

function PaperTradingPortfolio() {
  const reduceMotion = useReducedMotion();
  const [sipAmount, setSipAmount] = useState(5000);
  const [initialCash, setInitialCash] = useState<number | "">("");
  const [frequencyValue, setFrequencyValue] = useState(10);
  const [frequencyUnit, setFrequencyUnit] = useState<"minutes" | "days">("minutes");
  const [strategyStatus, setStrategyStatus] = useState("STOPPED");
  const [nextSipTs, setNextSipTs] = useState<string | null>(null);
  const [nextSipCountdown, setNextSipCountdown] = useState<string | null>(null);
  const [isStarting, setIsStarting] = useState(false);
  const [isStopping, setIsStopping] = useState(false);
  const [isResetting, setIsResetting] = useState(false);
  const [addCashEnabled, setAddCashEnabled] = useState(false);
  const [addCashAmount, setAddCashAmount] = useState<number | "">("");
  const [isAddingCash, setIsAddingCash] = useState(false);
  const [mtmPositions, setMtmPositions] = useState<PaperMtmPosition[]>([]);
  const [mtmEquity, setMtmEquity] = useState<number | null>(null);
  const [mtmInitialCash, setMtmInitialCash] = useState<number | null>(null);
  const [mtmCash, setMtmCash] = useState<number | null>(null);
  const [mtmPositionsValue, setMtmPositionsValue] = useState<number | null>(null);
  const [mtmUnrealizedPnl, setMtmUnrealizedPnl] = useState<number | null>(null);
  const [mtmPnlPoints, setMtmPnlPoints] = useState<
    { date: string; pnl: number }[]
  >([]);
  const [priceStale, setPriceStale] = useState(false);
  const [marketStatus, setMarketStatus] = useState<MarketStatusResponse | null>(null);
  const [timelineKey, setTimelineKey] = useState(0);
  const skipFirstPnlPointRef = useRef(true);

  const fundsQuery = useQuery<PaperFundsResponse>({
    queryKey: ["/paper/funds"],
    queryFn: async () => {
      const res = await apiRequest("GET", "/paper/funds");
      return res.json();
    },
  });

  const positionsQuery = useQuery<PaperPositionsResponse>({
    queryKey: ["/paper/positions"],
    queryFn: async () => {
      const res = await apiRequest("GET", "/paper/positions");
      return res.json();
    },
  });

  const ordersQuery = useQuery<PaperOrdersResponse>({
    queryKey: ["/paper/orders"],
    queryFn: async () => {
      const res = await apiRequest("GET", "/paper/orders");
      return res.json();
    },
    refetchInterval: 10000,
    refetchIntervalInBackground: true,
  });


  const positions = positionsQuery.data?.positions ?? [];
  const orders = ordersQuery.data?.orders ?? [];
  const displayPositions =
    mtmPositions.length > 0
      ? mtmPositions.map((pos) => {
          const cost = pos.avg_price * pos.qty;
          const pnlPct = cost ? (pos.pnl / cost) * 100 : 0;
          return {
            symbol: pos.symbol,
            qty: pos.qty,
            avg_price: pos.avg_price,
            last_price: pos.ltp,
            pnl: pos.pnl,
            pnl_pct: pnlPct,
          };
        })
      : positions;

  const pnlSeries = mtmPnlPoints;

  const refreshStatus = useCallback(async () => {
    try {
      const status = await getStrategyStatus();
      setStrategyStatus(status?.status ?? "STOPPED");
      setNextSipTs(status?.next_eligible_ts ?? null);
    } catch {
      setStrategyStatus("STOPPED");
      setNextSipTs(null);
    }
  }, []);

  useEffect(() => {
    refreshStatus();
    const id = window.setInterval(refreshStatus, 15000);
    return () => window.clearInterval(id);
  }, [refreshStatus]);

  useEffect(() => {
    const resetFlag = window.sessionStorage.getItem("paperReset");
    if (resetFlag === "1") {
      window.sessionStorage.removeItem("paperReset");
      toast({
        title: "Paper account reset",
        description: "Ready for new run.",
      });
    }
  }, []);

  useEffect(() => {
    if (!nextSipTs) {
      setNextSipCountdown(null);
      return;
    }
    const updateCountdown = () => {
      const target = new Date(nextSipTs).getTime();
      if (Number.isNaN(target)) {
        setNextSipCountdown(null);
        return;
      }
      const diff = target - Date.now();
      if (diff <= 0) {
        setNextSipCountdown("now");
        return;
      }
      const totalSeconds = Math.floor(diff / 1000);
      const hours = Math.floor(totalSeconds / 3600);
      const minutes = Math.floor((totalSeconds % 3600) / 60);
      const seconds = totalSeconds % 60;
      const hh = hours > 0 ? `${hours}h ` : "";
      const mm = `${minutes}`.padStart(2, "0");
      const ss = `${seconds}`.padStart(2, "0");
      setNextSipCountdown(`${hh}${mm}:${ss}`);
    };
    updateCountdown();
    const id = window.setInterval(updateCountdown, 1000);
    return () => window.clearInterval(id);
  }, [nextSipTs]);

  useEffect(() => {
    let timer: number;
    const poll = async () => {
      try {
        const res = await fetch("/paper/mtm", {
          credentials: "include",
        });
        if (!res.ok) {
          return;
        }
        const data: PaperMtmResponse = await res.json();
        setMtmPositions(Array.isArray(data.positions) ? data.positions : []);
        if (typeof data.equity === "number") {
          setMtmEquity(data.equity);
        }
        if (typeof data.initial_cash === "number") {
          setMtmInitialCash(data.initial_cash);
        }
        if (typeof data.cash === "number") {
          setMtmCash(data.cash);
        }
        if (typeof data.positions_value === "number") {
          setMtmPositionsValue(data.positions_value);
        }
        if (typeof data.unrealized_pnl === "number") {
          setMtmUnrealizedPnl(data.unrealized_pnl);
        }
        if (typeof data.price_stale === "boolean") {
          setPriceStale(data.price_stale);
        }
        if (data.ts && typeof data.unrealized_pnl === "number") {
          setMtmPnlPoints((prev) => {
            if (skipFirstPnlPointRef.current && prev.length === 0) {
              skipFirstPnlPointRef.current = false;
              return prev;
            }
            const last = prev[prev.length - 1];
            if (last?.date === data.ts) {
              if (last.pnl === data.unrealized_pnl) {
                return prev;
              }
              const next = [...prev];
              next[next.length - 1] = { date: data.ts, pnl: data.unrealized_pnl };
              return next;
            }
            const next = [...prev, { date: data.ts, pnl: data.unrealized_pnl }];
            return next.length > 200 ? next.slice(-200) : next;
          });
        }
      } catch (error) {
        console.error("MTM poll failed", error);
      }
    };

    poll();
    timer = window.setInterval(() => {
      if (document.hidden) return;
      poll();
    }, 5000);
    return () => window.clearInterval(timer);
  }, []);

  useEffect(() => {
    const fetchMarketStatus = async () => {
      try {
        const res = await fetch("/market/status", {
          credentials: "include",
        });
        if (!res.ok) {
          return;
        }
        const data: MarketStatusResponse = await res.json();
        setMarketStatus(data);
      } catch {
        setMarketStatus(null);
      }
    };

    fetchMarketStatus();
    const id = window.setInterval(fetchMarketStatus, 5000);
    return () => window.clearInterval(id);
  }, []);

  const handleReset = async () => {
    const ok = window.confirm(
      "This will RESET the entire paper account.\n\n" +
        "- All positions\n" +
        "- All orders\n" +
        "- Strategy state\n\n" +
        "This cannot be undone. Continue?",
    );

    if (!ok) {
      return;
    }

    setIsResetting(true);
    try {
      const res = await fetch("/paper/reset", { method: "POST" });
      if (!res.ok) {
        throw new Error("Reset failed");
      }
      setMtmPositions([]);
      setMtmEquity(null);
      setMtmInitialCash(null);
      setMtmCash(null);
      setMtmPositionsValue(null);
      setMtmUnrealizedPnl(null);
      setMtmPnlPoints([]);
      skipFirstPnlPointRef.current = true;
      setInitialCash("");
      fundsQuery.refetch();
      positionsQuery.refetch();
      ordersQuery.refetch();
      await refreshStatus();
      setTimelineKey((value) => value + 1);
      setIsResetting(false);
    } catch (error) {
      setIsResetting(false);
      alert("Reset failed. Check backend logs.");
      console.error(error);
    }
  };

  const handleStart = async () => {
    if (typeof initialCash !== "number" || initialCash < 10000) {
      return;
    }
    skipFirstPnlPointRef.current = true;
    setIsStarting(true);
    try {
      const result = await startStrategy({
        strategy_name: "Golden Nifty",
        initial_cash: initialCash,
        sip_amount: sipAmount,
        sip_frequency: {
          value: frequencyValue,
          unit: frequencyUnit,
        },
        mode: "PAPER",
      });
      if (result?.status === "already_running") {
        toast({
          title: "Strategy already running",
          description: "The paper strategy is already active.",
        });
      }
      if (result?.status === "unsupported_mode") {
        toast({
          title: "Unsupported mode",
          description: "Paper trading is the only available mode right now.",
        });
      }
    } finally {
      setIsStarting(false);
      await refreshStatus();
    }
  };

  const handleStop = async () => {
    setIsStopping(true);
    try {
      await stopStrategy();
    } finally {
      setIsStopping(false);
      await refreshStatus();
    }
  };

  const normalizedStrategyStatus =
    strategyStatus === "RUNNING"
      ? "RUNNING"
      : strategyStatus === "WAITING"
        ? "WAITING"
        : "STOPPED";
  const canStart = typeof initialCash === "number" && initialCash >= 10000;
  const canAddCash =
    addCashEnabled && typeof addCashAmount === "number" && addCashAmount > 0;
  const strategyBadgeClass =
    normalizedStrategyStatus === "RUNNING"
      ? "bg-green-500 text-white"
      : normalizedStrategyStatus === "WAITING"
        ? "bg-yellow-500 text-white"
        : "bg-gray-400 text-white";
  const marketState = marketStatus?.status ?? "UNKNOWN";
  const marketBadgeClass =
    marketState === "OPEN"
      ? "border-emerald-500/50 bg-emerald-500/15 text-emerald-300"
      : marketState === "CLOSED"
        ? "border-amber-400/50 bg-amber-400/15 text-amber-200"
        : "border-slate-400/40 bg-slate-400/15 text-slate-200";
  const priceBadgeClass = priceStale
    ? "border-amber-400/50 bg-amber-400/15 text-amber-200"
    : "border-emerald-500/50 bg-emerald-500/15 text-emerald-300";

  const summary = [
    { label: "Initial Cash", value: mtmInitialCash ?? 0 },
    { label: "Cash Available", value: mtmCash ?? 0 },
    { label: "Invested Value", value: mtmPositionsValue ?? 0 },
    { label: "Total Equity", value: mtmEquity ?? 0 },
    { label: "Unrealized P&L", value: mtmUnrealizedPnl ?? 0 },
  ];

  const ctaMotionProps = reduceMotion
    ? {}
    : {
        whileHover: { scale: 1.02 },
        whileTap: { scale: 0.97 },
        transition: { type: "spring", stiffness: 400, damping: 25 },
      };

  const cardContainer = {
    hidden: {},
    show: {
      transition: {
        staggerChildren: 0.12,
      },
    },
  };

  const cardItem = {
    hidden: { opacity: 0, y: 14 },
    show: { opacity: 1, y: 0 },
  };

  const handleAddCash = async () => {
    if (!canAddCash || typeof addCashAmount !== "number") {
      return;
    }

    setIsAddingCash(true);
    try {
      await apiRequest("POST", "/paper/add-cash", { amount: addCashAmount });
      setMtmCash((prev) =>
        typeof prev === "number" ? prev + addCashAmount : addCashAmount
      );
      setMtmInitialCash((prev) =>
        typeof prev === "number" ? prev + addCashAmount : addCashAmount
      );
      setMtmEquity((prev) =>
        typeof prev === "number" ? prev + addCashAmount : addCashAmount
      );
      fundsQuery.refetch();
      toast({
        title: "Cash added",
        description: `${formatCurrency(addCashAmount)} added to available cash.`,
      });
      setAddCashAmount("");
    } catch (error) {
      toast({
        title: "Add cash failed",
        description: "Please try again.",
      });
      console.error(error);
    } finally {
      setIsAddingCash(false);
    }
  };

  return (
    <div className="min-h-screen text-foreground">
      <Navigation />
      <PageEnter>
        <main className="pt-24 pb-40">
          <section className="max-w-6xl mx-auto px-6 py-10 space-y-8">
          <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
            <div className="space-y-2">
              <p className="text-sm uppercase tracking-[0.25em] text-muted-foreground">
                Paper Trading Portfolio
              </p>
              <h2 className="text-3xl md:text-4xl font-bold">Paper trading (simulated)</h2>
              <p className="text-muted-foreground max-w-2xl">
                This dashboard mirrors live execution flow with simulated orders and balances.
              </p>
            </div>
            <div className="flex flex-wrap gap-2">
              <Badge variant="secondary">Paper trading (simulated)</Badge>
              <Button variant="outline" onClick={() => {
                fundsQuery.refetch();
                positionsQuery.refetch();
                ordersQuery.refetch();
              }}>
                Refresh
              </Button>
            </div>
          </div>

          <div className="rounded-2xl border border-border/60 bg-card/70 shadow-xl overflow-hidden">
            <div className="flex items-center justify-between px-6 py-4 border-b border-border/50">
              <div className="space-y-1">
                <p className="text-sm font-semibold">Paper Strategy Control</p>
                <p className="text-xs text-muted-foreground">
                  Strategy: Golden Nifty (Paper) · Assets: NIFTYBEES + GOLDBEES
                </p>
                {nextSipTs && (
                  <p className="text-xs text-muted-foreground">
                    Next SIP {nextSipCountdown ? `in ${nextSipCountdown}` : ""} ({new Date(nextSipTs).toLocaleTimeString()})
                  </p>
                )}
              </div>
              <div className="flex items-center gap-2">
                <span className={`px-2 py-1 rounded text-xs ${strategyBadgeClass}`}>
                  {normalizedStrategyStatus}
                </span>
                <Badge variant="outline" className={marketBadgeClass}>
                  {marketState === "OPEN"
                    ? "Market OPEN"
                    : marketState === "CLOSED"
                      ? "Market CLOSED"
                      : "Market UNKNOWN"}
                </Badge>
                {priceStale && (
                  <Badge variant="outline" className={priceBadgeClass}>
                    Price STALE
                  </Badge>
                )}
              </div>
            </div>
            <div className="p-6 space-y-4">
              <div className="space-y-2">
                <Label htmlFor="paper-initial-cash">Initial Cash (Paper)</Label>
                <Input
                  id="paper-initial-cash"
                  type="number"
                  min={10000}
                  value={initialCash}
                  disabled={normalizedStrategyStatus === "RUNNING"}
                  onChange={(event) => {
                    const raw = event.target.value;
                    if (raw === "") {
                      setInitialCash("");
                      return;
                    }
                    const value = Number(raw);
                    setInitialCash(Number.isNaN(value) ? "" : value);
                  }}
                />
                <p className="text-xs text-muted-foreground">
                  Used only for paper trading. No real funds involved.
                </p>
              </div>
              <div className="space-y-3 rounded-lg border border-border/60 bg-background/50 px-4 py-3">
                <div className="flex items-center gap-2">
                  <Checkbox
                    id="paper-add-cash-toggle"
                    checked={addCashEnabled}
                    onCheckedChange={(value) => setAddCashEnabled(value === true)}
                  />
                  <Label htmlFor="paper-add-cash-toggle">Add cash during run</Label>
                </div>
                <div className="grid gap-2 md:grid-cols-[1fr_auto] md:items-end">
                  <div className="space-y-2">
                    <Label htmlFor="paper-add-cash">Amount to add</Label>
                    <Input
                      id="paper-add-cash"
                      type="number"
                      min={1}
                      step={100}
                      value={addCashAmount}
                      disabled={!addCashEnabled || isAddingCash}
                      onChange={(event) => {
                        const raw = event.target.value;
                        if (raw === "") {
                          setAddCashAmount("");
                          return;
                        }
                        const value = Number(raw);
                        setAddCashAmount(Number.isNaN(value) ? "" : value);
                      }}
                    />
                  </div>
                  <Button
                    variant="secondary"
                    onClick={handleAddCash}
                    disabled={!canAddCash || isAddingCash}
                  >
                    {isAddingCash ? "Adding..." : "Add cash"}
                  </Button>
                </div>
                <p className="text-xs text-muted-foreground">
                  Adds to available cash immediately while the strategy keeps running.
                </p>
              </div>
              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="paper-sip">SIP Amount</Label>
                  <Input
                    id="paper-sip"
                    type="number"
                    min={0}
                    step={100}
                    value={sipAmount}
                    onChange={(event) => {
                      const value = Number(event.target.value);
                      setSipAmount(Number.isNaN(value) ? 0 : value);
                    }}
                  />
                </div>
                <div className="space-y-3">
                  <div className="grid gap-3 sm:grid-cols-2">
                    <div className="space-y-2">
                      <Label htmlFor="paper-frequency">Frequency</Label>
                      <Input
                        id="paper-frequency"
                        type="number"
                        min={1}
                        step={1}
                        value={frequencyValue}
                        onChange={(event) => {
                          const value = Number(event.target.value);
                          setFrequencyValue(Number.isNaN(value) ? 1 : value);
                        }}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="paper-frequency-unit">Unit</Label>
                      <select
                        id="paper-frequency-unit"
                        value={frequencyUnit}
                        onChange={(event) =>
                          setFrequencyUnit(event.target.value as "minutes" | "days")
                        }
                        className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 md:text-sm"
                      >
                        <option value="minutes">Minutes (testing)</option>
                        <option value="days">Days (long-term)</option>
                      </select>
                    </div>
                  </div>
                  <p className="text-xs text-muted-foreground">
                    Minutes mode is for paper testing only. Live SIP uses days.
                  </p>
                </div>
              </div>
              <div className="flex flex-wrap gap-2">
                <MotionButton
                  {...ctaMotionProps}
                  onClick={handleStart}
                  disabled={!canStart || isStarting || isResetting || normalizedStrategyStatus === "RUNNING"}
                  className="shimmer"
                >
                  {isStarting ? "Starting..." : "Start Paper Strategy"}
                </MotionButton>
                <Button variant="outline" onClick={handleStop} disabled={isStopping}>
                  {isStopping ? "Stopping..." : "Stop Paper Strategy"}
                </Button>
                <Button
                  variant="destructive"
                  onClick={handleReset}
                  disabled={isResetting}
                >
                  {isResetting ? "Resetting..." : "Reset Paper Account"}
                </Button>
              </div>
              {marketState === "CLOSED" ? (
                <p className="text-xs text-muted-foreground">
                  Market CLOSED - orders will execute when the next session opens.
                </p>
              ) : null}
            </div>
          </div>

          <StrategyTimeline key={timelineKey} />

          <motion.div
            className="grid gap-4 md:grid-cols-3"
            variants={cardContainer}
            initial="hidden"
            animate="show"
          >
            {summary.map((item) => (
              <motion.div
                key={item.label}
                className="rounded-xl border border-border/70 bg-card/80 p-4 shadow-sm"
                variants={cardItem}
                whileHover={{
                  y: -6,
                  boxShadow: "0 20px 40px rgba(0,0,0,0.18)",
                }}
                transition={{ type: "spring", stiffness: 300, damping: 24 }}
              >
                <p className="text-xs uppercase tracking-[0.18em] text-muted-foreground">
                  {item.label}
                </p>
                <p className="text-2xl font-semibold">
                  <motion.span
                    key={item.value ?? 0}
                    initial={{ opacity: 0.6, y: 3 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.25, ease: "easeOut" }}
                  >
                    {formatCurrency(item.value)}
                  </motion.span>
                </p>
              </motion.div>
            ))}
          </motion.div>
          <p className="text-xs text-muted-foreground">Delivery SIP · No leverage</p>

          <div className="rounded-2xl border border-border/60 bg-card/70 shadow-xl overflow-hidden">
            <div className="flex items-center justify-between px-6 py-4 border-b border-border/50">
              <div className="space-y-1">
                <p className="text-sm font-semibold">Positions</p>
                <p className="text-xs text-muted-foreground">
                  Current paper positions and unrealized P&L.
                </p>
              </div>
              <div className="flex items-center gap-3">
                <span className="text-xs text-muted-foreground">
                  Live prices · 5s refresh
                </span>
                <Badge variant="outline">{displayPositions.length} positions</Badge>
              </div>
            </div>
            {positionsQuery.isLoading && displayPositions.length === 0 ? (
              <div className="px-6 py-6 text-sm text-muted-foreground">Loading positions...</div>
            ) : displayPositions.length === 0 ? (
              <div className="px-6 py-6 text-sm text-muted-foreground">
                No paper positions yet.
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="min-w-full text-sm">
                  <thead className="bg-muted/40 text-muted-foreground">
                    <tr>
                      <th className="px-6 py-3 text-left font-medium">Symbol</th>
                      <th className="px-6 py-3 text-left font-medium">Qty</th>
                      <th className="px-6 py-3 text-left font-medium">Avg price</th>
                      <th className="px-6 py-3 text-left font-medium">LTP</th>
                      <th className="px-6 py-3 text-left font-medium">P&amp;L</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border/60">
                    {displayPositions.map((pos) => (
                      <tr key={pos.symbol}>
                        <td className="px-6 py-3 font-semibold">{pos.symbol}</td>
                        <td className="px-6 py-3">{pos.qty}</td>
                        <td className="px-6 py-3">{formatCurrency(pos.avg_price, 2)}</td>
                        <td className="px-6 py-3">{formatCurrency(pos.last_price, 2)}</td>
                        <td className="px-6 py-3">
                          <span className={pos.pnl >= 0 ? "text-emerald-400" : "text-red-400"}>
                            {formatCurrency(pos.pnl, 2)} ({pos.pnl_pct.toFixed(2)}%)
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>

          <div className="rounded-2xl border border-border/60 bg-card/70 shadow-xl overflow-hidden">
            <div className="flex items-center justify-between px-6 py-4 border-b border-border/50">
              <div className="space-y-1">
                <p className="text-sm font-semibold">Orders</p>
                <p className="text-xs text-muted-foreground">Paper order history.</p>
              </div>
              <Badge variant="outline">{orders.length} orders</Badge>
            </div>
            {ordersQuery.isLoading ? (
              <div className="px-6 py-6 text-sm text-muted-foreground">Loading orders...</div>
            ) : orders.length === 0 ? (
              <div className="px-6 py-6 text-sm text-muted-foreground">
                No paper orders yet.
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="min-w-full text-sm">
                  <thead className="bg-muted/40 text-muted-foreground">
                    <tr>
                      <th className="px-6 py-3 text-left font-medium">Order ID</th>
                      <th className="px-6 py-3 text-left font-medium">Time</th>
                      <th className="px-6 py-3 text-left font-medium">Symbol</th>
                      <th className="px-6 py-3 text-left font-medium">Side</th>
                      <th className="px-6 py-3 text-left font-medium">Qty</th>
                      <th className="px-6 py-3 text-left font-medium">Price</th>
                      <th className="px-6 py-3 text-left font-medium">Status</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border/60">
                    {orders.map((order) => (
                      <tr key={order.id}>
                        <td className="px-6 py-3 font-mono text-xs">{order.id}</td>
                        <td className="px-6 py-3 text-xs text-muted-foreground">
                          {formatTimestamp(order.timestamp)}
                        </td>
                        <td className="px-6 py-3">{order.symbol}</td>
                        <td className="px-6 py-3">{order.side}</td>
                        <td className="px-6 py-3">{order.qty}</td>
                        <td className="px-6 py-3">{formatCurrency(order.price, 2)}</td>
                        <td className="px-6 py-3">
                          <Badge variant="outline">{order.status}</Badge>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>

          <div className="rounded-2xl border border-border/60 bg-card/70 shadow-xl p-6 space-y-4">
            <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
              <div className="space-y-1">
                <p className="text-sm font-semibold">P&amp;L curve</p>
                <p className="text-xs text-muted-foreground">
                  Paper P&amp;L over time.
                </p>
              </div>
              <span className="text-xs text-muted-foreground">
                Live P&amp;L · updates every 5s
              </span>
            </div>
            {pnlSeries.length === 0 ? (
              <div className="text-sm text-muted-foreground">No P&amp;L history yet.</div>
            ) : (
              <div className="h-80">
                <ChartContainer
                  config={{
                    pnl: { label: "P&L", color: "hsl(var(--chart-1))" },
                  }}
                  className="rounded-xl bg-background/60"
                >
                  <AreaChart data={pnlSeries}>
                    <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" />
                    <XAxis
                      dataKey="date"
                      tickFormatter={(value) =>
                        new Date(value).toLocaleDateString("en-IN", {
                          month: "short",
                          day: "numeric",
                        })
                      }
                      tickLine={false}
                      axisLine={false}
                      minTickGap={24}
                    />
                    <YAxis
                      tickFormatter={(v) => {
                        const numeric = Number(v);
                        const formatted = new Intl.NumberFormat("en-IN", {
                          maximumFractionDigits: 0,
                          notation: "compact",
                        }).format(Math.abs(numeric));
                        if (numeric > 0) {
                          return `+${formatted}`;
                        }
                        if (numeric < 0) {
                          return `-${formatted}`;
                        }
                        return formatted;
                      }}
                      label={{ value: "P&L (₹)", angle: -90, position: "insideLeft" }}
                      width={80}
                    />
                    <ReferenceLine y={0} stroke="var(--border)" strokeDasharray="3 3" />
                    <ChartTooltip
                      content={
                        <ChartTooltipContent
                          labelFormatter={(value) =>
                            new Date(value as string).toLocaleDateString("en-IN", {
                              year: "numeric",
                              month: "short",
                              day: "numeric",
                            })
                          }
                          formatter={(val) => formatSignedCurrency(Number(val))}
                        />
                      }
                    />
                    <Area
                      type="monotone"
                      dataKey="pnl"
                      stroke="var(--color-pnl)"
                      fill="var(--color-pnl)"
                      fillOpacity={0.15}
                      strokeWidth={2}
                    />
                  </AreaChart>
                </ChartContainer>
              </div>
            )}
          </div>
          </section>
        </main>
      </PageEnter>
      <Footer />
    </div>
  );
}

export default PaperTradingPortfolio;
