import { useRef, useCallback } from 'react';
import ReactDOM from 'react-dom/client';

/**
 * Hook to manage documentPictureInPicture window lifecycle
 * 
 * @param {Object} options
 * @param {Function} options.onClose - Callback when PiP window closes
 * @returns {Object} { isSupported, openPip, closePip, updateContent }
 */
const usePipWindow = ({ onClose }) => {
  const pipWinRef = useRef(null);
  const pipRootRef = useRef(null);

  // Check browser support for documentPictureInPicture
  const isSupported = typeof window !== 'undefined' && 'documentPictureInPicture' in window;

  /**
   * Open PiP window with specified size and content
   * 
   * @param {{w: number, h: number}} size - Window dimensions
   * @param {React.ReactElement} content - React component to render
   */
  const openPip = useCallback(async (size, content) => {
    if (!isSupported) {
      return;
    }

    try {
      // Request PiP window from browser
      const pipWin = await window.documentPictureInPicture.requestWindow({
        width: size.w,
        height: size.h,
      });

      // Copy CSS stylesheets from main window to PiP window
      // This includes Tailwind utility classes needed for MaskedIcon colors
      [...document.styleSheets].forEach(sheet => {
        try {
          if (sheet.href) {
            // External stylesheet (e.g. Tailwind CSS bundle) — copy as <link>
            const link = pipWin.document.createElement('link');
            link.rel = 'stylesheet';
            link.href = sheet.href;
            pipWin.document.head.appendChild(link);
          } else {
            // Inline stylesheet — copy rules as <style>
            const cssRules = [...sheet.cssRules].map(rule => rule.cssText).join('');
            const style = pipWin.document.createElement('style');
            style.textContent = cssRules;
            pipWin.document.head.appendChild(style);
          }
        } catch (e) {
          // Skip cross-origin stylesheets
        }
      });

      // Inject CSS variables from main document :root into PiP window
      // This ensures --bg-card, --t-color, etc. are available in PiP
      try {
        const rootStyles = getComputedStyle(document.documentElement);
        const cssVarNames = [
          '--bg-base', '--bg-panel', '--bg-card', '--bg-card-hover',
          '--bg-border', '--bg-border-dim',
          '--t-color', '--t-dim', '--t-border',
          '--ct-color', '--ct-dim', '--ct-border',
          '--text-primary', '--text-secondary', '--text-muted',
          '--hp-high', '--hp-mid', '--hp-low', '--money',
          '--card-radius', '--panel-radius',
        ];
        const varDecls = cssVarNames
          .map(v => `${v}: ${rootStyles.getPropertyValue(v).trim()};`)
          .join(' ');
        const rootStyle = document.createElement('style');
        rootStyle.textContent = `:root { ${varDecls} } *, *::before, *::after { box-sizing: border-box; } html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; } body { font-family: Inter, system-ui, -apple-system, sans-serif; color: var(--text-primary); background: var(--bg-base); -webkit-font-smoothing: antialiased; }`;
        pipWin.document.head.insertBefore(rootStyle, pipWin.document.head.firstChild);
      } catch (e) {
        // Failed to inject CSS variables
      }

      // Create container div for React content — must fill 100% of body
      const container = pipWin.document.createElement('div');
      container.style.cssText = 'width:100%;height:100%;margin:0;padding:0;display:flex;flex-direction:column;';
      pipWin.document.body.style.cssText = 'margin:0;padding:0;overflow:hidden;width:100%;height:100%;';
      pipWin.document.documentElement.style.cssText = 'width:100%;height:100%;overflow:hidden;';
      pipWin.document.body.appendChild(container);

      // Mount React component using createRoot
      const root = ReactDOM.createRoot(container);
      root.render(content);

      // Store references
      pipWinRef.current = pipWin;
      pipRootRef.current = root;

      // Attach pagehide listener for cleanup
      pipWin.addEventListener('pagehide', () => {
        // Unmount React component
        if (pipRootRef.current) {
          pipRootRef.current.unmount();
          pipRootRef.current = null;
        }
        
        // Clear window reference
        pipWinRef.current = null;
        
        // Call onClose callback
        if (onClose) {
          onClose();
        }
      });
    } catch (error) {
      // Failed to open PiP window
    }
  }, [isSupported, onClose]);

  /**
   * Close PiP window and cleanup
   */
  const closePip = useCallback(() => {
    // Unmount React component
    if (pipRootRef.current) {
      pipRootRef.current.unmount();
      pipRootRef.current = null;
    }

    // Close window
    if (pipWinRef.current) {
      pipWinRef.current.close();
      pipWinRef.current = null;
    }

    // Call onClose callback
    if (onClose) {
      onClose();
    }
  }, [onClose]);

  /**
   * Update content in existing PiP window
   * 
   * @param {React.ReactElement} content - New React component to render
   */
  const updateContent = useCallback((content) => {
    if (pipRootRef.current) {
      pipRootRef.current.render(content);
    }
  }, []);

  return {
    isSupported,
    openPip,
    closePip,
    updateContent,
  };
};

export default usePipWindow;
