import { useState, useRef, useEffect, useCallback } from "react";

// ── TYPES ──────────────────────────────────────────────
interface Contact {
    label: string;
    email: string;
    desc: string;
    icon: string;
    color: string;
    bg: string;
    border: string;
}

interface Message {
    id: string | number;
    role: "user" | "assistant";
    content: string;
    showContacts?: boolean;
    topic?: string | null;
    score?: number;
    followUps?: string[];
}

interface FeedbackEntry {
    msgId: string | number;
    type: "up" | "down";
    content: string;
    timestamp: number;
}

interface QuestionEntry {
    question: string;
    timestamp: number;
}

// ── CONFIG ─────────────────────────────────────────────
const CONTACTS: Contact[] = [
    {
        label: "Service Finance",
        email: "servicesgeneraux-sqy@ensup.eu",
        desc: "Questions sur un paiement, justificatif, vérification",
        icon: "💶", color: "#15803d", bg: "#f0fdf4", border: "#86efac",
    },
    {
        label: "Support informatique",
        email: "support@ensup.eu",
        desc: "Connexion, compte bloqué",
        icon: "💻", color: "#0369a1", bg: "#f0f9ff", border: "#bae6fd",
    },
];

const QUICK_QUESTIONS: string[] = [
    "Comment soumettre une note ?",
    "Ajouter un justificatif sur mobile",
    "Ma note a été refusée",
    "Configurer mon IBAN",
    "Calculer mes frais km",
    "Contacter le support",
];

// ── BASE DE CONNAISSANCES ENRICHIE ─────────────────────
interface KnowledgeEntry {
    id: string;
    keywords: string[];
    answer: string;
    showContacts?: boolean;
    topic: string;
    followUps: string[];
}

