export class SearchEngineManager {
    constructor() {
        this.engines = JSON.parse(localStorage.getItem('searchEngines')) || [
            { name: 'SearXNG', url: 'https://search.ploszukiwacz.pl/search?q=%s', default: true }
        ];
        this.searchForm = document.getElementById('search-form');
        this.enginesContainer = document.getElementById('search-engines');
        this.init();
    }

    init() {
        this.renderEngines();
        this.attachEventListeners();
        this.setDefaultEngine();
    }

    renderEngines() {
        this.enginesContainer.innerHTML = this.engines.map((engine, index) => `
            <div class="search-engine">
                <input type="text" value="${engine.name}" placeholder="Name" 
                    onchange="searchManager.updateEngine(${index}, 'name', this.value)">
                <input type="text" value="${engine.url}" placeholder="URL with %s"
                    onchange="searchManager.updateEngine(${index}, 'url', this.value)">
                <label><input type="radio" name="default-engine" ${engine.default ? 'checked' : ''}
                    onchange="searchManager.setDefault(${index})"> Default</label>
                <button class="settings-btn small" onclick="searchManager.removeEngine(${index})">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `).join('');
    }

    attachEventListeners() {
        document.getElementById('addSearchEngine').addEventListener('click', () => {
            this.addEngine({
                name: 'New Engine',
                url: 'https://',
                default: false
            });
        });
    }

    addEngine(engine) {
        this.engines.push(engine);
        this.save();
        this.renderEngines();
    }

    updateEngine(index, field, value) {
        if (this.engines[index]) {
            this.engines[index][field] = value;
            this.save();
            this.renderEngines();
        }
    }

    removeEngine(index) {
        if (this.engines[index].default && this.engines.length > 1) {
            this.engines[0].default = true;
        }
        this.engines.splice(index, 1);
        this.save();
        this.renderEngines();
    }

    setDefault(index) {
        this.engines.forEach((engine, i) => {
            engine.default = i === index;
        });
        this.save();
        this.setDefaultEngine();
    }

    setDefaultEngine() {
        const defaultEngine = this.engines.find(e => e.default) || this.engines[0];
        if (defaultEngine) {
            this.searchForm.action = defaultEngine.url.replace('%s', '');
            this.searchForm.querySelector('input').placeholder = `Search with ${defaultEngine.name}...`;
        }
    }

    save() {
        localStorage.setItem('searchEngines', JSON.stringify(this.engines));
    }
}