import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type React from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { motion } from "framer-motion";
import { Wallet, BarChart3, AlertCircle, RefreshCcw, PlugZap } from "lucide-react";
import BrokerConnectDialog from "./BrokerConnectDialog";
import LoginRequiredDialog from "./LoginRequiredDialog";
import { getQueryFn, apiRequest, queryClient } from "@/lib/queryClient";
import { getStrategyStatus, resumeStrategy, startStrategy, stopStrategy } from "@/api/strategy";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import StrategyTimeline from "@/components/StrategyTimeline";
import AutoLoginSetup from "@/components/AutoLoginSetup";
import { toast } from "@/hooks/use-toast";
import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
} from "@/components/ui/chart";
import {
  Area,
  AreaChart,
  CartesianGrid,
  XAxis,
  YAxis,
} from "recharts";
import type { User } from "@shared/schema";

type BrokerStatusResponse = {
  connected: boolean;
  broker?: string;
  connected_at?: string;
  userName?: string;
  brokerUserId?: string;
  authState?: string;
};

type HoldingsResponse = {
  holdings: any[];
};

type PositionsResponse = {
  positions: any[];
};

type MarketStatusResponse = {
  status?: "OPEN" | "CLOSED" | "HOLIDAY";
  reason?: string;
  checked_at?: string;
  next_open_at?: string | null;
};

type FundsResponse = {
  funds?: {
    net?: number;
    cash?: number;
    withdrawable?: number;
    utilized?: number;
    balance?: number;
    available?: {
      live_balance?: number;
      cash?: number;
      opening_balance?: number;
    };
    raw?: any;
  };
};

type EquityCurveResponse = {
  startDate: string;
  endDate: string;
  exactFrom?: string | null;
  points: { date: string; value: number }[];
};

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;
};

type SessionUser = Pick<User, "id" | "username">;

const MotionButton = motion(Button);
const BROKER_DATA_REFRESH_MS = 30_000;

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

function formatDateInput(date: Date) {
  return date.toISOString().slice(0, 10);
}

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 buildReconnectRedirectUrl() {
  const url = new URL(`${window.location.origin}/login`);
  url.searchParams.set("flow", "reconnect");
  return url.toString();
}

function formatBrokerName(broker?: string | null) {
  const normalized = (broker || "").trim().toUpperCase();
  if (normalized === "GROWW") return "Groww";
  if (normalized === "ZERODHA") return "Zerodha";
  return normalized || "broker";
}

function isBrokerAuthError(error: unknown) {
  const message = String((error as { message?: string } | null)?.message || "").toLowerCase();
  if (!message) {
    return false;
  }
  return (
    message.includes("401:") ||
    message.includes("session expired") ||
    message.includes("please reconnect") ||
    message.includes("broker session expired")
  );
}

function firstNumber(...values: unknown[]) {
  for (const value of values) {
    const parsed = Number(value);
    if (Number.isFinite(parsed)) {
      return parsed;
    }
  }
  return 0;
}

function getSettledQuantity(item: any) {
  return firstNumber(item?.settled_quantity, item?.quantity, item?.qty);
}

function getT1Quantity(item: any) {
  return firstNumber(item?.t1_quantity);
}

function getEffectiveQuantity(item: any) {
  return firstNumber(item?.effective_quantity, getSettledQuantity(item) + getT1Quantity(item));
}

function getNetQuantity(item: any) {
  const parsed = Number(item?.net_quantity);
  if (Number.isFinite(parsed)) {
    return parsed;
  }
  return getEffectiveQuantity(item);
}

function formatFrequencyLabel(value?: number | null, unit?: string | null) {
  const safeValue = Number(value);
  if (!Number.isFinite(safeValue) || safeValue <= 0 || !unit) {
    return null;
  }
  const normalizedUnit = unit === "minutes" ? "minute" : unit === "days" ? "day" : unit;
  const pluralizedUnit = safeValue === 1 ? normalizedUnit : `${normalizedUnit}s`;
  return `${safeValue} ${pluralizedUnit}`;
}

function getAveragePrice(item: any) {
  return firstNumber(item?.average_price, item?.avg_price);
}

function getLastPrice(item: any) {
  return firstNumber(item?.last_price, item?.close_price, getAveragePrice(item));
}

function getDisplayPnl(item: any) {
  return firstNumber(
    item?.display_pnl,
    getNetQuantity(item) * (getLastPrice(item) - getAveragePrice(item)),
  );
}

function getHoldingValue(item: any) {
  const netQuantity = getNetQuantity(item);
  if (Number.isFinite(Number(item?.net_quantity)) && netQuantity <= 0) {
    return 0;
  }
  const brokerValue = Number(item?.holding_value);
  if (Number.isFinite(brokerValue) && brokerValue >= 0) {
    return brokerValue;
  }
  return Math.max(netQuantity, 0) * Math.abs(getLastPrice(item));
}

function getPortfolioItemKey(item: any, idx: number) {
  return `${item.tradingsymbol || item.symbol || item.instrument_token || item.exchange || "item"}-${idx}`;
}

function renderPortfolioRows(items: any[]) {
  return items.map((item, idx) => {
    const qty = Number.isFinite(Number(item?.net_quantity))
      ? getNetQuantity(item)
      : getEffectiveQuantity(item);
    const settledQty = getSettledQuantity(item);
    const t1Qty = getT1Quantity(item);
    const avg = getAveragePrice(item);
    const ltp = getLastPrice(item);
    const pnl = getDisplayPnl(item);
    return (
      <tr key={getPortfolioItemKey(item, idx)}>
        <td className="px-4 py-3 sm:px-6">
          <div className="flex items-center gap-2">
            <span className="font-semibold">
              {item.tradingsymbol || item.symbol || "Instrument"}
            </span>
            <Badge variant="outline">{item.exchange || item.exchange_type || "N/A"}</Badge>
            {item.product ? <Badge variant="secondary">{item.product}</Badge> : null}
          </div>
        </td>
        <td className="px-4 py-3 sm:px-6">
          <div className="flex flex-col">
            <span>{qty}</span>
            {t1Qty > 0 && settledQty <= 0 ? (
              <span className="text-xs text-amber-300">T1 pending</span>
            ) : null}
          </div>
        </td>
        <td className="px-4 py-3 sm:px-6">{formatCurrency(avg, { decimals: 2 })}</td>
        <td className="px-4 py-3 sm:px-6">{ltp ? formatCurrency(ltp, { decimals: 2 }) : "-"}</td>
        <td className="px-4 py-3 sm:px-6">
          <span className={pnl >= 0 ? "text-emerald-500" : "text-red-500"}>
            {formatCurrency(pnl, { decimals: 2 })}
          </span>
        </td>
      </tr>
    );
  });
}