const KNOWLEDGE_BASE: KnowledgeEntry[] = [
    {
        id: "soumettre",
        keywords: ["soumettre", "créer", "nouvelle note", "comment soumettre", "envoyer", "nouvelle", "creer"],
        answer: "Pour soumettre une note de frais :\n1. Clique sur **Nouvelle note** dans le menu\n2. Renseigne le libellé global\n3. Ajoute tes dépenses ligne par ligne (date, catégorie, montant, justificatif)\n4. Clique sur **Soumettre**\n\n⚠️ Prérequis : IBAN + BIC + adresse complète dans Mon profil.",
        topic: "soumission",
        followUps: ["Configurer mon IBAN", "Ajouter un justificatif sur mobile", "Quel statut après soumission ?"],
    },
    {
        id: "justificatif",
        keywords: ["justificatif", "photo", "mobile", "qr", "qr code", "scanner", "telephone", "téléphone", "ajouter justificatif"],
        answer: "Pour ajouter un justificatif sur mobile :\n1. Dans le formulaire, clique sur **Générer QR Code** sur la ligne concernée\n2. Scanne le QR avec l'appareil photo natif de ton téléphone\n3. Prends la photo du justificatif\n4. Il est associé automatiquement ✅\n\nLe QR Code est valable **24h**. Utilise bien l'appli photo native (pas une app tierce).",
        topic: "justificatif",
        followUps: ["QR Code expiré que faire ?", "Justificatif en PDF ?", "Soumettre ma note"],
    },
    {
        id: "refusee",
        keywords: ["refusée", "refus", "refusé", "motif", "corriger", "correction", "resoumettre", "rejetee", "rejetée"],
        answer: "Si ta note est refusée :\n1. Ouvre-la dans **Mes notes**\n2. Lis le motif de refus (affiché en rouge)\n3. Clique sur **✏️ Corriger et resoumettre**\n4. Corrige les informations demandées\n5. Resoumets\n\nLa note repart au début du circuit de validation.",
        topic: "refus",
        followUps: ["Qui valide ma note ?", "Délai de re-soumission ?", "Contacter le support"],
    },
    {
        id: "iban",
        keywords: ["iban", "bic", "coordonnées bancaires", "bancaire", "banque", "virement", "configurer iban", "rib"],
        answer: "Pour configurer ton IBAN :\n1. Va dans **Mon profil** (menu gauche)\n2. Section **RIB / Coordonnées bancaires**\n3. Clique sur **Saisir mon IBAN**\n4. Entre ton IBAN (ex: FR76...) et ton BIC (ex: BNPAFRPP)\n5. Clique sur **Enregistrer**\n\n⚠️ IBAN et BIC sont obligatoires pour soumettre une note.",
        topic: "iban",
        followUps: ["Changer mon IBAN", "Virement non reçu ?", "Comment soumettre une note ?"],
    },
    {
        id: "km",
        keywords: ["km", "kilométrique", "kilomètre", "voiture", "véhicule", "barème", "indemnité", "kilometrique", "kilom"],
        answer: "Pour les frais kilométriques :\n- Sélectionne la catégorie **Kilométrique** dans ta dépense\n- Saisis le nombre de km\n- Le montant est calculé automatiquement selon le barème fiscal :\n  - 3 CV : 0,529 €/km\n  - 5 CV : 0,636 €/km\n  - 7 CV+ : 0,697 €/km\n\nConfigure ton véhicule dans **Mon profil → Véhicule personnel** pour un calcul automatique.",
        topic: "kilometrique",
        followUps: ["Ajouter ma carte grise", "Plusieurs trajets en une note ?", "Ajouter un justificatif sur mobile"],
    },
    {
        id: "support",
        keywords: ["support", "contact", "aide", "problème", "bug", "erreur", "contacter", "help", "assistance"],
        answer: "Voici les contacts disponibles selon ton besoin :",
        showContacts: true,
        topic: "support",
        followUps: ["Problème de connexion ?", "Compte bloqué ?"],
    },
    {
        id: "statut",
        keywords: ["statut", "état", "où en est", "validation", "validé", "approuvé", "payée", "circuit", "en attente", "valide"],
        answer: "Le circuit de validation d'une note :\n1. **En attente** → validation N1 en cours\n2. **Validé N1** → approuvé par le manager\n3. **Validé N2** → second niveau validé\n4. **Approuvé** → validé hiérarchiquement\n5. **Vérifié** → contrôle Finance OK\n6. **Paiement en attente** → XML SEPA généré\n7. **Payée** → remboursement effectué 💶",
        topic: "statut",
        followUps: ["Délai moyen de remboursement ?", "Note bloquée en validation ?", "Contacter le support"],
    },
    {
        id: "paiement",
        keywords: ["paiement", "remboursement", "payé", "quand", "délai", "virement", "non reçu", "pas reçu"],
        answer: "Si tu n'as pas reçu ton remboursement :\n1. Vérifie que le statut est bien **Payée** dans Mes notes\n2. Vérifie ton IBAN dans Mon profil\n3. Si tout est correct, contacte la Finance avec la référence de ta note.\n\nLe paiement est effectué par virement SEPA après confirmation par la Finance.",
        topic: "paiement",
        followUps: ["Vérifier mon IBAN", "Contacter le support", "Délai bancaire SEPA ?"],
    },
    {
        id: "adresse",
        keywords: ["adresse", "postale", "profil", "rue", "ville", "code postal", "modifier adresse"],
        answer: "Pour renseigner ton adresse postale :\n1. Va dans **Mon profil**\n2. Section **Adresse postale**\n3. Clique sur **Modifier**\n4. Remplis rue, code postal, ville, pays\n5. Clique sur **Enregistrer**\n\n⚠️ L'adresse complète est obligatoire pour soumettre une note.",
        topic: "profil",
        followUps: ["Comment soumettre une note ?", "Configurer mon IBAN"],
    },
    {
        id: "brouillon",
        keywords: ["brouillon", "sauvegarder", "sauvegarde", "automatique", "perdre"],
        answer: "Les brouillons sont sauvegardés **automatiquement toutes les 3 secondes** pendant que tu saisis ta note.\n\nPour retrouver un brouillon :\n- Clique sur **Nouvelle note**\n- Tes brouillons apparaissent en haut du formulaire\n- Clique sur l'un d'eux pour le reprendre.",
        topic: "soumission",
        followUps: ["Comment soumettre une note ?", "Ajouter un justificatif sur mobile"],
    },
    {
        id: "documents",
        keywords: ["document", "carte grise", "permis", "rib", "valider", "finance"],
        answer: "Les documents obligatoires dans Mon profil :\n- **RIB** : ton IBAN + BIC (obligatoire pour tout remboursement)\n- **Carte grise** : obligatoire pour les notes kilométriques\n- **Permis de conduire** : obligatoire pour les notes kilométriques\n\nCes documents sont soumis à validation par la Finance. Upload dans **Mon profil → Documents**.",
        topic: "profil",
        followUps: ["Configurer mon IBAN", "Calculer mes frais km"],
    },
    {
        id: "tva",
        keywords: ["tva", "taxe", "hors taxe", "ht", "ttc"],
        answer: "Pour la TVA dans tes dépenses :\n- Sélectionne le **taux de TVA** correspondant à ta dépense (0%, 5,5%, 10%, 20%)\n- Le montant HT est calculé automatiquement\n- Si pas de TVA (ex: frais kilométriques), laisse vide\n\nLes taux disponibles sont configurés par la Finance.",
        topic: "depenses",
        followUps: ["Calculer mes frais km", "Frais de repas plafond ?"],
    },
    {
        id: "repas",
        keywords: ["repas", "restaurant", "plafond", "25", "nourriture", "déjeuner", "dîner", "dejeuner", "diner"],
        answer: "Pour les frais de repas :\n- Catégorie : **Repas / Restaurant**\n- Plafond appliqué par la Finance : **25 € par personne**\n- Si ton repas dépasse ce plafond, le montant sera proratisé automatiquement\n- Indique le nombre de participants si c'est un repas d'équipe.",
        topic: "depenses",
        followUps: ["Ajouter le justificatif restaurant", "Plafond hôtel ?", "Comment soumettre une note ?"],
    },
    {
        id: "hotel",
        keywords: ["hébergement", "hotel", "hôtel", "nuit", "nuits", "hebergement"],
        answer: "Pour les frais d'hébergement :\n- Catégorie : **Hébergement / Hôtel**\n- Indique le **nombre de nuits** dans le champ prévu\n- Joins la facture de l'hôtel comme justificatif\n- Le montant par nuit est calculé automatiquement.",
        topic: "depenses",
        followUps: ["Ajouter la facture hôtel", "Frais de repas plafond ?", "Comment soumettre une note ?"],
    },
];

