/**
 * Redux-like Pattern for Actor Menu Management
 */

//=============================================================================
// #region ACTIONS
//=============================================================================

// Action Types
const ActionTypes = {
    SET_AVAILABLE_ACTIONS: "SET_AVAILABLE_ACTIONS",
    SET_MENU_ITEMS: "SET_MENU_ITEMS",
    ADD_ACTION: "ADD_ACTION",
    REMOVE_ACTION: "REMOVE_ACTION",
    CLEAR_ACTIONS: "CLEAR_ACTIONS",
};

// Action Creators
const actions = {
    setAvailableActions: (actionTypes) => ({
        type: ActionTypes.SET_AVAILABLE_ACTIONS,
        payload: actionTypes,
    }),

    setMenuItems: (menuItems) => ({
        type: ActionTypes.SET_MENU_ITEMS,
        payload: menuItems,
    }),

    addAction: (actionType) => ({
        type: ActionTypes.ADD_ACTION,
        payload: actionType,
    }),

    removeAction: (actionType) => ({
        type: ActionTypes.REMOVE_ACTION,
        payload: actionType,
    }),

    clearActions: () => ({
        type: ActionTypes.CLEAR_ACTIONS,
    }),
};

//=============================================================================
// #region REDUCER
//=============================================================================

const baseMenuItems = [
    {
        id: "bank",
        title: "Banking Services",
        description: "Access your bank account and manage finances",
        icon: "",
        action: "actor::open::bank",
    },
    {
        id: "phone",
        title: "Personal Phone",
        description: "Access and manage your personal phone",
        icon: "",
        action: "actor::open::phone",
    },
];

const actionDefinitions = {
    device: {
        id: "device",
        title: "Device Interaction",
        description: "Manage devices and settings",
        icon: "",
        action: "actor::open::device",
    },
    garage: {
        id: "garage",
        title: "Vehicle Garage",
        description: "Access and manage your vehicle collection",
        icon: "",
        action: "actor::open::garage",
    },
    locker: {
        id: "locker",
        title: "Locker",
        description: "Access your personal locker for storage",
        icon: "",
        action: "actor::open::locker",
    },
    player: {
        id: "player",
        title: "Player Interaction",
        description: "Interact with player-specific actions",
        icon: "",
        action: "actor::open::iplayer",
    },
    store: {
        id: "store",
        title: "Store",
        description: "Browse and purchase items from the store",
        icon: "",
        action: "actor::open::store",
    },
    va: {
        id: "va",
        title: "Virtual Arsenal",
        description: "Access your virtual arsenal",
        icon: "",
        action: "actor::open::arsenal",
    },
    vg: {
        id: "vg",
        title: "Virtual Garage",
        description: "Access your virtual garage",
        icon: "",
        action: "actor::open::vgarage",
    },
};

const initialState = {
    availableActions: [],
    menuItems: [...baseMenuItems],
    baseMenuItems: [...baseMenuItems],
    actionDefinitions: { ...actionDefinitions },
};

function actorReducer(state = initialState, action) {
    switch (action.type) {
        case ActionTypes.SET_AVAILABLE_ACTIONS:
            const newMenuItems = [...state.baseMenuItems];

            // Process available actions
            const actionArray = Array.isArray(action.payload)
                ? action.payload
                : [];
            actionArray.forEach((actionItem) => {
                if (Array.isArray(actionItem) && actionItem.length === 2) {
                    const [type, value] = actionItem;
                    const definition = state.actionDefinitions[value];
                    if (definition) {
                        newMenuItems.push(definition);
                    } else {
                        console.warn(
                            `No definition found for: ${type} - ${value}`,
                        );
                    }
                } else {
                    console.warn("Invalid action format:", actionItem);
                }
            });

            return {
                ...state,
                availableActions: action.payload,
                menuItems: newMenuItems,
            };

        case ActionTypes.SET_MENU_ITEMS:
            return {
                ...state,
                menuItems: action.payload,
            };

        case ActionTypes.ADD_ACTION:
            const definition = state.actionDefinitions[action.payload];
            if (
                definition &&
                !state.menuItems.find((item) => item.id === definition.id)
            ) {
                return {
                    ...state,
                    menuItems: [...state.menuItems, definition],
                };
            }
            return state;

        case ActionTypes.REMOVE_ACTION:
            return {
                ...state,
                menuItems: state.menuItems.filter(
                    (item) => item.id !== action.payload,
                ),
            };

        case ActionTypes.CLEAR_ACTIONS:
            return {
                ...state,
                availableActions: [],
                menuItems: [...state.baseMenuItems],
            };

        default:
            return state;
    }
}

//=============================================================================
// #region STORE
//=============================================================================

class Store {
    constructor(reducer, initialState) {
        this.reducer = reducer;
        this.state = initialState;
        this.listeners = [];
    }

    getState() {
        return this.state;
    }

    dispatch(action) {
        console.log("Dispatching action:", action);
        this.state = this.reducer(this.state, action);
        this.listeners.forEach((listener) => listener(this.state));
    }

