// Base Web Component Class
export class BaseComponent extends HTMLElement {
    constructor() {
        super();
        this.state = {};
        this.listeners = [];
    }

    // Lifecycle methods
    connectedCallback() {
        this.render();
        this.bindEvents();
    }

    disconnectedCallback() {
        this.cleanup();
    }

    attributeChangedCallback(name, oldValue, newValue) {
        if (oldValue !== newValue) {
            this.onAttributeChanged(name, oldValue, newValue);
        }
    }

    // State management
    setState(newState) {
        this.state = { ...this.state, ...newState };
        this.render();
    }

    getState() {
        return { ...this.state };
    }

    // Event handling
    addEventListener(element, event, handler, options = {}) {
        element.addEventListener(event, handler, options);
        this.listeners.push({ element, event, handler, options });
    }

    cleanup() {
        this.listeners.forEach(({ element, event, handler, options }) => {
            element.removeEventListener(event, handler, options);
        });
        this.listeners = [];
    }

    // Template methods (to be overridden)
    render() {
        // Override in child components
    }

    bindEvents() {
        // Override in child components
    }

    onAttributeChanged(name, oldValue, newValue) {
        // Override in child components if needed
    }

    // Utility methods
    $(selector) {
        return this.querySelector(selector);
    }

    $$(selector) {
        return this.querySelectorAll(selector);
    }

    emit(eventName, detail = {}) {
        const event = new CustomEvent(eventName, {
            detail,
            bubbles: true,
            composed: true
        });
        this.dispatchEvent(event);
    }

    // HTML template helpers
    html(strings, ...values) {
        return strings.reduce((result, string, i) => {
            const value = values[i] !== undefined ? values[i] : '';
            return result + string + value;
        }, '');
    }

    css(styles) {
        if (typeof styles === 'string') {
            return `<style>${styles}</style>`;
        }
        
        if (typeof styles === 'object') {
            const cssText = Object.entries(styles)
                .map(([key, value]) => `${key}: ${value};`)
                .join(' ');
            return cssText;
        }
        
        return '';
    }
}