// ── RÉPONSES SOCIALES ──────────────────────────────────
interface SocialEntry {
    patterns: string[];
    responses: string[];
}

const SOCIAL_RESPONSES: SocialEntry[] = [
    {
        patterns: ["merci", "merc", "thanks", "thank you", "super merci", "mercii"],
        responses: [
            "Avec plaisir 😊",
            "Je t'en prie !",
            "Avec plaisir. Si tu veux, je peux aussi t'aider sur les justificatifs, l'IBAN ou les remboursements.",
            "Pas de souci 😊",
        ],
    },
    {
        patterns: ["bonjour", "salut", "hello", "bonsoir", "coucou"],
        responses: [
            "Bonjour 👋 Comment puis-je t'aider sur la note de frais ?",
            "Salut 👋 Je suis là pour t'aider sur la plateforme NDF.",
            "Bonjour ! Tu peux me poser une question sur les justificatifs, le remboursement, l'IBAN ou le statut d'une note.",
        ],
    },
    {
        patterns: ["au revoir", "bye", "a bientot", "à bientot", "bonne journée", "bonne journee"],
        responses: ["À bientôt 👋", "Bonne journée 😊", "À bientôt, et bon courage pour ta note de frais !"],
    },
    {
        patterns: ["ok", "d accord", "dac", "ça marche", "ca marche", "parfait"],
        responses: ["Parfait 👍", "Très bien 😊", "D'accord, je reste là si besoin."],
    },
];

// ── UTILITAIRES ────────────────────────────────────────
function normalizeText(input: string): string {
    return input
        .toLowerCase()
        .normalize("NFD")
        .replace(/[\u0300-\u036f]/g, "")
        .replace(/[^a-z0-9\s]/g, " ")
        .replace(/\s+/g, " ")
        .trim();
}

function pickRandom<T>(arr: T[]): T {
    return arr[Math.floor(Math.random() * arr.length)];
}

// ── FUZZY MATCHING (distance de Levenshtein) ───────────
function levenshtein(a: string, b: string): number {
    const m = a.length, n = b.length;
    const dp: number[][] = Array.from({ length: m + 1 }, (_, i) =>
        Array.from({ length: n + 1 }, (__, j) => (i === 0 ? j : j === 0 ? i : 0))
    );
    for (let i = 1; i <= m; i++)
        for (let j = 1; j <= n; j++)
            dp[i][j] = a[i - 1] === b[j - 1]
                ? dp[i - 1][j - 1]
                : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
    return dp[m][n];
}

function fuzzyScore(inputNorm: string, keyword: string): number {
    const normKw = normalizeText(keyword);
    // Correspondance exacte (pondérée par longueur)
    if (inputNorm.includes(normKw)) return normKw.split(" ").length * 3;
    // Début de mot (min 4 chars)
    if (inputNorm.split(" ").some((w) => w.startsWith(normKw) && normKw.length >= 4)) return 2;
    // Fuzzy tolérant aux fautes de frappe
    const words = inputNorm.split(" ");
    const kwWords = normKw.split(" ");
    let score = 0;
    for (const kw of kwWords) {
        if (kw.length < 4) continue;
        const tolerance = kw.length <= 5 ? 1 : 2;
        if (words.some((w) => levenshtein(w, kw) <= tolerance)) score += 1.5;
    }
    return score;
}

// ── MOTEUR DE RÉPONSE ──────────────────────────────────
interface BotResponse {
    answer: string;
    showContacts?: boolean;
    topic?: string | null;
    score?: number;
    followUps?: string[];
}

function getBotResponse(input: string, conversationHistory: Message[]): BotResponse {
    const normalized = normalizeText(input);

    // 1) Réponses sociales
    for (const social of SOCIAL_RESPONSES) {
        if (social.patterns.some((p) => normalized.includes(normalizeText(p)))) {
            return { answer: pickRandom(social.responses), topic: null, score: 10, followUps: QUICK_QUESTIONS.slice(0, 3) };
        }
    }

    // 2) Contexte : sujet du dernier échange
    const lastTopic = [...conversationHistory].reverse().find((h) => h.topic)?.topic ?? null;

    // 3) Scoring fuzzy sur toute la KB
    let bestMatch: KnowledgeEntry | null = null;
    let bestScore = 0;

    for (const entry of KNOWLEDGE_BASE) {
        let score = 0;
        for (const kw of entry.keywords) {
            score += fuzzyScore(normalized, kw);
        }
        // Bonus contextuel : sujet précédent lié
        if (lastTopic && entry.topic === lastTopic) score += 0.5;

        if (score > bestScore) {
            bestScore = score;
            bestMatch = entry;
        }
    }

    if (bestMatch && bestScore >= 1.5) {
        return {
            answer: bestMatch.answer,
            showContacts: bestMatch.showContacts,
            topic: bestMatch.topic,
            score: bestScore,
            followUps: bestMatch.followUps,
        };
    }

    // 4) Réponse par défaut
    return {
        answer:
            "Je n'ai pas bien compris ta question 😅\n\nJe peux t'aider sur :\n- Soumettre une note\n- Ajouter un justificatif\n- Frais kilométriques\n- Configurer l'IBAN\n- Suivre le statut d'une note\n- Contacter le support\n\nTu peux reformuler avec une phrase simple.",
        topic: null,
        score: 0,
        followUps: QUICK_QUESTIONS,
    };
}

