import { useCallback, useEffect, useState } from 'react';

export interface RiskSettings {
  accountSize: number;
  riskPct: number;
}

const STORAGE_KEY = 'risk-settings';
const DEFAULTS: RiskSettings = { accountSize: 10000, riskPct: 1 };

/** Account size + per-trade risk %, persisted in localStorage (per browser). */
export function useRiskSettings() {
  const [settings, setSettings] = useState<RiskSettings>(() => {
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      if (raw) return { ...DEFAULTS, ...JSON.parse(raw) };
    } catch {
      /* ignore malformed storage */
    }
    return DEFAULTS;
  });

  useEffect(() => {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
    } catch {
      /* ignore quota/availability errors */
    }
  }, [settings]);

  const update = useCallback(
    (patch: Partial<RiskSettings>) => setSettings((s) => ({ ...s, ...patch })),
    [],
  );

  return { settings, update };
}
