define([
    'uiComponent',
    'ko',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/checkout-data'
], function (Component, ko, quote, checkoutData) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'PortalPeople_GetAddressAutocomplete/address-autocomplete'
        },

        searchTerm: ko.observable(''),
        addresses: ko.observableArray([]),
        selectedAddress: ko.observable(null),
        isLoading: ko.observable(false),
        errorMessage: ko.observable(''),
        showAddressList: ko.observable(false),
        isEnabled: ko.observable(false),

        initialize: function () {
            this._super();

            console.log('========================================');
            console.log('Address Autocomplete Component: Initializing...');
            console.log('window.checkoutConfig exists:', !!window.checkoutConfig);
            
            if (window.checkoutConfig) {
                console.log('checkoutConfig keys:', Object.keys(window.checkoutConfig));
                console.log('getaddress_autocomplete config:', window.checkoutConfig.getaddress_autocomplete);
            }
            
            // Read CSP-safe JSON config payload if present
            var configFromDom = null;
            var configEl = document.getElementById('getaddress-autocomplete-config');
            if (configEl && configEl.textContent) {
                try {
                    configFromDom = JSON.parse(configEl.textContent);
                } catch (e) {
                    console.log('GetAddress Autocomplete: Failed to parse JSON config payload');
                }
            }

            if (configFromDom && configFromDom.getaddress_autocomplete) {
                window.getAddressAutocompleteConfig = configFromDom.getaddress_autocomplete;
                if (!window.checkoutConfig) {
                    window.checkoutConfig = {};
                }
                // Merge DOM config into checkoutConfig to ensure api_key is included
                if (!window.checkoutConfig.getaddress_autocomplete) {
                    window.checkoutConfig.getaddress_autocomplete = configFromDom.getaddress_autocomplete;
                } else {
                    // Merge properties from DOM config into existing config
                    Object.assign(window.checkoutConfig.getaddress_autocomplete, configFromDom.getaddress_autocomplete);
                }
            }

            // Use fallback global config if checkoutConfig does not include our section
            if (window.checkoutConfig &&
                !window.checkoutConfig.getaddress_autocomplete &&
                window.getAddressAutocompleteConfig) {
                window.checkoutConfig.getaddress_autocomplete = window.getAddressAutocompleteConfig;
            }

            // Check if module is enabled via window checkout config
            // This is populated by ConfigProvider or injected config block
            if (window.checkoutConfig && 
                window.checkoutConfig.getaddress_autocomplete &&
                window.checkoutConfig.getaddress_autocomplete.enabled) {
                this.isEnabled(true);
                console.log('✓ Address Autocomplete Component Loaded and ENABLED');
                console.log('  - Full Config:', window.checkoutConfig.getaddress_autocomplete);
            } else {
                this.isEnabled(false);
                console.log('✗ Address Autocomplete Component DISABLED');
                if (!window.checkoutConfig) {
                    console.log('  - Reason: window.checkoutConfig not found');
                } else if (!window.checkoutConfig.getaddress_autocomplete) {
                    console.log('  - Reason: getaddress_autocomplete config section not found');
                    console.log('  - Available keys:', Object.keys(window.checkoutConfig).join(', '));
                } else {
                    console.log('  - Reason: Module not enabled or API key not configured');
                    console.log('  - Config:', window.checkoutConfig.getaddress_autocomplete);
                    console.log('  - enabled flag:', window.checkoutConfig.getaddress_autocomplete.enabled);
                    console.log('  - has_api_key:', window.checkoutConfig.getaddress_autocomplete.has_api_key);
                    console.log('  - is_enabled_flag:', window.checkoutConfig.getaddress_autocomplete.is_enabled_flag);
                }
            }
            console.log('========================================');

            return this;
        },

        visible: function () {
            return this.isEnabled();
        },

        searchAddresses: function () {
            var self = this;
            var term = this.searchTerm().trim();

            if (term.length < 2) {
                this.addresses([]);
                this.showAddressList(false);
                return;
            }

            this.isLoading(true);
            this.errorMessage('');

            // Get API key from config
            var apiKey = window.checkoutConfig && 
                         window.checkoutConfig.getaddress_autocomplete && 
                         window.checkoutConfig.getaddress_autocomplete.api_key;

            // Debug logging
            console.log('searchAddresses() called');
            console.log('apiKey from checkoutConfig:', apiKey);
            console.log('checkoutConfig.getaddress_autocomplete:', window.checkoutConfig && window.checkoutConfig.getaddress_autocomplete);
            console.log('window.getAddressAutocompleteConfig:', window.getAddressAutocompleteConfig);

            // Fallback: If not in checkoutConfig, try the global config
            if (!apiKey && window.getAddressAutocompleteConfig) {
                apiKey = window.getAddressAutocompleteConfig.api_key;
                console.log('✓ Using apiKey from window.getAddressAutocompleteConfig:', apiKey);
            }

            if (!apiKey) {
                this.isLoading(false);
                this.errorMessage('GetAddress.io API key not configured.');
                console.error('❌ No API key found in either checkoutConfig or window.getAddressAutocompleteConfig');
                return;
            }

            // Call GetAddress.io API
            var url = 'https://api.getaddress.io/find/' + encodeURIComponent(term) + '?api-key=' + encodeURIComponent(apiKey);

            fetch(url)
                .then(function(response) {
                    if (!response.ok) {
                        throw new Error('API request failed with status ' + response.status);
                    }
                    return response.json();
                })
                .then(function(data) {
                    self.isLoading(false);

                    if (data.Addresses && data.Addresses.length > 0) {
                        // Map GetAddress.io response to our format
                        var addresses = data.Addresses.map(function(addr, index) {
                            return {
                                address: addr.Address || addr.Label,
                                Label: addr.Label,
                                AddressId: addr.Id,
                                postcode: term  // Use search term (typically postcode)
                            };
                        });

                        self.addresses(addresses);
                        self.showAddressList(true);
                    } else {
                        self.errorMessage('No addresses found for "' + term + '"');
                    }
                })
                .catch(function(error) {
                    self.isLoading(false);
                    console.error('GetAddress.io API Error:', error);
                    self.errorMessage('Error searching for addresses. Please try again.');
                });
        },

        selectAddress: function (address) {
            this.selectedAddress(address);
            this.showAddressList(false);
            this.populateAddress(address);
        },

        populateAddress: function (address) {
            var shippingAddress = quote.shippingAddress();

            if (shippingAddress) {
                // Parse address and populate fields
                var addressParts = address.address ? address.address.split(', ') : [];
                
                shippingAddress.street = addressParts.length > 0 ? [addressParts[0]] : [''];
                shippingAddress.city = addressParts[addressParts.length - 1] || '';
                shippingAddress.postcode = address.postcode || '';
                shippingAddress.countryId = 'GB';
                shippingAddress.region = '';
                
                quote.shippingAddress(shippingAddress);
                console.log('Address populated:', address);
            }
        },

        clearSelection: function () {
            this.searchTerm('');
            this.selectedAddress(null);
            this.addresses([]);
            this.showAddressList(false);
            this.errorMessage('');
        }
    });
});