// ── CONTACT CARDS ──────────────────────────────────────
function ContactCards() {
    return (
        <div style={{ display: "flex", flexDirection: "column", gap: 7, marginTop: 7 }}>
            {CONTACTS.map((c) => (
                <a
                    key={c.email}
                    href={`mailto:${c.email}`}
                    style={{
                        display: "flex", alignItems: "center", gap: 10,
                        padding: "9px 12px",
                        background: c.bg, border: `1.5px solid ${c.border}`,
                        borderRadius: 10, textDecoration: "none", transition: "transform 0.15s",
                    }}
                    onMouseEnter={(e) => (e.currentTarget.style.transform = "translateY(-1px)")}
                    onMouseLeave={(e) => (e.currentTarget.style.transform = "none")}
                >
                    <span style={{ fontSize: 18, flexShrink: 0 }}>{c.icon}</span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 11, fontWeight: 700, color: c.color }}>{c.label}</div>
                        <div style={{ fontSize: 10, color: "#64748b", marginTop: 1 }}>{c.desc}</div>
                    </div>
                    <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 2, flexShrink: 0 }}>
                        <span style={{ fontSize: 10, fontWeight: 700, color: c.color, background: "rgba(255,255,255,0.7)", padding: "2px 7px", borderRadius: 20 }}>
                            ✉ Écrire
                        </span>
                        <span style={{ fontSize: 9, color: "#94a3b8", fontFamily: "monospace" }}>{c.email}</span>
                    </div>
                </a>
            ))}
        </div>
    );
}

// ── RENDU MARKDOWN ─────────────────────────────────────
function renderContent(text: string): React.ReactNode[] {
    return text.split("\n").map((line, i) => {
        if (!line.trim()) return <span key={i} style={{ display: "block", height: 4 }} />;

        const parseBold = (str: string): React.ReactNode[] =>
            str.split(/\*\*(.*?)\*\*/g).map((part, j) =>
                j % 2 === 1 ? <strong key={j}>{part}</strong> : part
            );

        const isBullet = line.startsWith("- ");
        const isNum = /^\d+\. /.test(line);

        if (isBullet || isNum) {
            const content = line.replace(/^- /, "").replace(/^\d+\. /, "");
            return (
                <div key={i} style={{ display: "flex", gap: 5, margin: "1px 0", alignItems: "flex-start" }}>
                    <span style={{ flexShrink: 0, opacity: 0.55, marginTop: 1, fontSize: 11 }}>
                        {isBullet ? "•" : line.match(/^(\d+)\./)?.[1] + "."}
                    </span>
                    <span>{parseBold(content)}</span>
                </div>
            );
        }
        return (
            <p key={i} style={{ margin: "2px 0", lineHeight: 1.55 }}>
                {parseBold(line)}
            </p>
        );
    });
}

// ── FEEDBACK BUTTON ────────────────────────────────────
interface FeedbackRowProps {
    msgId: string | number;
    content: string;
    onNegative: () => void;
}

