import { PanelBody } from "@wordpress/components";
import { useState, useCallback } from "@wordpress/element";

const STORAGE_KEY = "zenblocks-panel-states";

const getStoredStates = () => {
  try {
    const saved = window.localStorage.getItem(STORAGE_KEY);
    return saved ? JSON.parse(saved) : {};
  } catch (e) {
    return {};
  }
};

const saveState = (panelId, isOpen) => {
  try {
    const states = getStoredStates();
    states[panelId] = isOpen;
    window.localStorage.setItem(STORAGE_KEY, JSON.stringify(states));
  } catch (e) {}
};

export const getPanelState = (panelId, defaultOpen = false) => {
  const states = getStoredStates();
  return states[panelId] !== undefined ? states[panelId] : defaultOpen;
};

export const usePersistentPanel = (panelId, defaultOpen = false) => {
  const [isOpen, setIsOpen] = useState(() => getPanelState(panelId, defaultOpen));

  const toggle = useCallback(() => {
    setIsOpen((prev) => {
      const newState = !prev;
      saveState(panelId, newState);
      return newState;
    });
  }, [panelId]);

  return { isOpen, toggle };
};

export const PersistentPanelBody = ({ panelId, children, initialOpen = false, ...props }) => {
  const { isOpen, toggle } = usePersistentPanel(panelId, initialOpen);

  return (
    <PanelBody {...props} opened={isOpen} onToggle={toggle}>
      {children}
    </PanelBody>
  );
};

export default PersistentPanelBody;
