// Import WordPress i18n function
const { __ } = wp.i18n;

class SharedLinkSelector {
    constructor() {
        this.selectedLinkId = null;
        this.selectedLinkTitle = null;
        this.selectedCategoryId = null;
        this.selectedCategoryName = null;
        this.isPremium = linkcentral_insights_data.can_use_premium_code__premium_only === '1';
        this.listeners = []; // Array to store event listeners
    }

    init() {
        this.setupEventListeners();
        this.updateAllLinksButtonState(true);
    }

    setupEventListeners() {
        // All Links button
        jQuery('#linkcentral-shared-all-links').on('click', (e) => {
            e.preventDefault();
            this.resetToAllLinks();
        });

        
    }

    handleUnifiedSelect(event, ui) {
        if (ui.item.type === 'link') {
            this.selectedLinkId = ui.item.value;
            this.selectedLinkTitle = ui.item.title;
            this.selectedCategoryId = null;
            this.selectedCategoryName = null;
        } else if (ui.item.type === 'category') {
            this.selectedCategoryId = ui.item.value;
            this.selectedCategoryName = ui.item.title;
            this.selectedLinkId = null;
            this.selectedLinkTitle = null;
        }
        
        jQuery('#linkcentral-shared-unified-search').val(ui.item.title);
        
        this.updateAllLinksButtonState(false);
        this.notifyListeners();
        return false; // Prevent default behavior
    }

    resetToAllLinks() {
        this.selectedLinkId = null;
        this.selectedLinkTitle = null;
        this.selectedCategoryId = null;
        this.selectedCategoryName = null;
        jQuery('#linkcentral-shared-unified-search').val('');
        
        this.updateAllLinksButtonState(true);
        this.notifyListeners();
    }

    updateAllLinksButtonState(isSelected) {
        const $allLinksButton = jQuery('#linkcentral-shared-all-links');
        $allLinksButton.toggleClass('selected', isSelected);
    }

    

    // Public methods for external components
    addEventListener(callback) {
        this.listeners.push(callback);
    }

    notifyListeners() {
        this.listeners.forEach(callback => {
            callback({
                linkId: this.selectedLinkId,
                linkTitle: this.selectedLinkTitle,
                categoryId: this.selectedCategoryId,
                categoryName: this.selectedCategoryName
            });
        });
    }

    getCurrentSelection() {
        return {
            linkId: this.selectedLinkId,
            linkTitle: this.selectedLinkTitle,
            categoryId: this.selectedCategoryId,
            categoryName: this.selectedCategoryName
        };
    }
}

export default SharedLinkSelector; 