function FeedbackRow({ msgId, content, onNegative }: FeedbackRowProps) {
    const [voted, setVoted] = useState<"up" | "down" | null>(null);

    const handleVote = (type: "up" | "down") => {
        if (voted) return;
        setVoted(type);
        // Persistance locale
        const stored: FeedbackEntry[] = JSON.parse(localStorage.getItem("ndf_feedback") || "[]");
        stored.push({ msgId, type, content, timestamp: Date.now() });
        localStorage.setItem("ndf_feedback", JSON.stringify(stored.slice(-50)));
        if (type === "down") onNegative();
    };

    return (
        <div style={{ display: "flex", gap: 5, marginTop: 8, alignItems: "center" }}>
            {voted === null ? (
                <>
                    <button
                        onClick={() => handleVote("up")}
                        style={{
                            background: "none", border: "1.5px solid #e2e8f0", borderRadius: 20,
                            padding: "2px 8px", fontSize: 13, cursor: "pointer", color: "#94a3b8",
                            transition: "all 0.15s", fontFamily: "inherit",
                        }}
                        onMouseEnter={(e) => { e.currentTarget.style.borderColor = "#22c55e"; e.currentTarget.style.color = "#16a34a"; }}
                        onMouseLeave={(e) => { e.currentTarget.style.borderColor = "#e2e8f0"; e.currentTarget.style.color = "#94a3b8"; }}
                    >👍</button>
                    <button
                        onClick={() => handleVote("down")}
                        style={{
                            background: "none", border: "1.5px solid #e2e8f0", borderRadius: 20,
                            padding: "2px 8px", fontSize: 13, cursor: "pointer", color: "#94a3b8",
                            transition: "all 0.15s", fontFamily: "inherit",
                        }}
                        onMouseEnter={(e) => { e.currentTarget.style.borderColor = "#ef4444"; e.currentTarget.style.color = "#dc2626"; }}
                        onMouseLeave={(e) => { e.currentTarget.style.borderColor = "#e2e8f0"; e.currentTarget.style.color = "#94a3b8"; }}
                    >👎</button>
                    <span style={{ fontSize: 10, color: "#94a3b8" }}>Utile ?</span>
                </>
            ) : (
                <span style={{ fontSize: 10.5, color: voted === "up" ? "#16a34a" : "#dc2626" }}>
                    {voted === "up" ? "Merci 😊" : "Noté, on va améliorer ça !"}
                </span>
            )}
        </div>
    );
}

// ── BARRE DE CONFIANCE ─────────────────────────────────


// ── MESSAGE BUBBLE ─────────────────────────────────────
interface MessageBubbleProps {
    msg: Message;
    onNegativeFeedback: (msg: Message) => void;
}

function MessageBubble({ msg, onNegativeFeedback }: MessageBubbleProps) {
    const isBot = msg.role === "assistant";
    return (
        <div style={{
            display: "flex", flexDirection: isBot ? "row" : "row-reverse",
            gap: 8, alignItems: "flex-end", marginBottom: 10,
            animation: "ndfFade 0.2s ease",
        }}>
           {isBot && (
                <img
                    src="/img/emma-avatar.jpg"
                    alt="Emma"
                    style={{ width: 26, height: 26, borderRadius: "50%", objectFit: "cover", flexShrink: 0 }}
                />
            )}
            <div style={{ maxWidth: "83%" }}>
                <div style={{
                    padding: "9px 13px",
                    borderRadius: isBot ? "4px 13px 13px 13px" : "13px 4px 13px 13px",
                    background: isBot ? "var(--bg-card,#fff)" : "linear-gradient(135deg,#6366f1,#4f46e5)",
                    border: isBot ? "1.5px solid var(--border-card,#e2e8f0)" : "none",
                    color: isBot ? "var(--text-primary,#1e293b)" : "#fff",
                    fontSize: 12.5,
                    boxShadow: isBot ? "0 1px 4px rgba(0,0,0,0.06)" : "0 4px 14px rgba(99,102,241,0.3)",
                }}>
                    {renderContent(msg.content)}
                    {msg.showContacts && <ContactCards />}
                </div>
                {/* Feedback + barre confiance uniquement sur les messages bot */}
                {isBot && msg.id !== "welcome" && (
                    <div style={{ paddingLeft: 2 }}>
                   
                        <FeedbackRow
                            msgId={msg.id}
                            content={msg.content}
                            onNegative={() => onNegativeFeedback(msg)}
                        />
                    </div>
                )}
            </div>
        </div>
    );
}

// ── TYPING INDICATOR ───────────────────────────────────
function TypingIndicator() {
    return (
        <div style={{ display: "flex", gap: 8, alignItems: "flex-end", marginBottom: 10 }}>
           <img
                src="/img/emma-avatar.png"
                alt="Emma"
                style={{ width: 26, height: 26, borderRadius: "50%", objectFit: "cover", flexShrink: 0 }}
            />
            <div style={{
                padding: "11px 15px",
                background: "var(--bg-card,#fff)",
                border: "1.5px solid var(--border-card,#e2e8f0)",
                borderRadius: "4px 13px 13px 13px",
                display: "flex", gap: 4, alignItems: "center",
            }}>
                {[0, 1, 2].map((i) => (
                    <div key={i} style={{
                        width: 5, height: 5, borderRadius: "50%", background: "#6366f1",
                        animation: `ndfBounce 1.2s ease-in-out ${i * 0.2}s infinite`,
                    }} />
                ))}
            </div>
        </div>
    );
}

// ── MEMORY BADGE ───────────────────────────────────────
function MemoryBadge({ topics }: { topics: string[] }) {
    if (topics.length === 0) return null;
    return (
        <div style={{
            margin: "6px 13px 0",
            padding: "4px 10px",
            background: "#eef2ff", border: "1px solid #c7d2fe",
            borderRadius: 8, fontSize: 10, color: "#4f46e5",
            display: "flex", alignItems: "center", gap: 5,
            animation: "ndfFade 0.3s ease",
        }}>
            🧠 <span>Contexte : <strong>{topics.slice(-2).join(" → ")}</strong></span>
        </div>
    );
}