function getAvailableFundsValue(funds?: FundsResponse["funds"] | null) {
  return firstNumber(
    funds?.available?.live_balance,
    funds?.raw?.equity?.available?.live_balance,
    funds?.raw?.equity?.available?.cash,
    funds?.raw?.available?.live_balance,
    funds?.balance,
    funds?.cash,
    funds?.withdrawable,
    funds?.net,
    funds?.raw?.equity?.net,
    funds?.raw?.net,
    funds?.available?.opening_balance,
    funds?.raw?.equity?.available?.opening_balance,
    funds?.raw?.available?.opening_balance,
  );
}

function getFreshStartPreferenceKey(userId?: string | null, runId?: string | null) {
  if (!userId || !runId) {
    return null;
  }
  return `quantfortune:fresh-start:live:${userId}:${runId}`;
}

function readFreshStartPreference(key: string | null) {
  if (!key) {
    return false;
  }
  try {
    return window.localStorage.getItem(key) === "1";
  } catch {
    return false;
  }
}

function writeFreshStartPreference(key: string | null, value: boolean) {
  if (!key) {
    return;
  }
  try {
    if (value) {
      window.localStorage.setItem(key, "1");
    } else {
      window.localStorage.removeItem(key);
    }
  } catch {
    return;
  }
}

function usePrefersReducedMotion() {
  const [prefersReducedMotion, setPrefersReducedMotion] = useState(false);

  useEffect(() => {
    const mediaQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setPrefersReducedMotion(mediaQuery.matches);
    update();

    if (mediaQuery.addEventListener) {
      mediaQuery.addEventListener("change", update);
      return () => mediaQuery.removeEventListener("change", update);
    }

    mediaQuery.addListener(update);
    return () => mediaQuery.removeListener(update);
  }, []);

  return prefersReducedMotion;
}

