import { useEffect, useState } from "react";

/**
 * Auto-exit rules used when Trade Execution Mode = "auto".
 *
 * - reverseExit: close an open position if a pending signal appears on the
 *   same coin with the opposite side and confidence >= reverseMinConfidence.
 * - trailingSl: as the position moves in favour, ratchet the stop loss so it
 *   sits `trailingDistancePct` (percent of entry price) behind the best mark
 *   seen so far. SL only moves in the profitable direction, never against.
 */
export interface AutoExitSettings {
  reverseExit: boolean;
  reverseMinConfidence: number; // 0..1
  trailingSl: boolean;
  trailingDistancePct: number; // e.g. 1.5 means 1.5%
  trailingActivatePct: number; // arm trailing only after this much profit % from entry
}

const KEY = "delta.auto_exit_settings";

export const DEFAULT_AUTO_EXIT: AutoExitSettings = {
  reverseExit: true,
  reverseMinConfidence: 0.65,
  trailingSl: true,
  trailingDistancePct: 1.5,
  trailingActivatePct: 0.6,
};

export function getAutoExit(): AutoExitSettings {
  if (typeof window === "undefined") return DEFAULT_AUTO_EXIT;
  try {
    const raw = localStorage.getItem(KEY);
    if (!raw) return DEFAULT_AUTO_EXIT;
    return { ...DEFAULT_AUTO_EXIT, ...JSON.parse(raw) };
  } catch {
    return DEFAULT_AUTO_EXIT;
  }
}

export function setAutoExit(s: AutoExitSettings) {
  localStorage.setItem(KEY, JSON.stringify(s));
  window.dispatchEvent(new CustomEvent("delta:auto-exit", { detail: s }));
}

export function useAutoExit(): [AutoExitSettings, (patch: Partial<AutoExitSettings>) => void] {
  const [state, setState] = useState<AutoExitSettings>(DEFAULT_AUTO_EXIT);
  useEffect(() => {
    setState(getAutoExit());
    const onChange = (e: Event) => setState((e as CustomEvent<AutoExitSettings>).detail);
    const onStorage = (e: StorageEvent) => {
      if (e.key === KEY) setState(getAutoExit());
    };
    window.addEventListener("delta:auto-exit", onChange);
    window.addEventListener("storage", onStorage);
    return () => {
      window.removeEventListener("delta:auto-exit", onChange);
      window.removeEventListener("storage", onStorage);
    };
  }, []);
  return [
    state,
    (patch) => {
      const next = { ...state, ...patch };
      setAutoExit(next);
      setState(next);
    },
  ];
}
