/**
 * SIMPLIFIED INTEGRATION TEST: WebView Communication
 * Starting with minimal test to understand the flow
 */

import React from 'react';
import { render, waitFor, fireEvent } from '@testing-library/react-native';
import { SoluCXWidgetView as SoluCXWidget } from '../../SoluCXWidgetView';

// Mock only external dependencies
jest.mock('react-native-webview', () => {
    const React = require('react');
    const { View, Text } = require('react-native');
    return {
        __esModule: true,
        WebView: React.forwardRef((props: any, ref: any) => {
            React.useImperativeHandle(ref, () => ({
                injectJavaScript: jest.fn(),
            }));
            
            return (
                <View testID="webview" {...props}>
                    <Text>WebView Mock</Text>
                </View>
            );
        }),
    };
});

jest.mock('../../services/WidgetBootstrapService', () => ({
    requestWidgetUrl: jest.fn().mockResolvedValue({ available: true, url: 'https://survey.url/test' }),
}));

jest.mock('../../services/WidgetValidationService', () => ({
    WidgetValidationService: jest.fn().mockImplementation(() => ({
        shouldDisplayForTransaction: jest.fn().mockResolvedValue({ canDisplay: true }),
        shouldDisplayForTransactionAlreadyAnswered: jest.fn().mockResolvedValue({ canDisplay: true }),
        shouldDisplayWidget: jest.fn().mockResolvedValue({ canDisplay: true }),
    })),
}));

const mockStorage: Record<string, string> = {};
jest.mock('@react-native-async-storage/async-storage', () => ({
    __esModule: true,
    default: {
        getItem: jest.fn((key: string) => Promise.resolve(mockStorage[key] || null)),
        setItem: jest.fn((key: string, value: string) => {
            mockStorage[key] = value;
            return Promise.resolve();
        }),
    },
}));

describe('Integration: WebView Communication - Simplified', () => {
    beforeEach(() => {
        jest.clearAllMocks();
        Object.keys(mockStorage).forEach(key => delete mockStorage[key]);
    });

    it('should render WebView in form mode', async () => {
        const { getByTestId, debug } = render(
            <SoluCXWidget
                soluCXKey="test-key"
                type="modal"
                data={{ form_id: 'form123', customer_id: 'user1' }}
                options={{ height: 400 }}
            />
        );

        debug(); // Log component tree

        await waitFor(() => {
            expect(getByTestId('webview')).toBeTruthy();
        }, { timeout: 10000 });
    }, 15000);

    it('should handle FORM_CLOSE message in form mode', async () => {
        const mockOnClosed = jest.fn();

        const { getByTestId } = render(
            <SoluCXWidget
                soluCXKey="test-key"
                type="modal"
                data={{ form_id: 'form123', customer_id: 'user1' }}
                options={{ height: 400 }}
                callbacks={{ onClosed: mockOnClosed }}
            />
        );

        await waitFor(() => {
            expect(getByTestId('webview')).toBeTruthy();
        }, { timeout: 3000 });

        // Simulate message
        const webview = getByTestId('webview');
        fireEvent(webview, 'message', {
            nativeEvent: { data: 'FORM_CLOSE' },
        });

        await waitFor(() => {
            expect(mockOnClosed).toHaveBeenCalledTimes(1);}, { timeout: 1000 });
    });

    it('should render WebView in survey mode', async () => {
        const { getByTestId } = render(
            <SoluCXWidget
                soluCXKey="test-key"
                type="modal"
                data={{ customer_id: 'user1' }} // No form_id = survey
                options={{ height: 400 }}
            />
        );

        await waitFor(() => {
            expect(getByTestId('webview')).toBeTruthy();
        }, { timeout: 3000 });
    });

    it('should handle closeSoluCXWidget message in survey mode', async () => {
        const mockOnClosed = jest.fn();

        const { getByTestId } = render(
            <SoluCXWidget
                soluCXKey="test-key"
                type="modal"
                data={{ customer_id: 'user1' }}
                options={{ height: 400 }}
                callbacks={{ onClosed: mockOnClosed }}
            />
        );

        await waitFor(() => {
            expect(getByTestId('webview')).toBeTruthy();
        }, { timeout: 3000 });

        const webview = getByTestId('webview');
        fireEvent(webview, 'message', {
            nativeEvent: { data: 'closeSoluCXWidget' },
        });

        await waitFor(() => {
            expect(mockOnClosed).toHaveBeenCalledTimes(1);
        }, { timeout: 1000 });
    });
});
