/**
 * Italian SEO Validator - Gutenberg Sidebar Component
 * Versione Lite con validazione locale
 */

import { registerPlugin } from '@wordpress/plugins';
import { PluginDocumentSettingPanel } from '@wordpress/edit-post';
import { Button, Spinner, Notice, PanelRow } from '@wordpress/components';
import { useState, useEffect } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';
import { __ } from '@wordpress/i18n';
import { useSelect } from '@wordpress/data';
import { store as editorStore } from '@wordpress/editor';

const ItalianSEOValidatorSidebar = () => {
    const [isValidating, setIsValidating] = useState(false);
    const [validationResult, setValidationResult] = useState(null);
    const [error, setError] = useState(null);
    const [usageRemaining, setUsageRemaining] = useState(null);
    const [isLoadingSaved, setIsLoadingSaved] = useState(false);
    const [savedValidationAge, setSavedValidationAge] = useState(null);

    // Ottieni contenuto post corrente E post ID
    const { postContent, postId } = useSelect((select) => {
        const editor = select(editorStore);
        return {
            postContent: editor.getEditedPostContent(),
            postId: editor.getCurrentPostId()
        };
    }, []);
    
    // 🔄 CARICA VALIDAZIONE SALVATA all'apertura dell'editor
    useEffect(() => {
        const loadSavedValidation = async () => {
            if (!postId || postId === 0) return;
            
            setIsLoadingSaved(true);
            
            try {
                const response = await apiFetch({
                    path: `/ept/v1/validation/${postId}`,
                    method: 'GET'
                });
                
                if (response.success && response.has_saved_validation) {
                    setValidationResult(response.validation);
                    setSavedValidationAge(response.saved_data.age_days);
                    console.log('EPT: Validazione salvata caricata', response);
                }
            } catch (err) {
                console.log('EPT: Nessuna validazione salvata disponibile');
            } finally {
                setIsLoadingSaved(false);
            }
        };
        
        loadSavedValidation();
    }, [postId]);

    // Funzione per validare il contenuto
    const handleValidate = async () => {
        setIsValidating(true);
        setError(null);
        setValidationResult(null);
        setSavedValidationAge(null); // Reset età validazione precedente

        try {
            const response = await apiFetch({
                path: '/ept/v1/validate',
                method: 'POST',
                data: {
                    content: postContent,
                    post_id: postId,  // 🔑 Passa post_id per salvare risultati
                    tier: 'lite'
                }
            });

            if (response.success) {
                setValidationResult(response.data);
                setUsageRemaining(response.usage_remaining);
                setSavedValidationAge(0); // Validazione appena fatta
            } else {
                setError(response.message || 'Errore durante la validazione');
            }
        } catch (err) {
            setError(err.message || 'Errore di connessione con il server');
        } finally {
            setIsValidating(false);
        }
    };

    // Funzione per ottenere il colore del badge in base al punteggio
    const getScoreBadgeClass = (score) => {
        if (score >= 80) return 'ept-score-excellent';
        if (score >= 60) return 'ept-score-good';
        if (score >= 40) return 'ept-score-medium';
        return 'ept-score-poor';
    };

    // Funzione per ottenere l'etichetta di leggibilitÃ 
    const getReadabilityLabel = (score) => {
        if (score >= 80) return 'Ottima';
        if (score >= 60) return 'Buona';
        if (score >= 40) return 'Media';
        return 'Difficile';
    };

    return (
        <PluginDocumentSettingPanel
            name="ept-validator-panel"
            title={__('Italian SEO Validator', 'ept-validator')}
            className="ept-validator-sidebar"
        >
            <PanelRow>
                <div className="ept-sidebar-content">
                    {/* Info versione Lite */}
                    <div className="ept-info-box">
                        <p className="ept-info-text">
                            <strong>Versione Lite</strong>
                            <br />
                            Validazioni disponibili: <strong>{usageRemaining !== null ? usageRemaining : '...'}/3 al mese</strong>
                        </p>
                    </div>

                    {/* Bottone validazione */}
                    <Button
                        variant="primary"
                        onClick={handleValidate}
                        disabled={isValidating || !postContent || isLoadingSaved}
                        className="ept-validate-button"
                    >
                        {isValidating ? (
                            <>
                                <Spinner />
                                {__('Validazione in corso...', 'ept-validator')}
                            </>
                        ) : isLoadingSaved ? (
                            <>
                                <Spinner />
                                {__('Caricamento...', 'ept-validator')}
                            </>
                        ) : (
                            __('Valida Contenuto', 'ept-validator')
                        )}
                    </Button>

                    {/* Messaggio errore */}
                    {error && (
                        <Notice status="error" isDismissible={false}>
                            <p>{error}</p>
                            {error.includes('limite') && (
                                <p>
                                    <a href="/wp-admin/admin.php?page=ept-validator-settings">
                                        Passa a Pro per validazioni illimitate
                                    </a>
                                </p>
                            )}
                        </Notice>
                    )}

                    {/* Risultati validazione */}
                    {validationResult && (
                        <div className="ept-results">
                            {/* 💾 Badge età validazione salvata */}
                            {savedValidationAge !== null && savedValidationAge > 0 && (
                                <Notice status="info" isDismissible={false} className="ept-saved-notice">
                                    <div>
                                        <strong>ℹ️ Validazione salvata</strong>
                                        <p style={{ fontSize: '12px', marginTop: '4px', marginBottom: 0 }}>
                                            Eseguita {savedValidationAge === 0 ? 'oggi' : `${savedValidationAge} giorn${savedValidationAge > 1 ? 'i' : 'o'} fa`}
                                        </p>
                                    </div>
                                </Notice>
                            )}
                            
                            <Notice status="success" isDismissible={false}>
                                <strong>âœ“ Validazione completata</strong>
                            </Notice>

                            {/* Punteggio Gulpease */}
                            <div className="ept-result-card">
                                <div className="ept-result-header">
                                    <span className="ept-result-label">LeggibilitÃ  (Gulpease)</span>
                                    <span className={`ept-score-badge ${getScoreBadgeClass(validationResult.gulpease_score)}`}>
                                        {validationResult.gulpease_score.toFixed(1)}
                                    </span>
                                </div>
                                <p className="ept-result-description">
                                    {getReadabilityLabel(validationResult.gulpease_score)}
                                </p>
                            </div>

                            {/* Statistiche testo */}
                            <div className="ept-result-card">
                                <h4 className="ept-result-title">Statistiche</h4>
                                <ul className="ept-stats-list">
                                    <li>Parole: <strong>{validationResult.word_count}</strong></li>
                                    <li>Frasi: <strong>{validationResult.sentence_count}</strong></li>
                                    <li>Lettere: <strong>{validationResult.letter_count}</strong></li>
                                </ul>
                            </div>

                            {/* Controlli struttura */}
                            <div className="ept-result-card">
                                <h4 className="ept-result-title">Struttura</h4>
                                <ul className="ept-checks-list">
                                    <li className={validationResult.structure_checks.has_title ? 'check-pass' : 'check-fail'}>
                                        {validationResult.structure_checks.has_title ? 'âœ“' : 'âœ—'} Titolo presente
                                    </li>
                                    <li className={validationResult.structure_checks.has_paragraphs ? 'check-pass' : 'check-fail'}>
                                        {validationResult.structure_checks.has_paragraphs ? 'âœ“' : 'âœ—'} Paragrafi formattati
                                    </li>
                                </ul>
                            </div>

                            {/* Warnings */}
                            {validationResult.warnings && validationResult.warnings.length > 0 && (
                                <div className="ept-warnings">
                                    <h4 className="ept-warnings-title">âš ï¸ Avvisi</h4>
                                    <ul className="ept-warnings-list">
                                        {validationResult.warnings.map((warning, index) => (
                                            <li key={index}>{warning}</li>
                                        ))}
                                    </ul>
                                </div>
                            )}

                            {/* CTA Pro */}
                            <div className="ept-pro-cta">
                                <p>ðŸš€ <strong>Passa a Pro</strong> per:</p>
                                <ul>
                                    <li>Validazioni illimitate</li>
                                    <li>Analisi avanzata (SEO, EAT)</li>
                                    <li>Suggerimenti automatici</li>
                                </ul>
                                <Button
                                    variant="secondary"
                                    href="/wp-admin/admin.php?page=ept-validator-settings"
                                    target="_self"
                                >
                                    Scopri di piÃ¹
                                </Button>
                            </div>
                        </div>
                    )}
                </div>
            </PanelRow>
        </PluginDocumentSettingPanel>
    );
};

// Registra il plugin nella sidebar
registerPlugin('ept-validator', {
    render: ItalianSEOValidatorSidebar
});