import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';

const STORAGE_KEY = 'cbm-settings-v1';

const DEFAULT_SETTINGS = {
  showServerNames: true,
  showMemberTimezones: false,
  // Synced files stay read-only until checked out; opting in leaves the whole
  // workspace writable (edits without a lock still show as "Modified").
  allowUncheckedEdits: false,
  // Silences the conflict/rollback/stale-submit/deleted-on-server popups.
  // Purely a notification switch — the server-side protections these popups
  // describe (blocked stale submits, checkout conflicts) still apply either
  // way; this only stops the client from telling you about them.
  warningsEnabled: true,
  showTimeTracking: false,
  // Tab appearance. Off = the default "browser tab" look (borderless, pipe
  // separators, a single grey pill on the selected tab). On = the old "bold"
  // look (every tab a grey pill, the selected one going full colour).
  boldTabStyling: false,
  // Shimmers "List Changes" in the Repository panel header every 12s while
  // the changelist has anything in it — a nudge that there is work waiting to
  // be submitted. Purely decorative; the button works either way.
  listChangesHint: true,
};

function loadSettings() {
  try {
    const saved = localStorage.getItem(STORAGE_KEY);
    if (saved) return { ...DEFAULT_SETTINGS, ...JSON.parse(saved) };
  } catch {
    /* use defaults */
  }
  return DEFAULT_SETTINGS;
}

const SettingsContext = createContext(null);

export function SettingsProvider({ children }) {
  const [settings, setSettings] = useState(loadSettings);

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

  const setShowServerNames = useCallback((showServerNames) => {
    setSettings((prev) => ({ ...prev, showServerNames }));
  }, []);

  const setShowMemberTimezones = useCallback((showMemberTimezones) => {
    setSettings((prev) => ({ ...prev, showMemberTimezones }));
  }, []);

  const setAllowUncheckedEdits = useCallback((allowUncheckedEdits) => {
    setSettings((prev) => ({ ...prev, allowUncheckedEdits }));
  }, []);

  const setWarningsEnabled = useCallback((warningsEnabled) => {
    setSettings((prev) => ({ ...prev, warningsEnabled }));
  }, []);

  const setShowTimeTracking = useCallback((showTimeTracking) => {
    setSettings((prev) => ({ ...prev, showTimeTracking }));
  }, []);

  const setBoldTabStyling = useCallback((boldTabStyling) => {
    setSettings((prev) => ({ ...prev, boldTabStyling }));
  }, []);

  const setListChangesHint = useCallback((listChangesHint) => {
    setSettings((prev) => ({ ...prev, listChangesHint }));
  }, []);

  const value = useMemo(
    () => ({
      showServerNames: settings.showServerNames,
      setShowServerNames,
      showMemberTimezones: settings.showMemberTimezones,
      setShowMemberTimezones,
      allowUncheckedEdits: settings.allowUncheckedEdits,
      setAllowUncheckedEdits,
      warningsEnabled: settings.warningsEnabled,
      setWarningsEnabled,
      showTimeTracking: settings.showTimeTracking,
      setShowTimeTracking,
      boldTabStyling: settings.boldTabStyling,
      setBoldTabStyling,
      listChangesHint: settings.listChangesHint,
      setListChangesHint,
    }),
    [
      settings.showServerNames,
      setShowServerNames,
      settings.showMemberTimezones,
      setShowMemberTimezones,
      settings.allowUncheckedEdits,
      setAllowUncheckedEdits,
      settings.warningsEnabled,
      setWarningsEnabled,
      settings.showTimeTracking,
      setShowTimeTracking,
      settings.boldTabStyling,
      setBoldTabStyling,
      settings.listChangesHint,
      setListChangesHint,
    ]
  );

  return <SettingsContext.Provider value={value}>{children}</SettingsContext.Provider>;
}

export function useSettings() {
  const ctx = useContext(SettingsContext);
  if (!ctx) throw new Error('useSettings must be used within SettingsProvider');
  return ctx;
}
