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

const KEY = 'mo-midsummer';

// Seasonal master switch. The Små grodorna theme is only active around
// Midsummer week. Out of season this is false → the theme is fully dormant
// (no rain/frogs/maypole/banner/palette) regardless of any stored preference,
// and the 🐸 toggle is removed from the sidebar. To bring it back next year:
// flip this to true and re-add <FrogToggle /> in SidebarWindowButtons.tsx.
const SEASON_ACTIVE = false;

interface MidsummerCtx {
  enabled: boolean;
  toggle: () => void;
}

const Ctx = createContext<MidsummerCtx | null>(null);

export const MidsummerProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  // In season, default ON (only the literal "off" disables). Out of season,
  // always off — the stored preference is ignored.
  const [pref, setPref] = useState<boolean>(() => localStorage.getItem(KEY) !== 'off');
  const enabled = SEASON_ACTIVE && pref;

  useEffect(() => {
    const el = document.documentElement;
    if (enabled) el.setAttribute('data-midsummer', '');
    else el.removeAttribute('data-midsummer');
  }, [enabled]);

  const toggle = useCallback(() => {
    setPref(p => {
      const next = !p;
      localStorage.setItem(KEY, next ? 'on' : 'off');
      return next;
    });
  }, []);

  return (
    <Ctx.Provider value={{ enabled, toggle }}>
      {children}
    </Ctx.Provider>
  );
};

export function useMidsummer(): MidsummerCtx {
  const c = useContext(Ctx);
  if (!c) throw new Error('useMidsummer must be used within MidsummerProvider');
  return c;
}
