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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
} from "@/components/ui/chart";
import { apiRequest } from "@/lib/queryClient";
import {
  getStrategyStatus,
  resumeStrategy,
  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" | "HOLIDAY";
  reason?: string;
  checked_at?: string;
  next_open_at?: string | null;
};

type EngineStatus = {
  state?: string;
  run_id?: string | null;
  last_heartbeat_ts?: string | null;
  last_execution_ts?: string | null;
  next_eligible_ts?: string | null;
};

type StrategyStatusResponse = {
  status?: string;
  last_updated?: string | null;
  last_execution_ts?: string | null;
  next_eligible_ts?: string | null;
  run_id?: string | null;
  can_resume?: boolean;
  can_restart?: boolean;
  config?: {
    strategy?: string | null;
    sip_amount?: number | null;
    sip_frequency?: {
      value?: number | null;
      unit?: string | null;
    } | null;
    mode?: string | null;
    broker?: string | null;
    active?: boolean | null;
  } | null;
};

const MotionButton = motion(Button);

function formatMinuteTimestamp(date: Date) {
  return date.toLocaleString(undefined, {
    year: "numeric",
    month: "short",
    day: "numeric",
    hour: "numeric",
    minute: "2-digit",
  });
}

function formatRelativeSeconds(seconds: number) {
  if (!Number.isFinite(seconds)) return "";
  if (seconds <= 0) return "now";
  const total = Math.round(seconds);
  const days = Math.floor(total / 86400);
  const hours = Math.floor((total % 86400) / 3600);
  const minutes = Math.floor((total % 3600) / 60);
  const parts = [];
  if (days) parts.push(`${days}d`);
  if (hours) parts.push(`${hours}h`);
  if (!days && minutes) parts.push(`${minutes}m`);
  if (parts.length === 0) parts.push("less than 1m");
  return `in ${parts.join(" ")}`;
}

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 [strategyDetails, setStrategyDetails] = useState<StrategyStatusResponse | null>(null);
  const [isStarting, setIsStarting] = useState(false);
  const [isResuming, setIsResuming] = useState(false);
  const [isStopping, setIsStopping] = useState(false);
  const [isResetting, setIsResetting] = useState(false);
  const [freshStartRequested, setFreshStartRequested] = 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 [engineStatus, setEngineStatus] = useState<EngineStatus | null>(null);
  const [priceStale, setPriceStale] = useState(false);
  const [marketStatus, setMarketStatus] = useState<MarketStatusResponse | null>(null);
  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()) as StrategyStatusResponse;
      setStrategyDetails(status ?? null);
      setStrategyStatus(status?.status ?? "STOPPED");
      const savedAmount = Number(status?.config?.sip_amount);
      if (!freshStartRequested && Number.isFinite(savedAmount) && savedAmount > 0) {
        setSipAmount(savedAmount);
      }
      const savedFrequency = status?.config?.sip_frequency;
      const savedFrequencyValue = Number(savedFrequency?.value);
      const savedFrequencyUnit =
        savedFrequency?.unit === "minutes"
          ? "minutes"
          : savedFrequency?.unit === "days"
            ? "days"
            : null;
      if (!freshStartRequested && Number.isFinite(savedFrequencyValue) && savedFrequencyValue >= 1) {
        setFrequencyValue(savedFrequencyValue);
      }
      if (!freshStartRequested && savedFrequencyUnit) {
        setFrequencyUnit(savedFrequencyUnit);
      }
    } catch {
      setStrategyDetails(null);
      setStrategyStatus("STOPPED");
    }
  }, [freshStartRequested]);

  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.",
      });
    }
  }, []);

  const refreshEngineStatus = useCallback(async () => {
    try {
      const res = await apiRequest("GET", "/engine/status");
      const data: EngineStatus = await res.json();
      setEngineStatus(data);
    } catch {
      setEngineStatus(null);
    }
  }, []);

  useEffect(() => {
    void refreshEngineStatus();
    const id = window.setInterval(refreshEngineStatus, 5000);
    return () => window.clearInterval(id);
  }, [refreshEngineStatus]);

  useEffect(() => {
    let timer: number;
    const poll = async () => {
      try {
        const res = await apiRequest("GET", "/paper/mtm");
        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);
  }, []);

  const refreshMarketStatus = useCallback(async () => {
    try {
      const res = await apiRequest("GET", "/market/status");
      const data: MarketStatusResponse = await res.json();
      setMarketStatus(data);
    } catch {
      setMarketStatus(null);
    }
  }, []);

  useEffect(() => {
    void refreshMarketStatus();
    const id = window.setInterval(refreshMarketStatus, 5000);
    return () => window.clearInterval(id);
  }, [refreshMarketStatus]);

  useEffect(() => {
    if (!freshStartRequested && typeof mtmInitialCash === "number" && mtmInitialCash > 0) {
      setInitialCash(mtmInitialCash);
    }
  }, [freshStartRequested, mtmInitialCash]);

  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 {
      await apiRequest("POST", "/paper/reset");
      setMtmPositions([]);
      setMtmEquity(null);
      setMtmInitialCash(null);
      setMtmCash(null);
      setMtmPositionsValue(null);
      setMtmUnrealizedPnl(null);
      setMtmPnlPoints([]);
      skipFirstPnlPointRef.current = true;
      setInitialCash("");
      await Promise.all([
        fundsQuery.refetch(),
        positionsQuery.refetch(),
        ordersQuery.refetch(),
        refreshStatus(),
        refreshEngineStatus(),
        refreshMarketStatus(),
      ]);
      setFreshStartRequested(false);
    } catch (error) {
      toast({
        title: "Reset failed",
        description: error instanceof Error ? error.message : "Please try again.",
      });
      console.error(error);
    } finally {
      setIsResetting(false);
    }
  };

  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.",
        });
      }
      if (result?.status === "started" || result?.status === "restarted") {
        setFreshStartRequested(false);
        toast({
          title: "Paper strategy started",
          description: "The simulator is now running.",
        });
      }
    } catch (error) {
      toast({
        title: "Start failed",
        description: error instanceof Error ? error.message : "Please try again.",
      });
      console.error(error);
    } finally {
      setIsStarting(false);
      await Promise.allSettled([
        refreshStatus(),
        refreshEngineStatus(),
        refreshMarketStatus(),
        fundsQuery.refetch(),
        positionsQuery.refetch(),
        ordersQuery.refetch(),
      ]);
    }
  };

  const handleResume = async () => {
    setIsResuming(true);
    try {
      const result = await resumeStrategy();
      if (result?.status === "already_running") {
        toast({
          title: "Strategy already running",
          description: "The paper strategy is already active.",
        });
      } else if (result?.status === "resumed") {
        setFreshStartRequested(false);
        toast({
          title: "Paper strategy resumed",
          description: "The previous paper run has been resumed with its saved schedule.",
        });
      } else if (result?.status === "no_resumable_run") {
        setFreshStartRequested(true);
        toast({
          title: "No resumable strategy",
          description: "Start a fresh paper cycle instead.",
        });
      } else {
        toast({
          title: "Resume failed",
          description: result?.message || result?.status || "Unable to resume strategy.",
        });
      }
    } catch (error) {
      toast({
        title: "Resume failed",
        description: error instanceof Error ? error.message : "Please try again.",
      });
      console.error(error);
    } finally {
      setIsResuming(false);
      await Promise.allSettled([
        refreshStatus(),
        refreshEngineStatus(),
        refreshMarketStatus(),
        fundsQuery.refetch(),
        positionsQuery.refetch(),
        ordersQuery.refetch(),
      ]);
    }
  };

  const handleStop = async () => {
    setIsStopping(true);
    try {
      await stopStrategy();
      setFreshStartRequested(false);
      toast({
        title: "Paper strategy stopped",
        description: "The simulator has been stopped.",
      });
    } catch (error) {
      toast({
        title: "Stop failed",
        description: error instanceof Error ? error.message : "Please try again.",
      });
      console.error(error);
    } finally {
      setIsStopping(false);
      await Promise.allSettled([
        refreshStatus(),
        refreshEngineStatus(),
        refreshMarketStatus(),
        fundsQuery.refetch(),
        positionsQuery.refetch(),
        ordersQuery.refetch(),
      ]);
    }
  };

  const normalizedStrategyStatus =
    strategyStatus === "RUNNING"
      ? "RUNNING"
      : strategyStatus === "WAITING"
        ? "WAITING"
        : "STOPPED";
  const isStrategyActive =
    normalizedStrategyStatus === "RUNNING" ||
    normalizedStrategyStatus === "WAITING";
  const canResumeSavedStrategy = !!strategyDetails?.can_resume;
  const showResumeStrategy =
    !isStrategyActive && canResumeSavedStrategy && !freshStartRequested;
  const showRestartStrategy =
    !isStrategyActive && !!strategyDetails?.can_restart && !freshStartRequested;
  const showFreshStartStrategy =
    !isStrategyActive && (!canResumeSavedStrategy || freshStartRequested);
  const canEditStrategyConfig = showFreshStartStrategy;
  const canStartFresh = typeof initialCash === "number" && initialCash >= 10000;
  const canStop = isStrategyActive;
  const strategyLocked =
    !canEditStrategyConfig || isStarting || isResuming || isStopping || isResetting;
  const canAddCash =
    canStop && addCashEnabled && typeof addCashAmount === "number" && addCashAmount > 0;
  const heartbeatAgeSec = engineStatus?.last_heartbeat_ts
    ? (Date.now() - new Date(engineStatus.last_heartbeat_ts).getTime()) / 1000
    : Infinity;

  let liveness: "ACTIVE" | "STALLED" | "DEAD" | "STOPPED";
  if (!engineStatus) {
    liveness = "DEAD";
  } else if (engineStatus.state !== "RUNNING") {
    liveness = "STOPPED";
  } else if (heartbeatAgeSec < 10) {
    liveness = "ACTIVE";
  } else if (heartbeatAgeSec < 30) {
    liveness = "STALLED";
  } else {
    liveness = "DEAD";
  }

  const livenessBadgeClass =
    liveness === "ACTIVE"
      ? "border-emerald-500/50 bg-emerald-500/15 text-emerald-300"
      : liveness === "STALLED"
        ? "border-amber-400/50 bg-amber-400/15 text-amber-200"
        : liveness === "DEAD"
          ? "border-red-500/50 bg-red-500/15 text-red-300"
          : "border-slate-400/40 bg-slate-400/15 text-slate-200";
  const livenessBadgeLabel =
    liveness === "ACTIVE"
      ? "Engine active"
      : liveness === "STALLED"
        ? "Engine stalled"
        : liveness === "DEAD"
          ? "Engine dead"
          : "Engine stopped";
  const strategyBadgeClass =
    normalizedStrategyStatus === "RUNNING"
      ? "border-emerald-500/50 bg-emerald-500/10 text-emerald-400"
      : normalizedStrategyStatus === "WAITING"
        ? "border-amber-400/50 bg-amber-400/10 text-amber-300"
        : "border-red-500/40 bg-red-500/10 text-red-400";
  const strategyBadgeLabel =
    normalizedStrategyStatus === "RUNNING"
      ? "Strategy running"
      : normalizedStrategyStatus === "WAITING"
        ? "Strategy waiting"
        : "Strategy stopped";
  const marketState = marketStatus?.status ?? "UNKNOWN";
  const canArmStrategy = liveness === "ACTIVE" || liveness === "STOPPED";
  const nextEligibleTs = engineStatus?.next_eligible_ts
    ? new Date(engineStatus.next_eligible_ts)
    : null;
  const nextEligibleValid = nextEligibleTs && !Number.isNaN(nextEligibleTs.getTime());
  const eligibleSeconds = nextEligibleValid
    ? (nextEligibleTs.getTime() - Date.now()) / 1000
    : Infinity;
  const isEligible = eligibleSeconds <= 0;
  const relativeEligible = formatRelativeSeconds(eligibleSeconds);

  let nextEligibleLine = "-";
  let eligibilityStatus: string | null = "First execution pending";
  let eligibilityClass = "text-muted-foreground";

  if (nextEligibleValid) {
    eligibilityStatus = null;
    if (isEligible && marketState === "OPEN") {
      nextEligibleLine = "Now";
      eligibilityStatus = "Eligible. Execution imminent.";
      eligibilityClass = "text-emerald-400";
    } else if (isEligible && marketState === "CLOSED") {
      nextEligibleLine = `${formatMinuteTimestamp(nextEligibleTs)} (eligible)`;
      eligibilityStatus = "Eligible. Waiting for market open.";
      eligibilityClass = "text-amber-300";
    } else {
      nextEligibleLine = `${formatMinuteTimestamp(nextEligibleTs)} (${relativeEligible})`;
      eligibilityStatus = "Not eligible yet";
      eligibilityClass = "text-muted-foreground";
    }
  }

  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="mx-auto max-w-6xl space-y-8 px-4 py-8 sm:px-6 sm:py-10">
          <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-2xl font-bold sm:text-3xl md:text-4xl">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={() => {
                  void Promise.allSettled([
                    fundsQuery.refetch(),
                    positionsQuery.refetch(),
                    ordersQuery.refetch(),
                    refreshStatus(),
                    refreshEngineStatus(),
                    refreshMarketStatus(),
                  ]);
                }}
              >
                Refresh
              </Button>
            </div>
          </div>

          <div className="rounded-2xl border border-border/60 bg-card/70 shadow-xl overflow-hidden">
            <div className="flex flex-col gap-3 border-b border-border/50 px-4 py-4 sm:flex-row sm:items-center sm:justify-between sm:px-6">
              <div className="space-y-1">
                <p className="text-sm font-semibold">Strategy control</p>
                <p className="text-xs text-muted-foreground">
                  Start or stop the Golden Nifty SIP engine from the dashboard.
                </p>
              </div>
              <div className="flex flex-wrap items-center gap-2">
                <Badge variant="outline" className={livenessBadgeClass}>
                  {livenessBadgeLabel}
                </Badge>
                <Badge variant="outline" className={strategyBadgeClass}>
                  {strategyBadgeLabel}
                </Badge>
                {priceStale ? (
                  <Badge variant="outline" className="border-amber-400/50 bg-amber-400/15 text-amber-200">
                    Price stale
                  </Badge>
                ) : null}
              </div>
            </div>
            <div className="space-y-4 p-4 sm:p-6">
              <div className="rounded-lg border border-border/60 bg-background/40 px-4 py-3">
                <div className="text-xs uppercase tracking-[0.18em] text-muted-foreground">
                  Next eligible SIP
                </div>
                <div className="text-sm font-semibold text-foreground">{nextEligibleLine}</div>
                {eligibilityStatus ? (
                  <div className={`text-xs ${eligibilityClass}`}>{eligibilityStatus}</div>
                ) : null}
              </div>
              <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={strategyLocked}
                  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}
                    disabled={!canStop || isAddingCash || isStarting || isResuming || isStopping || isResetting}
                    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={!canStop || !addCashEnabled || isAddingCash || isStarting || isResuming || isStopping || isResetting}
                      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}
                    disabled={strategyLocked}
                    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-[minmax(0,1fr)_220px]">
                    <div className="space-y-2">
                      <Label htmlFor="paper-frequency">Frequency</Label>
                      <Input
                        id="paper-frequency"
                        type="number"
                        min={1}
                        step={1}
                        value={frequencyValue}
                        disabled={strategyLocked}
                        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
                        value={frequencyUnit}
                        disabled={strategyLocked}
                        onValueChange={(value) =>
                          setFrequencyUnit(value as "minutes" | "days")
                        }
                      >
                        <SelectTrigger id="paper-frequency-unit">
                          <SelectValue placeholder="Select unit" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="days">Days</SelectItem>
                          <SelectItem value="minutes">Minutes (testing)</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                  <p className="text-xs text-muted-foreground">
                    Minutes mode is for paper testing only. Live SIP uses days.
                  </p>
                </div>
              </div>
              {showResumeStrategy ? (
                <div className="text-xs text-muted-foreground">
                  Resume uses the previously saved paper SIP configuration. Choose restart to begin a fresh cycle.
                </div>
              ) : null}
              <div className="flex flex-col gap-2 sm:flex-row sm:flex-wrap">
                {showResumeStrategy ? (
                  <MotionButton
                    {...ctaMotionProps}
                    onClick={handleResume}
                    disabled={isResuming || !canArmStrategy}
                    className="w-full shimmer sm:w-auto"
                  >
                    {isResuming ? "Resuming..." : "Resume Strategy"}
                  </MotionButton>
                ) : null}
                {showFreshStartStrategy ? (
                  <MotionButton
                    {...ctaMotionProps}
                    onClick={handleStart}
                    disabled={!canStartFresh || isStarting || isResuming || isStopping || isResetting || !canArmStrategy || isStrategyActive}
                    className="w-full shimmer sm:w-auto"
                  >
                    {isStarting ? "Starting..." : "Start Strategy"}
                  </MotionButton>
                ) : null}
                {showRestartStrategy ? (
                  <Button
                    variant="outline"
                    onClick={() => setFreshStartRequested(true)}
                    disabled={isStarting || isResuming || isStopping || isResetting}
                    className="w-full sm:w-auto"
                  >
                    Restart Strategy
                  </Button>
                ) : null}
                {isStrategyActive ? (
                  <Button
                    variant="outline"
                    onClick={handleStop}
                    disabled={!canStop || isStarting || isResuming || isStopping || isResetting}
                    className="w-full sm:w-auto"
                  >
                    {isStopping ? "Stopping..." : "Stop Strategy"}
                  </Button>
                ) : null}
                <Button
                  variant="destructive"
                  onClick={handleReset}
                  disabled={isStarting || isResuming || isStopping || isResetting}
                  className="w-full sm:w-auto"
                >
                  {isResetting ? "Resetting..." : "Reset Paper Account"}
                </Button>
              </div>
              <StrategyTimeline compact />
            </div>
          </div>

          <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 flex-col gap-3 border-b border-border/50 px-4 py-4 sm:flex-row sm:items-center sm:justify-between sm:px-6">
              <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 flex-wrap 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-4 py-6 text-sm text-muted-foreground sm:px-6">Loading positions...</div>
            ) : displayPositions.length === 0 ? (
              <div className="px-4 py-6 text-sm text-muted-foreground sm:px-6">
                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-4 py-3 text-left font-medium sm:px-6">Symbol</th>
                      <th className="px-4 py-3 text-left font-medium sm:px-6">Qty</th>
                      <th className="px-4 py-3 text-left font-medium sm:px-6">Avg price</th>
                      <th className="px-4 py-3 text-left font-medium sm:px-6">LTP</th>
                      <th className="px-4 py-3 text-left font-medium sm:px-6">P&amp;L</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border/60">
                    {displayPositions.map((pos) => (
                      <tr key={pos.symbol}>
                        <td className="px-4 py-3 font-semibold sm:px-6">{pos.symbol}</td>
                        <td className="px-4 py-3 sm:px-6">{pos.qty}</td>
                        <td className="px-4 py-3 sm:px-6">{formatCurrency(pos.avg_price, 2)}</td>
                        <td className="px-4 py-3 sm:px-6">{formatCurrency(pos.last_price, 2)}</td>
                        <td className="px-4 py-3 sm:px-6">
                          <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 flex-col gap-3 border-b border-border/50 px-4 py-4 sm:flex-row sm:items-center sm:justify-between sm:px-6">
              <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-4 py-6 text-sm text-muted-foreground sm:px-6">Loading orders...</div>
            ) : orders.length === 0 ? (
              <div className="px-4 py-6 text-sm text-muted-foreground sm:px-6">
                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-4 py-3 text-left font-medium sm:px-6">Order ID</th>
                      <th className="px-4 py-3 text-left font-medium sm:px-6">Time</th>
                      <th className="px-4 py-3 text-left font-medium sm:px-6">Symbol</th>
                      <th className="px-4 py-3 text-left font-medium sm:px-6">Side</th>
                      <th className="px-4 py-3 text-left font-medium sm:px-6">Qty</th>
                      <th className="px-4 py-3 text-left font-medium sm:px-6">Price</th>
                      <th className="px-4 py-3 text-left font-medium sm:px-6">Status</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border/60">
                    {orders.map((order) => (
                      <tr key={order.id}>
                        <td className="px-4 py-3 font-mono text-xs sm:px-6">{order.id}</td>
                        <td className="px-4 py-3 text-xs text-muted-foreground sm:px-6">
                          {formatTimestamp(order.timestamp)}
                        </td>
                        <td className="px-4 py-3 sm:px-6">{order.symbol}</td>
                        <td className="px-4 py-3 sm:px-6">{order.side}</td>
                        <td className="px-4 py-3 sm:px-6">{order.qty}</td>
                        <td className="px-4 py-3 sm:px-6">{formatCurrency(order.price, 2)}</td>
                        <td className="px-4 py-3 sm:px-6">
                          <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;