    subscribe(listener) {
        this.listeners.push(listener);
        return () => {
            this.listeners = this.listeners.filter((l) => l !== listener);
        };
    }
}

// Create store instance
const store = new Store(actorReducer, initialState);

//=============================================================================
// #region SELECTORS
//=============================================================================

const selectors = {
    getMenuItems: (state) => state.menuItems,
    getAvailableActions: (state) => state.availableActions,
    getBaseMenuItems: (state) => state.baseMenuItems,
    getActionDefinitions: (state) => state.actionDefinitions,
    getMenuItemById: (state, id) =>
        state.menuItems.find((item) => item.id === id),
    getMenuItemsCount: (state) => state.menuItems.length,
};

//=============================================================================
// #region UI COMPONENTS (Redux-connected)
//=============================================================================

class ActorUI {
    constructor(store) {
        this.store = store;
        this.unsubscribe = null;
    }

    init() {
        console.log("ActorUI initializing...");

        // Subscribe to state changes
        this.unsubscribe = this.store.subscribe((state) => {
            this.render(state);
        });

        // Initial render
        this.render(this.store.getState());

        // Request initial data
        this.requestInitialData();

        console.log("ActorUI initialized successfully");
    }

    render(state) {
        this.updateMenuDisplay(state);
    }

    updateMenuDisplay(state) {
        const grid = document.getElementById("menuGrid");
        if (!grid) {
            console.error("Menu grid element not found");
            return;
        }

        // Clear existing menu items
        grid.innerHTML = "";

        // Render menu items
        const menuItems = selectors.getMenuItems(state);
        menuItems.forEach((item) => {
            const menuItem = document.createElement("div");
            menuItem.className = "neu-menu-item";
            menuItem.setAttribute("data-action", item.action);
            menuItem.innerHTML = `
                <div class="neu-menu-item-icon">${item.icon}</div>
                <div class="neu-menu-item-title">${item.title}</div>
                <div class="neu-menu-item-description">${item.description}</div>
            `;
            menuItem.addEventListener("click", () =>
                this.handleMenuItemClick(item),
            );

            grid.appendChild(menuItem);
        });

        console.log(`Rendered ${menuItems.length} menu items`);
    }

    handleMenuItemClick(item) {
        console.log("Menu item clicked:", item);
        const alert = {
            event: item.action,
            data: {},
        };
        A3API.SendAlert(JSON.stringify(alert));
    }

    requestInitialData() {
        console.log("Requesting initial actor data...");
        const alert = {
            event: "actor::get::actions",
            data: {},
        };
        A3API.SendAlert(JSON.stringify(alert));
    }

    destroy() {
        if (this.unsubscribe) {
            this.unsubscribe();
        }
    }
}

//=============================================================================
// #region DATA HANDLERS (Redux-connected)
//=============================================================================

function updateAvailableActions(actionTypes) {
    console.log("Updating available actions:", actionTypes);
    store.dispatch(actions.setAvailableActions(actionTypes));
}

function handleGetActionsResponse(data) {
    console.log("Received actions data:", data);
    store.dispatch(actions.setAvailableActions(data));
}

//=============================================================================
// #region ACTION HANDLERS
//=============================================================================

function handleMenuItemClick(item) {
    console.log("Legacy menu item click handler:", item);
    const alert = {
        event: item.action,
        data: {},
    };
    A3API.SendAlert(JSON.stringify(alert));
}

//=============================================================================
// #region INITIALIZATION FUNCTIONS
//=============================================================================

// Global flag to prevent double initialization
let actorUIInitialized = false;

/**
 * Initialize the actor interface - called from HTML after script loads
 */
function initializeMenu() {
    console.log("initializeMenu() called");

    if (actorUIInitialized) {
        console.log("ActorUI already initialized, skipping...");
        return;
    }

    // Check if DOM is ready
    if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", () => {
            if (!actorUIInitialized) {
                console.log("DOM loaded, initializing ActorUI...");
                window.actorUI = new ActorUI(store);
                window.actorUI.init();
                actorUIInitialized = true;
            }
        });
    } else {
        // DOM is already ready
        console.log("DOM already ready, initializing ActorUI...");
        window.actorUI = new ActorUI(store);
        window.actorUI.init();
        actorUIInitialized = true;
    }
}

//=============================================================================
// #region GLOBAL VARIABLES
//=============================================================================

// Make actorUI globally accessible
let actorUI;

// Auto-initialize if DOM is already loaded when script executes
if (document.readyState !== "loading") {
    console.log("Script loaded after DOM ready, auto-initializing...");
    if (!actorUIInitialized) {
        actorUI = new ActorUI(store);
        actorUI.init();
        actorUIInitialized = true;
    }
} else {
    // Wait for DOM to be ready
    document.addEventListener("DOMContentLoaded", () => {
        if (!actorUIInitialized) {
            console.log("DOM loaded, initializing ActorUI...");
            actorUI = new ActorUI(store);
            actorUI.init();
            actorUIInitialized = true;
        }
    });
}