// ── SUGGESTIONS DYNAMIQUES ─────────────────────────────
interface SuggestionsBarProps {
    suggestions: string[];
    label: string;
    onSelect: (q: string) => void;
    disabled: boolean;
}

function SuggestionsBar({ suggestions, label, onSelect, disabled }: SuggestionsBarProps) {
    return (
        <div style={{ padding: "4px 13px 10px" }}>
            {label && (
                <div style={{ fontSize: 9.5, color: "#94a3b8", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 4 }}>
                    {label}
                </div>
            )}
            <div style={{ display: "flex", flexWrap: "wrap", gap: 5 }}>
                {suggestions.map((q, i) => (
                    <button
                        key={q}
                        className="ndf-quick"
                        onClick={() => onSelect(q)}
                        disabled={disabled}
                        style={{
                            padding: "4px 9px",
                            background: "var(--bg-card,#fff)",
                            border: "1.5px solid var(--border-card,#e2e8f0)",
                            borderRadius: 20, cursor: "pointer",
                            fontSize: 10.5, fontWeight: 600,
                            color: "var(--text-secondary,#64748b)",
                            fontFamily: "inherit", transition: "all 0.15s",
                            animation: `ndfFade 0.2s ease ${i * 0.05}s both`,
                        }}
                    >{q}</button>
                ))}
            </div>
        </div>
    );
}