export default function PortfolioSection() {
  const sectionRef = useRef<HTMLElement | null>(null);
  const [isVisible, setIsVisible] = useState(false);
  const [scrollY, setScrollY] = useState(0);
  const prefersReducedMotion = usePrefersReducedMotion();
  const [loginPromptOpen, setLoginPromptOpen] = useState(false);
  const [connectPromptOpen, setConnectPromptOpen] = useState(false);
  const [brokerDialogOpen, setBrokerDialogOpen] = useState(false);
  const [sessionExpired, setSessionExpired] = useState(false);
  const [reconnectAttempted, setReconnectAttempted] = useState(false);
  const [cachedHoldings, setCachedHoldings] = useState<any[]>([]);
  const [cachedPositions, setCachedPositions] = useState<any[]>([]);
  const [cachedFunds, setCachedFunds] = useState<FundsResponse["funds"] | null>(null);
  const [cachedEquityCurve, setCachedEquityCurve] = useState<EquityCurveResponse | null>(null);
  const {
    data: brokerStatus,
    isFetching: brokerStatusLoading,
    refetch: refetchBrokerStatus,
  } = useQuery<BrokerStatusResponse | null>({
    queryKey: ["/broker/status"],
    queryFn: getQueryFn<BrokerStatusResponse>({ on401: "returnNull" }),
    staleTime: 0,
    refetchOnMount: "always",
  });
  const { data: sessionUser, refetch: refetchSessionUser } = useQuery<SessionUser | null>({
    queryKey: ["/me"],
    queryFn: getQueryFn<SessionUser | null>({ on401: "returnNull" }),
    staleTime: 0,
    refetchOnMount: "always",
  });

  async function startSavedZerodhaReconnect() {
    try {
      const redirectUrl = buildReconnectRedirectUrl();
      const params = new URLSearchParams({ redirectUrl });
      const res = await apiRequest("GET", `/broker/login-url?${params.toString()}`);
      const data = (await res.json()) as { loginUrl?: string };
      if (!data?.loginUrl) {
        throw new Error("Reconnect link unavailable.");
      }
      window.open(data.loginUrl, "_blank", "noopener,noreferrer");
      toast({
        title: "Continue in Zerodha",
        description: "Log in and return here. We will reconnect your broker automatically.",
      });
    } catch (error: any) {
      const message = String(error?.message || "");
      if (message.includes("400:") && message.includes("Broker credentials not configured")) {
        setBrokerDialogOpen(true);
        toast({
          title: "Enter Zerodha API credentials",
          description: "Saved broker credentials are missing. Enter the API key and secret once to reconnect.",
        });
        return;
      }
      if (message.includes("401:")) {
        setLoginPromptOpen(true);
        return;
      }
      throw error;
    }
  }

  async function startSavedGrowwReconnect() {
    try {
      const res = await apiRequest("POST", "/broker/groww/reconnect");
      await res.json();
      await Promise.allSettled([
        refetchBrokerStatus(),
        refreshBrokerData({ includeEquityCurve: true }),
      ]);
      toast({
        title: "Groww reconnected",
        description: "Your Groww broker session has been refreshed.",
      });
    } catch (error: any) {
      const message = String(error?.message || "");
      if (message.includes("400:") && message.includes("Broker credentials not configured")) {
        setBrokerDialogOpen(true);
        toast({
          title: "Enter Groww API credentials",
          description: "Saved Groww credentials are missing. Enter the API key and secret once to reconnect.",
        });
        return;
      }
      if (message.includes("401:")) {
        setLoginPromptOpen(true);
        return;
      }
      throw error;
    }
  }

  const disconnectBrokerMutation = useMutation({
    mutationFn: async () => {
      const res = await apiRequest("POST", "/broker/disconnect");
      return res.json();
    },
    onSuccess: async () => {
      setSessionExpired(false);
      setReconnectAttempted(false);
      setCachedHoldings([]);
      setCachedPositions([]);
      setCachedFunds(null);
      setCachedEquityCurve(null);
      queryClient.removeQueries({ queryKey: ["/broker/holdings"] });
      queryClient.removeQueries({ queryKey: ["/broker/positions"] });
      queryClient.removeQueries({ queryKey: ["/broker/funds"] });
      queryClient.removeQueries({ queryKey: ["/broker/equity-curve"] });
      await refetchBrokerStatus();
      toast({
        title: "Broker disconnected",
        description: "Your broker account has been disconnected.",
      });
    },
    onError: (err: any) =>
      toast({
        title: "Disconnect failed",
        description: err?.message || "Unable to disconnect broker.",
      }),
  });

  const holdingsQuery = useQuery<HoldingsResponse>({
    queryKey: ["/broker/holdings"],
    queryFn: async () => {
      const res = await apiRequest("GET", "/broker/holdings");
      return res.json();
    },
    enabled: !!brokerStatus?.connected,
    retry: 1,
    retryDelay: 600,
  });

  const fundsQuery = useQuery<FundsResponse>({
    queryKey: ["/broker/funds"],
    queryFn: async () => {
      const res = await apiRequest("GET", "/broker/funds");
      return res.json();
    },
    enabled: !!brokerStatus?.connected,
    retry: 1,
    retryDelay: 600,
  });

  const [startDate, setStartDate] = useState(() =>
    formatDateInput(new Date(Date.now() - 90 * 24 * 60 * 60 * 1000)),
  );
  const [sipAmount, setSipAmount] = useState(5000);
  const [frequencyValue, setFrequencyValue] = useState(30);
  const [frequencyUnit, setFrequencyUnit] = useState<"days" | "minutes">("days");
  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 [freshStartRequested, setFreshStartRequested] = useState(false);
  const [engineStatus, setEngineStatus] = useState<EngineStatus | null>(null);
  const [marketStatus, setMarketStatus] = useState<MarketStatusResponse | null>(null);

  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 (error) {
      setStrategyDetails(null);
      setStrategyStatus("STOPPED");
    }
  }, [freshStartRequested]);

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

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

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

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

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

  useEffect(() => {
    if (prefersReducedMotion) {
      setIsVisible(true);
      return;
    }

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true);
        }
      },
      { threshold: 0.2 },
    );

    if (sectionRef.current) {
      observer.observe(sectionRef.current);
    }

    return () => observer.disconnect();
  }, [prefersReducedMotion]);

  useEffect(() => {
    if (prefersReducedMotion) {
      setScrollY(0);
      return;
    }

    let rafId: number | null = null;
    const handleScroll = () => {
      if (rafId !== null) return;
      rafId = window.requestAnimationFrame(() => {
        setScrollY(window.scrollY);
        rafId = null;
      });
    };

    window.addEventListener("scroll", handleScroll, { passive: true });
    handleScroll();

    return () => {
      window.removeEventListener("scroll", handleScroll);
      if (rafId !== null) {
        window.cancelAnimationFrame(rafId);
      }
    };
  }, [prefersReducedMotion]);

  const equityCurveQuery = useQuery<EquityCurveResponse>({
    queryKey: ["/broker/equity-curve", startDate],
    queryFn: async () => {
      const res = await apiRequest(
        "GET",
        `/broker/equity-curve${startDate ? `?from=${startDate}` : ""}`,
      );
      return res.json();
    },
    enabled: !!brokerStatus?.connected,
    retry: 1,
    retryDelay: 600,
  });

  const positionsQuery = useQuery<PositionsResponse>({
    queryKey: ["/broker/positions"],
    queryFn: async () => {
      const res = await apiRequest("GET", "/broker/positions");
      return res.json();
    },
    enabled: !!brokerStatus?.connected,
    retry: 1,
    retryDelay: 600,
  });

  const refreshBrokerData = useCallback(
    async ({ includeEquityCurve = false }: { includeEquityCurve?: boolean } = {}) => {
      if (!brokerStatus?.connected) {
        return;
      }
      const tasks: Promise<unknown>[] = [
        holdingsQuery.refetch(),
        positionsQuery.refetch(),
        fundsQuery.refetch(),
        refetchBrokerStatus(),
      ];
      if (includeEquityCurve) {
        tasks.push(equityCurveQuery.refetch());
      }
      await Promise.allSettled(tasks);
    },
    [
      brokerStatus?.connected,
      holdingsQuery.refetch,
      positionsQuery.refetch,
      fundsQuery.refetch,
      equityCurveQuery.refetch,
      refetchBrokerStatus,
    ],
  );

  const isConnected = !!brokerStatus?.connected;
  const isAuthed = brokerStatus !== null;
  const holdings = holdingsQuery.data?.holdings ?? cachedHoldings;
  const positions = positionsQuery.data?.positions ?? cachedPositions;
  const fundsSnapshot = fundsQuery.data?.funds ?? cachedFunds;
  const noHoldings = holdings.length === 0;
  const noPositions = positions.length === 0;

  useEffect(() => {
    if (holdingsQuery.data) {
      setCachedHoldings(holdingsQuery.data.holdings ?? []);
      setSessionExpired(false);
      setReconnectAttempted(false);
    }
  }, [holdingsQuery.data]);

  useEffect(() => {
    if (fundsQuery.data) {
      setCachedFunds(fundsQuery.data.funds ?? null);
      setSessionExpired(false);
      setReconnectAttempted(false);
    }
  }, [fundsQuery.data]);

  useEffect(() => {
    if (equityCurveQuery.data) {
      setCachedEquityCurve(equityCurveQuery.data);
      setSessionExpired(false);
      setReconnectAttempted(false);
    }
  }, [equityCurveQuery.data]);

  useEffect(() => {
    if (positionsQuery.data) {
      setCachedPositions(positionsQuery.data.positions ?? []);
      setSessionExpired(false);
      setReconnectAttempted(false);
    }
  }, [positionsQuery.data]);

  useEffect(() => {
    if (!brokerStatus?.connected) {
      return;
    }

    const authIssue =
      isBrokerAuthError(holdingsQuery.error) ||
      isBrokerAuthError(fundsQuery.error) ||
      isBrokerAuthError(positionsQuery.error) ||
      isBrokerAuthError(equityCurveQuery.error);

    if (authIssue) {
      setSessionExpired(true);
    }
  }, [
    brokerStatus?.connected,
    holdingsQuery.error,
    fundsQuery.error,
    positionsQuery.error,
    equityCurveQuery.error,
  ]);

  useEffect(() => {
    const authState = (brokerStatus?.authState || "").trim().toUpperCase();
    if (!isConnected || !authState || authState === "VALID") {
      setSessionExpired(false);
      setReconnectAttempted(false);
    }
  }, [isConnected, brokerStatus?.authState]);
  useEffect(() => {
    if (!isConnected) {
      setSessionExpired(false);
      setReconnectAttempted(false);
    }
  }, [isConnected]);

  useEffect(() => {
    if (!sessionExpired || reconnectAttempted || !isConnected) {
      return;
    }
    setReconnectAttempted(true);
    (async () => {
      try {
        await refreshBrokerData({ includeEquityCurve: true });
      } catch {
        return;
      }
    })();
  }, [
    sessionExpired,
    reconnectAttempted,
    isConnected,
    refreshBrokerData,
  ]);

  useEffect(() => {
    if (!isConnected) {
      return;
    }

    const refreshIfVisible = () => {
      if (document.visibilityState !== "visible") {
        return;
      }
      void refreshBrokerData();
    };

    const handleVisibilityChange = () => {
      if (document.visibilityState === "visible") {
        void refreshBrokerData();
      }
    };

    const intervalId = window.setInterval(refreshIfVisible, BROKER_DATA_REFRESH_MS);
    document.addEventListener("visibilitychange", handleVisibilityChange);

    return () => {
      window.clearInterval(intervalId);
      document.removeEventListener("visibilitychange", handleVisibilityChange);
    };
  }, [isConnected, refreshBrokerData]);
  const availableFunds = getAvailableFundsValue(fundsSnapshot);

  const { totalValue, totalPnl } = useMemo(() => {
    return [...holdings, ...positions].reduce(
      (acc, item) => {
        return {
          totalValue: acc.totalValue + getHoldingValue(item),
          totalPnl: acc.totalPnl + getDisplayPnl(item),
        };
      },
      { totalValue: 0, totalPnl: 0 },
    );
  }, [holdings, positions]);

  const activeHoldingCount = useMemo(
    () => holdings.filter((item) => getEffectiveQuantity(item) > 0).length,
    [holdings],
  );
  const activePositionCount = useMemo(
    () => positions.filter((item) => getNetQuantity(item) !== 0).length,
    [positions],
  );

  const equityCurve = equityCurveQuery.data ?? cachedEquityCurve;
  const equityCurvePoints = equityCurve?.points ?? [];
  const showSessionExpired = sessionExpired && isConnected;
  const brokerAuthExpired = (brokerStatus?.authState || "").toUpperCase() === "EXPIRED";
  const showReconnectBroker = isConnected && (showSessionExpired || brokerAuthExpired);
  const connectedBroker = (brokerStatus?.broker || "").trim().toUpperCase();
  const brokerLabel = formatBrokerName(connectedBroker);

  const normalizedStrategyStatus =
    strategyStatus === "RUNNING"
      ? "RUNNING"
      : strategyStatus === "WAITING"
        ? "WAITING"
        : "STOPPED";
  const savedStrategyAmount = Number(strategyDetails?.config?.sip_amount);
  const savedStrategyFrequencyValue = Number(strategyDetails?.config?.sip_frequency?.value);
  const savedStrategyFrequencyUnit =
    strategyDetails?.config?.sip_frequency?.unit === "minutes"
      ? "minutes"
      : strategyDetails?.config?.sip_frequency?.unit === "days"
        ? "days"
        : null;
  const savedStrategyCadence = formatFrequencyLabel(
    savedStrategyFrequencyValue,
    savedStrategyFrequencyUnit,
  );
  const savedStrategyAmountLabel =
    Number.isFinite(savedStrategyAmount) && savedStrategyAmount > 0
      ? formatCurrency(savedStrategyAmount)
      : null;
  const savedStrategyMode =
    strategyDetails?.config?.mode === "LIVE"
      ? "Live"
      : strategyDetails?.config?.mode === "PAPER"
        ? "Paper"
        : null;
  const savedStrategyBroker =
    strategyDetails?.config?.broker ? formatBrokerName(strategyDetails.config.broker) : null;
  const savedStrategySummary = [
    savedStrategyAmountLabel ? `${savedStrategyAmountLabel} SIP` : null,
    savedStrategyCadence ? `every ${savedStrategyCadence}` : null,
    savedStrategyMode,
    savedStrategyBroker,
  ]
    .filter(Boolean)
    .join(" · ");
  const isStrategyActive =
    normalizedStrategyStatus === "RUNNING" ||
    normalizedStrategyStatus === "WAITING";
  const canResumeSavedStrategy = !!strategyDetails?.can_resume;
  const freshStartPreferenceKey = getFreshStartPreferenceKey(
    sessionUser?.id,
    strategyDetails?.run_id,
  );
  const showResumeStrategy =
    !isStrategyActive && canResumeSavedStrategy && !freshStartRequested;
  const showRestartStrategy =
    !isStrategyActive && !!strategyDetails?.can_restart && !freshStartRequested;
  const showFreshStartStrategy =
    !isStrategyActive && (!canResumeSavedStrategy || freshStartRequested);
  const canEditStrategyConfig = showFreshStartStrategy;

  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 requestFreshStart = useCallback(() => {
    setFreshStartRequested(true);
    writeFreshStartPreference(freshStartPreferenceKey, true);
  }, [freshStartPreferenceKey]);

  const clearFreshStartPreference = useCallback(() => {
    setFreshStartRequested(false);
    writeFreshStartPreference(freshStartPreferenceKey, false);
  }, [freshStartPreferenceKey]);

  useEffect(() => {
    if (!freshStartPreferenceKey) {
      return;
    }
    if (isStrategyActive || !strategyDetails?.can_restart) {
      writeFreshStartPreference(freshStartPreferenceKey, false);
      setFreshStartRequested(false);
      return;
    }
    if (readFreshStartPreference(freshStartPreferenceKey)) {
      setFreshStartRequested(true);
    }
  }, [freshStartPreferenceKey, isStrategyActive, strategyDetails?.can_restart]);

  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 requireLogin = useCallback(async () => {
    const latest = await refetchSessionUser();
    if (!latest.data) {
      setLoginPromptOpen(true);
      return false;
    }
    return true;
  }, [refetchSessionUser]);

  const reconnectCurrentBroker = async () => {
    if (connectedBroker === "GROWW") {
      return startSavedGrowwReconnect();
    }
    if (connectedBroker === "ZERODHA") {
      return startSavedZerodhaReconnect();
    }
    setBrokerDialogOpen(true);
  };

  const handleReconnectClick = useCallback(() => {
    requireLogin()
      .then((isLoggedIn) => {
        if (!isLoggedIn) {
          return;
        }
        if (brokerStatus?.connected) {
          return reconnectCurrentBroker().catch((error: any) =>
            toast({
              title: "Reconnect failed",
              description: error?.message || `Unable to reconnect ${brokerLabel}.`,
            }),
          );
        }
        setBrokerDialogOpen(true);
      })
      .catch(() => {
        setLoginPromptOpen(true);
      });
  }, [brokerLabel, brokerStatus, reconnectCurrentBroker, requireLogin]);

  const handleRefreshBrokerData = useCallback(() => {
    void refreshBrokerData({ includeEquityCurve: true });
  }, [refreshBrokerData]);

  const handleDisconnectBroker = useCallback(() => {
    disconnectBrokerMutation.mutate();
  }, [disconnectBrokerMutation]);

  const handleStart = async () => {
    if (!(await requireLogin())) {
      return;
    }
    if (!isConnected) {
      setConnectPromptOpen(true);
      return;
    }
    if (showSessionExpired || brokerAuthExpired) {
      toast({
        title: "Reconnect broker",
        description: `Your ${brokerLabel} session has expired. Reconnect before starting the live strategy.`,
      });
      handleReconnectClick();
      return;
    }
    setIsStarting(true);
    try {
      const result = await startStrategy({
        strategy_name: "Golden Nifty",
        sip_amount: sipAmount,
        sip_frequency: {
          value: frequencyValue,
          unit: frequencyUnit,
        },
        mode: "LIVE",
      });
      if (result?.status === "broker_auth_required") {
        toast({
          title: "Reconnect broker",
          description: `Your ${brokerLabel} session has expired. Reconnect and try again.`,
        });
        await reconnectCurrentBroker();
        return;
      }
      if (result?.status === "already_running") {
        toast({
          title: "Strategy already running",
          description: "The engine is already active.",
        });
      } else if (result?.status === "started" || result?.status === "restarted") {
        clearFreshStartPreference();
        toast({
          title: "Live strategy started",
          description: `Golden Nifty is now armed for live ${brokerLabel} execution.`,
        });
      } else {
        toast({
          title: "Start failed",
          description: result?.message || result?.status || "Unable to start strategy.",
        });
      }
    } catch (error: any) {
      const message = error?.message || "Unable to start strategy.";
      if (String(message).includes("401:")) {
        setLoginPromptOpen(true);
      }
      toast({
        title: "Start failed",
        description: message,
      });
    } finally {
      setIsStarting(false);
      await Promise.allSettled([
        refreshStatus(),
        refreshEngineStatus(),
        refreshMarketStatus(),
        refreshBrokerData({ includeEquityCurve: true }),
      ]);
    }
  };

  const handleResume = async () => {
    if (!(await requireLogin())) {
      return;
    }
    if (!isConnected) {
      setConnectPromptOpen(true);
      return;
    }
    if (showSessionExpired || brokerAuthExpired) {
      toast({
        title: "Reconnect broker",
        description: `Your ${brokerLabel} session has expired. Reconnect before resuming the live strategy.`,
      });
      handleReconnectClick();
      return;
    }
    setIsResuming(true);
    try {
      const result = await resumeStrategy();
      if (result?.status === "broker_auth_required") {
        toast({
          title: "Reconnect broker",
          description: `Your ${brokerLabel} session has expired. Reconnect and resume again.`,
        });
        await reconnectCurrentBroker();
        return;
      }
      if (result?.status === "already_running") {
        toast({
          title: "Strategy already running",
          description: "The engine is already active.",
        });
      } else if (result?.status === "resumed") {
        clearFreshStartPreference();
        toast({
          title: "Live strategy resumed",
          description: "The previous live 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 cycle instead.",
        });
      } else {
        toast({
          title: "Resume failed",
          description: result?.message || result?.status || "Unable to resume strategy.",
        });
      }
    } catch (error: any) {
      const message = error?.message || "Unable to resume strategy.";
      if (String(message).includes("401:")) {
        setLoginPromptOpen(true);
      }
      toast({
        title: "Resume failed",
        description: message,
      });
    } finally {
      setIsResuming(false);
      await Promise.allSettled([
        refreshStatus(),
        refreshEngineStatus(),
        refreshMarketStatus(),
        refreshBrokerData({ includeEquityCurve: true }),
      ]);
    }
  };

  const handleStop = async () => {
    setIsStopping(true);
    try {
      const result = await stopStrategy();
      if (result?.status === "stopped") {
        clearFreshStartPreference();
        if (result?.warning) {
          toast({
            title: "Strategy stopped",
            description: `Stopped with warning: ${result.warning}`,
          });
        }
      } else if (result?.status === "already_stopped") {
        clearFreshStartPreference();
        toast({
          title: "Strategy already stopped",
          description: "The live strategy was already inactive.",
        });
      } else {
        toast({
          title: "Stop failed",
          description: result?.message || result?.status || "Unable to stop strategy.",
        });
      }
    } catch (error: any) {
      toast({
        title: "Stop failed",
        description: error?.message || "Unable to stop strategy.",
      });
    } finally {
      setIsStopping(false);
      await Promise.allSettled([
        refreshStatus(),
        refreshEngineStatus(),
        refreshMarketStatus(),
        refreshBrokerData({ includeEquityCurve: true }),
      ]);
    }
  };

  const summaryCards = [
    {
      icon: <Wallet className="h-5 w-5" />,
      label: "Available funds",
      value: formatCurrency(isConnected ? availableFunds : 0, { decimals: 2 }),
      muted: !isConnected,
      subText:
        isConnected && fundsQuery.data?.funds?.utilized !== undefined
          ? `Utilized: ${formatCurrency(fundsQuery.data?.funds?.utilized || 0, { decimals: 2 })}`
          : undefined,
    },
    {
      icon: <Wallet className="h-5 w-5" />,
      label: "Portfolio value",
      value: formatCurrency(totalValue, { decimals: 2 }),
      muted: !isConnected,
      subText:
        isConnected && (activeHoldingCount > 0 || activePositionCount > 0)
          ? `Holdings: ${activeHoldingCount} | Positions: ${activePositionCount}`
          : undefined,
    },
    {
      icon: <BarChart3 className="h-5 w-5" />,
      label: "Positions",
      value: activePositionCount.toString(),
      muted: !isConnected,
    },
    {
      icon: <AlertCircle className="h-5 w-5" />,
      label: "Unrealized P&L",
      value: formatCurrency(totalPnl, { decimals: 2 }),
      muted: !isConnected,
    },
  ];

  const revealTransition = prefersReducedMotion ? "" : "transition-all duration-700";
  const sectionRevealClass = prefersReducedMotion
    ? "opacity-100"
    : isVisible
      ? "opacity-100 translate-y-0"
      : "opacity-0 translate-y-6";
  const cardRevealClass = prefersReducedMotion
    ? "opacity-100"
    : isVisible
      ? "opacity-100 translate-y-0"
      : "opacity-0 translate-y-4";
  const hoverLift = prefersReducedMotion
    ? ""
    : "transition-all duration-300 hover:-translate-y-1 hover:shadow-2xl hover:shadow-primary/10";
  const parallaxOffset = prefersReducedMotion ? 0 : Math.min(scrollY * 0.3, 220);

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

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

  const summaryAnimate = prefersReducedMotion || isVisible ? "show" : "hidden";
  const ctaMotionProps = prefersReducedMotion
    ? {}
    : {
        whileHover: { scale: 1.02 },
        whileTap: { scale: 0.97 },
        transition: { type: "spring", stiffness: 400, damping: 25 },
      };

  return (
    <section
      ref={sectionRef}
      id="portfolio"
      className={`relative overflow-hidden bg-gradient-to-b from-background to-background/80 px-4 py-20 pb-20 sm:px-6 sm:py-24 sm:pb-24 md:py-32 md:pb-32 ${revealTransition} ${sectionRevealClass}`}
    >
      <LoginRequiredDialog
        open={loginPromptOpen}
        onOpenChange={setLoginPromptOpen}
        context="start the strategy"
      />
      <LoginRequiredDialog
        open={connectPromptOpen}
        onOpenChange={setConnectPromptOpen}
        title="Connect broker"
        message="Connect your broker to start the strategy."
      />
      <div className="absolute inset-0 pointer-events-none">
        <div
          className="absolute -top-24 left-1/4 h-72 w-72 rounded-full bg-primary/10 blur-3xl"
          style={{ transform: `translate3d(0, ${parallaxOffset}px, 0)` }}
        />
        <div
          className="absolute top-6 right-[8%] h-80 w-80 rounded-full bg-chart-2/10 blur-3xl"
          style={{ transform: `translate3d(0, ${parallaxOffset}px, 0)` }}
        />
        <div
          className="absolute top-32 left-8 h-48 w-48 rounded-full bg-chart-3/10 blur-3xl"
          style={{ transform: `translate3d(0, ${parallaxOffset}px, 0)` }}
        />
      </div>

      <div className="relative z-10 max-w-6xl mx-auto space-y-10">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
          <div className="space-y-2">
            <p className="text-sm uppercase tracking-[0.25em] text-muted-foreground">Portfolio</p>
            <h3 className="text-2xl font-bold sm:text-3xl md:text-4xl">Your holdings & live positions</h3>
            <p className="text-muted-foreground max-w-2xl">
              Connect your broker to sync holdings. When disconnected, values stay at zero and you will see a prompt to connect.
            </p>
            {isConnected && (brokerStatus?.userName || brokerStatus?.broker) ? (
              <div className="inline-flex max-w-full flex-wrap items-center gap-2 rounded-full border border-primary/50 bg-primary/10 px-3 py-1 text-sm font-medium text-primary sm:flex-nowrap">
                <Wallet className="h-4 w-4" />
                {brokerStatus?.userName ? (
                  <>
                    Connected as <span className="font-semibold">{brokerStatus.userName}</span>
                  </>
                ) : (
                  <>
                    Connected to <span className="font-semibold">{brokerStatus?.broker}</span>
                  </>
                )}
              </div>
            ) : null}
          </div>
        <div className="flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:flex-wrap">
          <BrokerConnectDialog
            open={brokerDialogOpen}
            onOpenChange={setBrokerDialogOpen}
            triggerClassName="w-full sm:w-auto"
          />
          <Button variant="secondary" asChild className="w-full sm:w-auto">
            <a href="/portfolio/paper" target="_blank" rel="noreferrer">
              Paper Trading Portfolio
            </a>
          </Button>
          {isConnected ? (
              <Button
                variant="outline"
                onClick={handleRefreshBrokerData}
                disabled={holdingsQuery.isFetching || positionsQuery.isFetching || equityCurveQuery.isFetching}
                className="w-full sm:w-auto"
              >
                <RefreshCcw className="h-4 w-4" />
                {holdingsQuery.isFetching || positionsQuery.isFetching || equityCurveQuery.isFetching
                  ? "Refreshing..."
                  : "Refresh data"}
              </Button>
            ) : null}
          {showReconnectBroker ? (
              <Button
                variant="outline"
                onClick={handleReconnectClick}
                className="w-full sm:w-auto"
              >
                <PlugZap className="h-4 w-4" />
                Reconnect broker
              </Button>
            ) : null}
          {isConnected ? (
              <Button
                variant="outline"
                onClick={handleDisconnectBroker}
                disabled={disconnectBrokerMutation.isPending}
                className="w-full sm:w-auto"
              >
                {disconnectBrokerMutation.isPending ? "Disconnecting..." : "Disconnect broker"}
              </Button>
            ) : null}
          </div>
        </div>

        <motion.div
          className="grid gap-4 md:grid-cols-3"
          variants={cardContainer}
          initial="hidden"
          animate={summaryAnimate}
        >
          {summaryCards.map((card) => (
            <motion.div
              key={card.label}
              variants={cardItem}
              whileHover={{
                y: -6,
                boxShadow: "0 20px 40px rgba(0,0,0,0.18)",
              }}
              transition={{ type: "spring", stiffness: 300, damping: 24 }}
            >
              <SummaryCard {...card} prefersReducedMotion={prefersReducedMotion} />
            </motion.div>
          ))}
        </motion.div>

        <div
          className={`rounded-2xl border border-border/60 bg-card/70 shadow-xl overflow-hidden ${hoverLift} ${revealTransition} ${cardRevealClass}`}
          style={prefersReducedMotion ? undefined : { transitionDelay: "500ms" }}
        >
          <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">Holdings</p>
              <p className="text-xs text-muted-foreground">
                Settled holdings synced from your connected broker.
              </p>
            </div>
            <Badge variant={isConnected ? "secondary" : "outline"}>
              {isConnected ? "Broker connected" : "Not connected"}
            </Badge>
          </div>

          {!isAuthed ? (
            <ZeroState message="Log in and connect your broker to see your portfolio." />
          ) : brokerStatusLoading ? (
            <ZeroState message="Checking broker status..." />
          ) : !isConnected ? (
            <ZeroState message="Connect to broker to see your portfolio." />
          ) : holdingsQuery.isLoading ? (
            <ZeroState message="Fetching holdings..." />
          ) : holdingsQuery.isError && holdings.length === 0 ? (
            <ZeroState
              message={
                showSessionExpired
                  ? "Session expired. Reconnect to refresh holdings and funds."
                  : "Could not fetch holdings. Try refreshing."
              }
            />
          ) : noHoldings ? (
            <ZeroState message="No holdings yet. Refresh after connecting." />
          ) : (
            <div className="overflow-x-auto">
              {showSessionExpired ? (
                <div className="border-b border-amber-400/20 bg-amber-500/10 px-4 py-3 text-xs text-amber-200 sm:px-6">
                  Session expired. Showing the last known holdings. Use the top reconnect action to refresh.
                </div>
              ) : null}
              <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&L</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border/60">
                  {renderPortfolioRows(holdings)}
                </tbody>
              </table>
            </div>
          )}
        </div>

        <div
          className={`rounded-2xl border border-border/60 bg-card/70 shadow-xl overflow-hidden ${hoverLift} ${revealTransition} ${cardRevealClass}`}
          style={prefersReducedMotion ? undefined : { transitionDelay: "550ms" }}
        >
          <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">Live positions</p>
              <p className="text-xs text-muted-foreground">
                Same-day broker positions appear here before they move into holdings.
              </p>
            </div>
            <Badge variant={isConnected ? "secondary" : "outline"}>
              {activePositionCount} open
            </Badge>
          </div>

          {!isAuthed ? (
            <ZeroState message="Log in and connect your broker to see live positions." />
          ) : brokerStatusLoading ? (
            <ZeroState message="Checking broker status..." />
          ) : !isConnected ? (
            <ZeroState message="Connect to broker to see live positions." />
          ) : positionsQuery.isLoading ? (
            <ZeroState message="Fetching positions..." />
          ) : positionsQuery.isError && positions.length === 0 ? (
            <ZeroState
              message={
                showSessionExpired
                  ? "Session expired. Reconnect to refresh positions."
                  : "Could not fetch positions. Try refreshing."
              }
            />
          ) : noPositions ? (
            <ZeroState message="No live positions yet. Same-day buys and sells will appear here." />
          ) : (
            <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&L</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border/60">
                  {renderPortfolioRows(positions)}
                </tbody>
              </table>
            </div>
          )}
        </div>


        <div
          className={`rounded-2xl border border-border/60 bg-card/70 shadow-xl overflow-hidden ${hoverLift} ${revealTransition} ${cardRevealClass}`}
          style={prefersReducedMotion ? undefined : { transitionDelay: "600ms" }}
        >
          <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>
            </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="grid gap-4 md:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="strategy-sip">SIP Amount</Label>
                <Input
                  id="strategy-sip"
                  type="number"
                  min={0}
                  step={100}
                  value={sipAmount}
                  disabled={!canEditStrategyConfig}
                  onChange={(event) => {
                    const value = Number(event.target.value);
                    setSipAmount(Number.isNaN(value) ? 0 : value);
                  }}
                />
              </div>
              <div className="grid gap-4 md:grid-cols-[minmax(0,1fr)_220px]">
                <div className="space-y-2">
                  <Label htmlFor="strategy-frequency">Frequency</Label>
                  <Input
                    id="strategy-frequency"
                    type="number"
                    min={1}
                    step={1}
                    value={frequencyValue}
                    disabled={!canEditStrategyConfig}
                    onChange={(event) => {
                      const value = Number(event.target.value);
                      setFrequencyValue(Number.isNaN(value) ? 1 : value);
                    }}
                  />
                </div>
                <div className="space-y-2">
                  <Label>Unit</Label>
                  <Select
                    value={frequencyUnit}
                    disabled={!canEditStrategyConfig}
                    onValueChange={(value) => setFrequencyUnit(value as "days" | "minutes")}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select unit" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="days">Days</SelectItem>
                      <SelectItem value="minutes">Minutes (testing)</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>
            {frequencyUnit === "minutes" ? (
              <div className="text-xs text-amber-300">
                Minutes mode is for live testing only. The engine checks every few seconds in this mode.
              </div>
            ) : null}
            {savedStrategySummary ? (
              <div className="rounded-lg border border-border/60 bg-background/40 px-3 py-2 text-xs text-muted-foreground">
                {isStrategyActive ? "Current run" : showResumeStrategy ? "Resume will continue" : "Saved strategy config"}
                : <span className="font-medium text-foreground"> {savedStrategySummary}</span>
              </div>
            ) : null}
            {showResumeStrategy ? (
              <div className="text-xs text-muted-foreground">
                Resume uses the previously saved 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={isStarting || !canArmStrategy || isStrategyActive}
                  className="w-full shimmer sm:w-auto"
                >
                  {isStarting ? "Starting..." : "Start Strategy"}
                </MotionButton>
              ) : null}
              {showRestartStrategy ? (
                <Button variant="outline" onClick={requestFreshStart} className="w-full sm:w-auto">
                  Restart Strategy
                </Button>
              ) : null}
              {isStrategyActive ? (
                <Button variant="outline" onClick={handleStop} disabled={isStopping} className="w-full sm:w-auto">
                  {isStopping ? "Stopping..." : "Stop Strategy"}
                </Button>
              ) : null}
            </div>
            <StrategyTimeline compact />
          </div>
        </div>

        {isConnected && (
          <div
            className={`${revealTransition} ${cardRevealClass}`}
            style={prefersReducedMotion ? undefined : { transitionDelay: "650ms" }}
          >
            <AutoLoginSetup />
          </div>
        )}

        <div
          className={`rounded-2xl border border-border/60 bg-card/70 shadow-xl p-6 space-y-4 ${hoverLift} ${revealTransition} ${cardRevealClass}`}
          style={prefersReducedMotion ? undefined : { transitionDelay: "700ms" }}
        >
          <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
            <div>
              <p className="text-sm font-semibold">Equity curve</p>
              <p className="text-xs text-muted-foreground">
                Track exact stored daily broker snapshots from the day recording began.
              </p>
            </div>
            <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
              <Label htmlFor="equity-start" className="text-xs text-muted-foreground">
                From
              </Label>
              <Input
                id="equity-start"
                type="date"
                value={startDate}
                max={formatDateInput(new Date())}
                onChange={(e) => setStartDate(e.target.value)}
                className="w-full sm:w-[180px]"
                disabled={!isConnected}
              />
            </div>
          </div>

          {!isConnected ? (
            <ZeroState message="Connect to broker to see your equity curve." />
          ) : equityCurveQuery.isLoading && equityCurvePoints.length === 0 ? (
            <ZeroState message="Loading equity curve..." />
          ) : equityCurveQuery.isError && equityCurvePoints.length === 0 ? (
            <ZeroState message="Could not load equity curve." />
          ) : equityCurvePoints.length === 0 ? (
            <ZeroState message="No exact equity snapshots yet. The curve starts from the first recorded daily snapshot." />
          ) : (
            <div className="h-72 sm:h-80">
              <ChartContainer
                config={{
                  equity: { label: "Equity", color: "hsl(var(--chart-1))" },
                }}
                className="rounded-xl bg-background/60"
              >
                <AreaChart data={equityCurvePoints}>
                  <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) =>
                      new Intl.NumberFormat("en-IN", { maximumFractionDigits: 0, notation: "compact" }).format(v as number)
                    }
                    width={80}
                  />
                  <ChartTooltip
                    content={
                      <ChartTooltipContent
                        labelFormatter={(value) =>
                          new Date(value as string).toLocaleDateString("en-IN", {
                            year: "numeric",
                            month: "short",
                            day: "numeric",
                          })
                        }
                        formatter={(val) => formatCurrency(Number(val))}
                      />
                    }
                  />
                  <Area
                    type="monotone"
                    dataKey="value"
                    stroke="var(--color-equity)"
                    fill="var(--color-equity)"
                    fillOpacity={0.15}
                    strokeWidth={2}
                  />
                </AreaChart>
              </ChartContainer>
              <p className="text-xs text-muted-foreground mt-2">
                Exact daily values from{" "}
                {equityCurve?.exactFrom
                  ? new Date(equityCurve.exactFrom).toLocaleDateString("en-IN", {
                      year: "numeric",
                      month: "short",
                      day: "numeric",
                    })
                  : "the first recorded snapshot"}
                .
              </p>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

function SummaryCard({
  icon,
  label,
  value,
  muted,
  subText,
  prefersReducedMotion,
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
  muted?: boolean;
  subText?: string;
  prefersReducedMotion: boolean;
}) {
  const cardRef = useRef<HTMLDivElement | null>(null);
  const [transform, setTransform] = useState({ rotateX: 0, rotateY: 0, scale: 1 });
  const hoverClass = prefersReducedMotion
    ? ""
    : "transition-all duration-300";

  const handleMouseMove = (event: React.MouseEvent<HTMLDivElement>) => {
    if (prefersReducedMotion || !cardRef.current) return;
    const rect = cardRef.current.getBoundingClientRect();
    const x = (event.clientX - rect.left) / rect.width - 0.5;
    const y = (event.clientY - rect.top) / rect.height - 0.5;
    setTransform({
      rotateX: y * -8,
      rotateY: x * 8,
      scale: 1.02,
    });
  };

  const handleMouseLeave = () => {
    if (prefersReducedMotion) return;
    setTransform({ rotateX: 0, rotateY: 0, scale: 1 });
  };

  const tiltStyle = prefersReducedMotion
    ? undefined
    : {
        transform: `perspective(900px) rotateX(${transform.rotateX}deg) rotateY(${transform.rotateY}deg) scale(${transform.scale})`,
        transition: "transform 0.12s ease-out",
      };

  return (
    <div
      ref={cardRef}
      className={`rounded-xl border border-border/70 bg-card/80 p-4 shadow-sm ${hoverClass}`}
      style={prefersReducedMotion ? undefined : { perspective: "900px" }}
      onMouseMove={handleMouseMove}
      onMouseLeave={handleMouseLeave}
    >
      <div className="will-change-transform" style={tiltStyle}>
        <div className="flex items-center gap-3">
          <div className="rounded-full bg-primary/10 p-2 text-primary">{icon}</div>
          <div>
            <p className="text-xs uppercase tracking-[0.18em] text-muted-foreground">{label}</p>
            <p className={`text-xl font-semibold ${muted ? "text-muted-foreground" : "text-foreground"}`}>
              <motion.span
                key={value}
                initial={{ opacity: 0.6, y: 3 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.25, ease: "easeOut" }}
              >
                {value}
              </motion.span>
            </p>
            {subText ? <p className="text-xs text-muted-foreground">{subText}</p> : null}
          </div>
        </div>
      </div>
    </div>
  );
}

function ZeroState({ message }: { message: string }) {
  return (
    <div className="flex flex-col items-center justify-center gap-3 px-6 py-12 text-center">
      <div className="rounded-full bg-muted/70 p-3 text-muted-foreground">
        <Wallet className="h-6 w-6" />
      </div>
      <p className="text-sm font-medium">{message}</p>
      <p className="text-xs text-muted-foreground max-w-md">
        Once connected, we will pull your latest holdings and live positions securely from your broker.
      </p>
    </div>
  );
}
