import { createContext, useState, useContext, useCallback, useEffect } from '@wordpress/element';

// Share context globally to support cross-bundle access (main plugin + Pro plugin)
// Each plugin has its own webpack build, so createContext() would create separate instances.
// Using window ensures both bundles reference the same context object.
const CONTEXT_KEY = '__zenblocks_responsive_tab_context_v2__';
if (!window[CONTEXT_KEY]) {
  window[CONTEXT_KEY] = createContext();
}
const ResponsiveTabContextV2 = window[CONTEXT_KEY];

export const ResponsiveTabProviderV2 = ({ children, onTabChange, externalActiveTab }) => {
  const [activeTab, setActiveTabInternal] = useState(externalActiveTab || 'pc');
  const [previewMode, setPreviewMode] = useState(false);

  // 外部からactiveTabが変更された場合に同期
  useEffect(() => {
    if (externalActiveTab && externalActiveTab !== activeTab) {
      setActiveTabInternal(externalActiveTab);
    }
  }, [externalActiveTab]);

  // タブ変更時にonTabChangeコールバックも呼び出す
  const setActiveTab = useCallback((tab) => {
    setActiveTabInternal(tab);
    if (onTabChange) {
      onTabChange(tab);
    }
  }, [onTabChange]);

  return (
    <ResponsiveTabContextV2.Provider value={{ activeTab, setActiveTab, previewMode, setPreviewMode }}>
      {children}
    </ResponsiveTabContextV2.Provider>
  );
};

export const useResponsiveTabV2 = () => {
  const context = useContext(ResponsiveTabContextV2);
  if (!context) {
    return {
      activeTab: 'pc',
      setActiveTab: () => {},
      previewMode: false,
      setPreviewMode: () => {},
    };
  }
  return context;
};
