const { useState, useEffect } = React;

const BugGenerator = () => {
    const [currentBug, setCurrentBug] = useState('Qui peut s\'assoir à la même table que Dofus et dire qu\'il a des bugs qui sont tout aussi stylés ?');

    const generateBug = async () => {
        try {
            const [hooksResponse, bugsResponse, featuresResponse] = await Promise.all([
                fetch('data/hooks.json'),
                fetch('data/bugs.json'),
                fetch('data/features.json')
            ]);

            const [hooks, bugs, features] = await Promise.all([
                hooksResponse.json(),
                bugsResponse.json(),
                featuresResponse.json()
            ]);

            const hook = hooks.hooks[Math.floor(Math.random() * hooks.hooks.length)];
            const bug = bugs.bugs[Math.floor(Math.random() * bugs.bugs.length)];
            const feature = features.features[Math.floor(Math.random() * features.features.length)];

            const phrase = hook.includes("fait que") ? 
                `${hook} ${feature}` : 
                `${hook} ${bug}, ${feature}`;

            setCurrentBug(phrase);
        } catch (error) {
            console.error('Erreur lors de la génération:', error);
            setCurrentBug('Une erreur s\'est produite. Veuillez réessayer.');
        }
    };

    const generateImage = async () => {
        try {
            // Créer un canvas temporaire
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            
            // Définir la taille du canvas
            canvas.width = 1200;
            canvas.height = 630;
            
            // Définir le style
            ctx.fillStyle = '#1a1b26';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // Charger le favicon
            const faviconLoadPromise = new Promise((resolve, reject) => {
                const favicon = new Image();
                favicon.onload = () => resolve(favicon);
                favicon.onerror = reject;
                favicon.src = 'assets/favicon.png';
            });
            
            const favicon = await faviconLoadPromise;
            // Dessiner le favicon
            const iconSize = 64;
            ctx.drawImage(favicon, 
                canvas.width/2 - (iconSize + 180), // Position X (à gauche du texte)
                80 - iconSize/2, // Position Y (centré avec le texte)
                iconSize, 
                iconSize
            );
            
            // Ajouter le texte "À cause de Flash"
            ctx.fillStyle = '#9ece6a';
            ctx.font = 'bold 48px Arial';
            ctx.textAlign = 'center';
            ctx.fillText('À cause de Flash', canvas.width/2, 120);
            
            // Ajouter le bug
            ctx.fillStyle = '#c0caf5';
            ctx.font = '32px Arial';
            
            // Wrapper le texte
            const words = currentBug.split(' ');
            let line = '';
            let lines = [];
            const maxWidth = canvas.width - 100;
            const lineHeight = 40;
            
            for (let n = 0; n < words.length; n++) {
                const testLine = line + words[n] + ' ';
                const metrics = ctx.measureText(testLine);
                if (metrics.width > maxWidth) {
                    lines.push(line);
                    line = words[n] + ' ';
                } else {
                    line = testLine;
                }
            }
            lines.push(line);
            
            // Dessiner les lignes de texte
            lines.forEach((line, i) => {
                ctx.fillText(line, canvas.width/2, 280 + (i * lineHeight));
            });
            
            // Ajouter le watermark
            ctx.fillStyle = '#a9b1d6';
            ctx.font = '24px Arial';
            ctx.fillText('https://cila.camelia-studio.org/a-cause-de-flash/', canvas.width/2, canvas.height - 40);
            
            // Convertir le canvas en image et déclencher le téléchargement
            const dataUrl = canvas.toDataURL('image/png');
            const link = document.createElement('a');
            link.download = 'mon-bug-dofus.png';
            link.href = dataUrl;
            link.click();
        } catch (error) {
            console.error('Erreur lors de la génération de l\'image:', error);
            alert('Une erreur s\'est produite lors de la génération de l\'image.');
        }
    };

    return React.createElement('div', { className: 'bug-container' },
        React.createElement('button', {
            onClick: generateBug,
            className: 'generate-button'
        }, 'Générer un bug !'),
        React.createElement('div', {
            className: 'bug-result'
        }, currentBug),
        React.createElement('button', {
            onClick: generateImage,
            className: 'share-button'
        }, 'Partager mon bug')
    );
};

// Attendre que le DOM soit chargé
document.addEventListener('DOMContentLoaded', () => {
    const root = document.getElementById('bug-generator-root');
    ReactDOM.createRoot(root).render(React.createElement(BugGenerator));
});