const colorInput = document.getElementById('color-input');
const selectedHexNode = document.getElementById('selected-hex');
const complementHexNode = document.getElementById('complement-hex');
const selectedColorBox = document.getElementById('selected-color');
const complementColorBox = document.getElementById('complement-color');
const paletteContainer = document.getElementById('palette-container');
const themeSelector = document.getElementById('theme-selector');
const themePreview = document.getElementById('theme-preview-content');
const themeDescription = document.getElementById('theme-description');

const paletteEndpoint = '../palettes/default.json';
const themesEndpoint = '../themes/themes.json';
let palettes = [];
let themes = [];

async function fetchPalettes() {
    try {
        const response = await fetch(paletteEndpoint);
        const data = await response.json();
        palettes = data.palettes || [];
        renderPalettes(palettes);
    } catch (err) {
        paletteContainer.textContent = 'Impossible de charger les palettes.';
        console.error(err);
    }
}

async function fetchThemes() {
    try {
        const response = await fetch(themesEndpoint);
        const data = await response.json();
        themes = data.themes || [];
        populateThemeSelector(themes);
    } catch (err) {
        themeDescription.textContent = 'Erreur lors du chargement des thèmes.';
        console.error(err);
    }
}

function populateThemeSelector(themeList) {
    themeSelector.innerHTML = '';
    themeList.forEach((theme, index) => {
        const option = document.createElement('option');
        option.value = theme.file;
        option.textContent = theme.name;
        themeSelector.appendChild(option);
        if (index === 0) {
            loadTheme(theme);
        }
    });
}

async function loadTheme(theme) {
    try {
        const response = await fetch(`../themes/${theme.file}`);
        const content = await response.text();
        themeDescription.textContent = theme.description || 'Aperçu CSS interactif.';
        themePreview.textContent = content.trim();
    } catch (err) {
        themePreview.textContent = 'Impossible de charger le fichier.';
        console.error(err);
    }
}

function renderPalettes(list) {
    paletteContainer.innerHTML = '';
    list.forEach(palette => {
        const card = document.createElement('article');
        card.className = 'palette-card';
        card.innerHTML = `
        <header>
            <h3>${palette.name}</h3>
            <small>${palette.description}</small>
        </header>
        <div class="palette-colors"></div>
        <button data-palette="${palette.name}">Copier la sélection</button>
        `;
        const colorGrid = card.querySelector('.palette-colors');
        palette.colors.forEach(color => {
            const swatch = document.createElement('span');
            swatch.style.background = color;
            swatch.dataset.hex = color;
            swatch.title = color;
            swatch.addEventListener('click', () => updateColor(color));
            colorGrid.appendChild(swatch);
        });
        const copyButton = card.querySelector('button');
        copyButton.addEventListener('click', () => {
            const text = palette.colors.join(', ');
            copyToClipboard(text, copyButton);
        });
        paletteContainer.appendChild(card);
    });
}

function updateColor(hex) {
    const normalized = hex.startsWith('#') ? hex : `#${hex}`;
    colorInput.value = normalized;
    selectedHexNode.textContent = normalized;
    selectedColorBox.style.background = normalized;
    const complement = getComplement(normalized);
    complementColorBox.style.background = complement;
    complementHexNode.textContent = complement;
}

function getComplement(hex) {
    const r = parseInt(hex.slice(1, 3), 16);
    const g = parseInt(hex.slice(3, 5), 16);
    const b = parseInt(hex.slice(5, 7), 16);
    const complement = [255 - r, 255 - g, 255 - b]
        .map(value => value.toString(16).padStart(2, '0'))
        .join('');
    return `#${complement}`;
}

function copyToClipboard(text, button) {
    navigator.clipboard.writeText(text).then(() => {
        if (button) {
            const original = button.dataset.origText || button.textContent;
            button.dataset.origText = original;
            button.textContent = 'Copié';
            button.classList.add('copied');
            setTimeout(() => {
                button.textContent = original;
                button.classList.remove('copied');
            }, 1200);
        }
    }).catch(err => {
        console.error('Impossible de copier', err);
    });
}

colorInput.addEventListener('input', (event) => {
    updateColor(event.target.value);
});

document.querySelectorAll('button[data-copy]').forEach(button => {
    button.addEventListener('click', () => {
        const target = button.dataset.copy;
        const text = target === 'selected' ? selectedHexNode.textContent : complementHexNode.textContent;
        copyToClipboard(text, button);
    });
});

themeSelector.addEventListener('change', () => {
    const theme = themes.find(t => t.file === themeSelector.value);
    if (theme) {
        loadTheme(theme);
    }
});

const themePanel = document.getElementById('theme-panel');
document.getElementById('theme-toggle').addEventListener('click', () => {
    themePanel.classList.toggle('collapsed');
});

fetchPalettes();
fetchThemes();
updateColor(colorInput.value);