// ── COMPOSANT PRINCIPAL ────────────────────────────────
export default function NDFChatbot() {
    const [open, setOpen] = useState<boolean>(false);
    const [showWelcomeBubble, setShowWelcomeBubble] = useState<boolean>(true);
    const [displayMsgs, setDisplayMsgs] = useState<Message[]>([
        {
            id: "welcome",
            role: "assistant",
            content: "Bonjour ! 👋 Je suis Emma l'assistante NDF d'ENSUP Group.\n\nJe peux répondre à tes questions sur la plateforme : soumission, justificatifs, validations, remboursements, profil...\n\nComment puis-je t'aider ?",
            topic: null,
        },
    ]);
    const [currentSuggestions, setCurrentSuggestions] = useState<string[]>(QUICK_QUESTIONS);
    const [suggestionsLabel, setSuggestionsLabel] = useState<string>("Questions fréquentes");
    const [input, setInput] = useState<string>("");
    const [loading, setLoading] = useState<boolean>(false);
    const [hasNotif, setHasNotif] = useState<boolean>(true);
    const bottomRef = useRef<HTMLDivElement>(null);
    const inputRef = useRef<HTMLInputElement>(null);

    // Sujets uniques de la conversation pour le badge mémoire
    const conversationTopics = displayMsgs
        .filter((m) => m.topic)
        .map((m) => m.topic as string)
        .filter((v, i, a) => a.indexOf(v) === i);

    useEffect(() => {
        bottomRef.current?.scrollIntoView({ behavior: "smooth" });
    }, [displayMsgs, loading, open]);

    useEffect(() => {
        if (open) {
            setHasNotif(false);
            setTimeout(() => inputRef.current?.focus(), 120);
        }
    }, [open]);

    useEffect(() => {
        if (!open && showWelcomeBubble) {
            const timer = setTimeout(() => setShowWelcomeBubble(false), 6000);
            return () => clearTimeout(timer);
        }
    }, [open, showWelcomeBubble]);

    useEffect(() => {
        if (open) setShowWelcomeBubble(false);
    }, [open]);

    // Réponse au feedback négatif
    const handleNegativeFeedback = useCallback((originalMsg: Message) => {
        setTimeout(() => {
            setDisplayMsgs((prev) => [...prev, {
                id: Date.now(),
                role: "assistant",
                content: "Désolé que cette réponse ne t'ait pas aidé 😕\n\nTu peux :\n- **Reformuler** ta question différemment\n- Contacter directement le **support**\n\nQue cherchais-tu exactement ?",
                topic: originalMsg.topic,
                score: undefined,
            }]);
            setCurrentSuggestions(["Contacter le support", ...QUICK_QUESTIONS.slice(0, 3)]);
            setSuggestionsLabel("Que faire ?");
        }, 400);
    }, []);

    const sendMessage = useCallback((text: string) => {
        const userContent = text.trim();
        if (!userContent || loading) return;

        // Log de la question en localStorage
        const qLog: QuestionEntry[] = JSON.parse(localStorage.getItem("ndf_questions") || "[]");
        qLog.push({ question: userContent, timestamp: Date.now() });
        localStorage.setItem("ndf_questions", JSON.stringify(qLog.slice(-100)));

        setDisplayMsgs((prev) => [...prev, { id: Date.now(), role: "user", content: userContent }]);
        setInput("");
        setLoading(true);
        setCurrentSuggestions([]);

        setTimeout(() => {
            setDisplayMsgs((prev) => {
                const { answer, showContacts, topic, score, followUps } = getBotResponse(userContent, prev);
                const newMsg: Message = {
                    id: Date.now() + 1,
                    role: "assistant",
                    content: answer,
                    showContacts,
                    topic,
                    score,
                    followUps,
                };
                // Mettre à jour suggestions après le message
                setTimeout(() => {
                    if (followUps && followUps.length > 0) {
                        setCurrentSuggestions(followUps);
                        setSuggestionsLabel("Questions liées 💡");
                    } else {
                        setCurrentSuggestions(QUICK_QUESTIONS.slice(0, 4));
                        setSuggestionsLabel("Tu peux aussi me demander…");
                    }
                }, 50);
                return [...prev, newMsg];
            });
            setLoading(false);
        }, 600 + Math.random() * 300);
    }, [loading]);

    const resetConversation = () => {
        setDisplayMsgs([{
            id: "reset-" + Date.now(),
            role: "assistant",
            content: "Conversation réinitialisée 🔄\n\nComment puis-je t'aider ?",
            topic: null,
        }]);
        setCurrentSuggestions(QUICK_QUESTIONS);
        setSuggestionsLabel("Questions fréquentes");
    };

    return (
        <>
            <style>{`
        @keyframes ndfFade { from{opacity:0;transform:translateY(5px)}to{opacity:1;transform:none} }
        @keyframes ndfBounce { 0%,80%,100%{transform:translateY(0)}40%{transform:translateY(-4px)} }
        @keyframes ndfSlideUp { from{opacity:0;transform:translateY(14px) scale(0.98)}to{opacity:1;transform:none} }
        @keyframes ndfPulse { 0%,100%{box-shadow:0 6px 20px rgba(99,102,241,0.4)}50%{box-shadow:0 6px 28px rgba(99,102,241,0.65)} }
        .ndf-quick:hover{background:#eef2ff!important;border-color:#6366f1!important;color:#4f46e5!important}
        .ndf-inp:focus{border-color:#6366f1!important;box-shadow:0 0 0 3px rgba(99,102,241,0.12)!important;outline:none}
        .ndf-send:hover:not(:disabled){background:#4f46e5!important}
        .ndf-send:disabled{opacity:0.4!important;cursor:not-allowed!important}
        .ndf-scroll::-webkit-scrollbar{width:4px}
        .ndf-scroll::-webkit-scrollbar-track{background:transparent}
        .ndf-scroll::-webkit-scrollbar-thumb{background:#c7d2fe;border-radius:4px}
      `}</style>

            {/* ── BULLE DE BIENVENUE ── */}
            {showWelcomeBubble && !open && (
                <div style={{
                    position: "fixed", bottom: 92, right: 28, maxWidth: 250,
                    background: "#ffffff", color: "#1e293b", border: "1px solid #e2e8f0",
                    borderRadius: 14, padding: "10px 12px",
                    boxShadow: "0 10px 30px rgba(0,0,0,0.12)",
                    zIndex: 9999, animation: "ndfSlideUp 0.25s ease",
                }}>
                    <button
                        onClick={() => setShowWelcomeBubble(false)}
                        aria-label="Fermer le message d'accueil"
                        style={{
                            position: "absolute", top: 6, right: 6,
                            width: 20, height: 20, border: "none", background: "transparent",
                            cursor: "pointer", color: "#94a3b8", fontSize: 12, lineHeight: 1,
                        }}
                    >✕</button>
                    <div style={{ fontSize: 12.5, fontWeight: 700, marginBottom: 4, color: "#4f46e5" }}>Hello 👋</div>
                    <div style={{ fontSize: 11.5, lineHeight: 1.45, paddingRight: 12 }}>
                        Je suis <strong>Emma</strong>, je peux t'aider si besoin.
                    </div>
                    <div style={{
                        position: "absolute", bottom: -8, right: 18,
                        width: 14, height: 14, background: "#ffffff",
                        borderRight: "1px solid #e2e8f0", borderBottom: "1px solid #e2e8f0",
                        transform: "rotate(45deg)",
                    }} />
                </div>
            )}

            {/* ── BOUTON FLOTTANT ── */}
            <button
                onClick={() => setOpen((o) => !o)}
                aria-label="Ouvrir l'assistant NDF"
                style={{
                    position: "fixed", bottom: 28, right: 28,
                    width: 52, height: 52, borderRadius: "50%",
                    background: open
                        ? "linear-gradient(135deg,#6b7280,#4b5563)"
                        : "linear-gradient(135deg,#6366f1,#4f46e5)",
                    border: "none", cursor: "pointer",
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontSize: 21, color: "#fff",
                    animation: !open ? "ndfPulse 2.8s ease-in-out infinite" : "none",
                    zIndex: 9999, transition: "background 0.2s",
                }}
            >
                {open ? "✕" : "💬"}
                {hasNotif && !open && (
                    <span style={{
                        position: "absolute", top: 2, right: 2,
                        width: 11, height: 11, background: "#ef4444",
                        borderRadius: "50%", border: "2px solid white",
                    }} />
                )}
            </button>

            {/* ── FENÊTRE CHAT ── */}
            {open && (
                <div style={{
                    position: "fixed", bottom: 90, right: 28,
                    width: 352, maxHeight: "76vh",
                    background: "var(--bg-app,#f8fafc)", borderRadius: 18,
                    boxShadow: "0 20px 60px rgba(0,0,0,0.18)",
                    border: "1px solid var(--border-card,#e2e8f0)",
                    display: "flex", flexDirection: "column",
                    zIndex: 9998, overflow: "hidden",
                    animation: "ndfSlideUp 0.22s ease",
                }}>

                    {/* HEADER */}
                    <div style={{
                        background: "linear-gradient(135deg,#6366f1,#4f46e5)",
                        padding: "13px 16px",
                        display: "flex", alignItems: "center", gap: 10, flexShrink: 0,
                    }}>
                     <img
                            src="/img/emma-avatar.jpg"
                            alt="Emma"
                            style={{ width: 26, height: 26, borderRadius: "50%", objectFit: "cover", flexShrink: 0 }}
                        />
                        <div style={{ flex: 1 }}>
                            <div style={{ color: "#fff", fontSize: 13, fontWeight: 700 }}>Emma</div>
                            <div style={{ color: "rgba(255,255,255,0.65)", fontSize: 10, marginTop: 1 }}>
                                <span style={{
                                    display: "inline-block", width: 5, height: 5, borderRadius: "50%",
                                    background: "#4ade80", marginRight: 4, verticalAlign: "middle",
                                }} />
                                ENSUP Group · Toujours disponible
                            </div>
                        </div>
                        <button
                            onClick={resetConversation}
                            title="Nouvelle conversation"
                            style={{
                                background: "rgba(255,255,255,0.15)", border: "none", borderRadius: 7,
                                width: 28, height: 28, cursor: "pointer", color: "rgba(255,255,255,0.8)",
                                fontSize: 14, display: "flex", alignItems: "center", justifyContent: "center",
                            }}
                        >🗑</button>
                        <button
                            onClick={() => setOpen(false)}
                            style={{
                                background: "rgba(255,255,255,0.15)", border: "none", borderRadius: 7,
                                width: 28, height: 28, cursor: "pointer", color: "#fff",
                                fontSize: 17, display: "flex", alignItems: "center", justifyContent: "center",
                            }}
                        >✕</button>
                    </div>

                    {/* BADGE MÉMOIRE CONTEXTUELLE */}
                    <MemoryBadge topics={conversationTopics} />

                    {/* MESSAGES */}
                    <div
                        className="ndf-scroll"
                        style={{
                            flex: 1, overflowY: "auto",
                            padding: "14px 13px 6px",
                            display: "flex", flexDirection: "column",
                        }}
                    >
                        {displayMsgs.map((msg) => (
                            <MessageBubble
                                key={msg.id}
                                msg={msg}
                                onNegativeFeedback={handleNegativeFeedback}
                            />
                        ))}
                        {loading && <TypingIndicator />}
                        <div ref={bottomRef} />
                    </div>

                    {/* SUGGESTIONS DYNAMIQUES */}
                    {currentSuggestions.length > 0 && (
                        <SuggestionsBar
                            suggestions={currentSuggestions}
                            label={suggestionsLabel}
                            onSelect={sendMessage}
                            disabled={loading}
                        />
                    )}

                    <div style={{ height: 1, background: "var(--border-divider,#e2e8f0)", flexShrink: 0 }} />

                    {/* INPUT */}
                    <form
                        onSubmit={(e) => { e.preventDefault(); sendMessage(input); }}
                        style={{
                            display: "flex", gap: 7, padding: "10px 13px",
                            background: "var(--bg-card,#fff)", flexShrink: 0,
                        }}
                    >
                        <input
                            ref={inputRef}
                            className="ndf-inp"
                            value={input}
                            onChange={(e) => setInput(e.target.value)}
                            placeholder="Posez votre question..."
                            disabled={loading}
                            style={{
                                flex: 1, padding: "8px 11px",
                                border: "1.5px solid var(--border-input,#e2e8f0)",
                                borderRadius: 9, fontSize: 12.5, fontFamily: "inherit",
                                background: "var(--bg-input,#f8fafc)",
                                color: "var(--text-primary,#1e293b)",
                                transition: "border-color 0.2s, box-shadow 0.2s",
                            }}
                        />
                        <button
                            type="submit"
                            className="ndf-send"
                            disabled={!input.trim() || loading}
                            style={{
                                width: 36, height: 36, borderRadius: 9, flexShrink: 0,
                                background: "linear-gradient(135deg,#6366f1,#4f46e5)",
                                border: "none", cursor: "pointer",
                                display: "flex", alignItems: "center", justifyContent: "center",
                                fontSize: 15, color: "#fff", transition: "background 0.15s",
                            }}
                        >➤</button>
                    </form>

                    <div style={{
                        padding: "5px 13px 9px",
                        background: "var(--bg-card,#fff)",
                        textAlign: "center", fontSize: 9.5,
                        color: "var(--text-muted,#94a3b8)",
                    }}>
                       Emma · ENSUP Group
                    </div>
                </div>
            )}
        </>
    );
} 