import { useEffect, useState } from 'react';
import { getScreenerSettings, saveScreenerSettings } from '../../../../api';

export function useScreenerSettings() {
  const [remote, setRemote] = useState(null);
  const [local, setLocal] = useState(null);

  useEffect(() => {
    getScreenerSettings().then((s) => { setRemote(s); setLocal(s); });
  }, []);

  const dirty = remote && local && JSON.stringify(remote) !== JSON.stringify(local);

  async function save() {
    if (!local) return;
    const saved = await saveScreenerSettings({
      weights: local.weights, node_params: local.node_params, gate_params: local.gate_params,
      top_n: local.top_n, rr_ratio: local.rr_ratio,
      atr_window: local.atr_window, atr_stop_mult: local.atr_stop_mult,
    });
    setRemote(saved);
    setLocal(saved);
  }

  return { settings: local, dirty, setLocal, save };
}
