import { useState, useEffect, useCallback } from 'react';
import { kv } from '../lib/kv';

export function useCustomOptions(key: string, defaults: string[]) {
  const [custom, setCustom] = useState<string[]>([]);

  useEffect(() => {
    kv.getItem(key).then((json) => {
      if (json) {
        try { setCustom(JSON.parse(json)); } catch {}
      }
    });
  }, [key]);

  const addOption = useCallback(async (value: string) => {
    const trimmed = value.trim();
    if (!trimmed || defaults.includes(trimmed)) return;
    setCustom((prev) => {
      if (prev.includes(trimmed)) return prev;
      const next = [...prev, trimmed];
      kv.setItem(key, JSON.stringify(next));
      return next;
    });
  }, [key, defaults]);

  const removeOption = useCallback((value: string) => {
    setCustom((prev) => {
      const next = prev.filter((o) => o !== value);
      kv.setItem(key, JSON.stringify(next));
      return next;
    });
  }, [key]);

  return {
    options: [...defaults, ...custom],
    customOptions: custom,
    addOption,
    removeOption,
  };
}
