// src/navigation/WebAppLayout.tsx
import React, { useRef, useState, useEffect } from 'react';
import { View, StyleSheet } from 'react-native';
import {
    NavigationContainer,
    NavigationContainerRef, // Correct type for ref
    DefaultTheme as NavigationDefaultTheme,
    DarkTheme as NavigationDarkTheme,
    NavigationIndependentTree
} from '@react-navigation/native';

import WebSidebar from '../components/WebSidebar';
import WebContentNavigator from './WebContentNavigator';
import theme from '../constants/theme'; // Your Paper theme
import { WebContentStackParamList, WebContentNavigationProp } from '../types/navigation'; // Import correct types

// Combine Paper theme with Navigation theme
export const CombinedDarkTheme = {
    ...NavigationDarkTheme,
    ...theme,
    colors: {
      ...NavigationDarkTheme.colors,
      ...theme.colors,
      card: theme.colors.surface,
      border: theme.colors.surface,
      text: theme.colors.text,
      primary: theme.colors.primary,
      background: theme.colors.background,
    },
};


const WebAppLayout = () => {
    // Use the specific ref type
    const navigationRef = useRef<WebContentNavigationProp>(null);
    const [currentWebRoute, setCurrentWebRoute] = useState<string | undefined>(undefined);

     const handleWebNavigationReady = () => {
        setCurrentWebRoute(navigationRef.current?.getCurrentRoute()?.name);
    };
    const handleWebNavigationStateChange = () => {
        const currentRoute = navigationRef.current?.getCurrentRoute();
        if (currentRoute) {
            setCurrentWebRoute(currentRoute.name);
        }
    };

    const styles = StyleSheet.create({
        webContainer: {
            flex: 1,
            flexDirection: 'row',
            height: '100vh', // Full viewport height for web
            backgroundColor: theme.colors.background,
        },
        contentArea: {
            flex: 1, // Content takes remaining space
            height: '100%',
        },
    });

    return (
        <View style={styles.webContainer}>
           <WebSidebar navigationRef={navigationRef} currentRouteName={currentWebRoute} />
           <View style={styles.contentArea}>
            <NavigationIndependentTree>
               <NavigationContainer
                   ref={navigationRef}
                   theme={CombinedDarkTheme}
                   onReady={handleWebNavigationReady}
                   onStateChange={handleWebNavigationStateChange}
               >
                   <WebContentNavigator />
               </NavigationContainer>
            </NavigationIndependentTree>
           </View>
       </View>
   )
}

export default WebAppLayout;