"use client";

import { useEffect, useRef, useState } from "react";
import type { LiveMetrics, PaperMetrics } from "./types";

const API_BASE = "/cv/api";

export function useLiveMetrics() {
  const [data, setData] = useState<LiveMetrics | null>(null);
  const [connected, setConnected] = useState(false);
  const wsRef = useRef<WebSocket | null>(null);
  const timerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);

  useEffect(() => {
    const WS_BASE = `${window.location.protocol === "https:" ? "wss:" : "ws:"}//${window.location.host}/cv/ws`;

    function connect() {
      try {
        const ws = new WebSocket(WS_BASE);
        wsRef.current = ws;
        ws.onopen = () => setConnected(true);
        ws.onclose = () => {
          setConnected(false);
          timerRef.current = setTimeout(connect, 5000);
        };
        ws.onmessage = (e) => {
          try {
            const d = JSON.parse(e.data) as LiveMetrics;
            setData(d);
          } catch { /* ignore */ }
        };
      } catch {
        timerRef.current = setTimeout(connect, 5000);
      }
    }

    connect();
    return () => {
      wsRef.current?.close();
      clearTimeout(timerRef.current);
    };
  }, []);

  return { data, connected };
}

export function usePaperMetrics() {
  const [data, setData] = useState<PaperMetrics | null>(null);
  const [connected, setConnected] = useState(false);
  const wsRef = useRef<WebSocket | null>(null);

  useEffect(() => {
    const base = `${window.location.protocol === "https:" ? "wss:" : "ws:"}//${window.location.host}/cv/ws/paper`;
    const connect = () => {
      try {
        const ws = new WebSocket(base);
        wsRef.current = ws;
        ws.onopen = () => setConnected(true);
        ws.onclose = () => {
          setConnected(false);
          setTimeout(connect, 5000);
        };
        ws.onmessage = (e) => {
          try {
            const d = JSON.parse(e.data) as PaperMetrics;
            setData(d);
          } catch { /* ignore */ }
        };
      } catch {
        setTimeout(connect, 5000);
      }
    };
    connect();
    return () => wsRef.current?.close();
  }, []);

  return { data, connected };
}

export async function fetchHistorical(): Promise<Record<string, import("./types").BacktestSummary>> {
  const res = await fetch(`${API_BASE}/backtests/historical`);
  const list: import("./types").BacktestSummary[] = await res.json();
  const byStrat: Record<string, import("./types").BacktestSummary> = {};
  for (const b of list) {
    const key = `${b.strategy} · ${b.coin ?? "?"}`;
    if (!byStrat[key]) byStrat[key] = b;
  }
  return byStrat;
}

export async function fetchBacktestDetail(name: string): Promise<import("./types").BacktestFull> {
  const res = await fetch(`${API_BASE}/backtest/historical/${encodeURIComponent(name)}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

export async function recalcBacktest(
  name: string,
  feeTier: number,
  stakingTier: string,
): Promise<import("./types").BacktestFull> {
  const res = await fetch(
    `${API_BASE}/backtest/${encodeURIComponent(name)}/recalc?fee_tier=${feeTier}&staking_tier=${stakingTier}`,
  );
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}
