const { useState, useMemo, useEffect } = React;

const data = [
  { id: 1, dom: "Droit civil", sd: "Relations personnelles hors mariage", dem: "Infidélité dans un concubinage", mis: "Suspicion d'un fait constitutif d'infidélité dans une union de fait (préjudice existant)", cj: ["Art. 515.8 du Code civil", "Art. 1240 du Code civil"], jp: ["JP Civ. 30 mai 1838, Bouvier Juris. Générale V° Mariage, n°82 Sirey 1838, 1, 492 (Rupture de fiançailles)", "JP CA Reims n°05/01583 du 19/10/06"] },
  { id: 2, dom: "Droit civil", sd: "Relations personnelles hors mariage", dem: "Infidélité dans un PACS", mis: "Suspicion d'un fait constitutif d'infidélité entre partenaires de PACS", cj: ["Art. 515.1 à 7 du Code civil", "Art. 1104 du Code civil"], jp: [] },
  { id: 3, dom: "Droit civil", sd: "Relations personnelles hors mariage", dem: "Départ du domicile", mis: "Déterminer la cessation de vie commune dans le cadre d'un PACS", cj: ["Art. 515.4 du Code civil"], jp: [] },
  { id: 4, dom: "Droit civil", sd: "Mariage", dem: "Enquêtes de moralité", mis: "Suspicion d'un défaut de capacité ou d'empêchement légal au mariage", cj: ["Art. 144 du Code civil", "Art. 146 du Code civil", "Art. 161 du Code civil"], jp: [] },
  { id: 5, dom: "Droit civil", sd: "Mariage", dem: "Enquête sur la validité du mariage célébré", mis: "Suspicion de non-conformité de la cérémonie matrimoniale", cj: ["Art. 165 du Code civil", "Art. 180 du Code civil"], jp: [] },
  { id: 6, dom: "Droit civil", sd: "Divorce et séparation", dem: "Adultère", mis: "Suspicion de violation du devoir de fidélité", cj: ["Art. 212 du Code civil", "Art. 242 du Code civil"], jp: [] },
  { id: 7, dom: "Droit civil", sd: "Divorce et séparation", dem: "Départ du domicile", mis: "Déterminer la cessation de vie commune", cj: ["Art. 215 du Code civil", "Art. 237 et 238 du Code civil"], jp: [] },
  { id: 8, dom: "Droit civil", sd: "Effets du divorce/de la séparation", dem: "Prestation compensatoire", mis: "Déterminer les conditions de vie des époux", cj: ["Art. 270 et 271 du Code civil"], jp: [] },
  { id: 9, dom: "Droit civil", sd: "Effets du divorce/de la séparation", dem: "Pension alimentaire entre époux", mis: "Déterminer les conditions de vie des époux", cj: ["Art. 212 du Code civil", "Art. 255.6 du Code civil"], jp: [] },
  { id: 10, dom: "Droit civil", sd: "Effets du divorce/de la séparation", dem: "Dommages et intérêts", mis: "Déterminer les conditions de vie des époux", cj: ["Art. 266 du Code civil"], jp: [] },
  { id: 11, dom: "Droit civil", sd: "Effets du divorce/de la séparation", dem: "Enquête de patrimoine", mis: "Déterminer du patrimoine dans le cadre de la liquidation du régime matrimonial", cj: ["Art. 1467 du Code civil"], jp: [] },
  { id: 12, dom: "Droit civil", sd: "Effets du divorce/de la séparation", dem: "Pension alimentaire enfants", mis: "Déterminer les conditions de vie d'un parent", cj: ["Art. 371.2 et 373.2.2 du Code civil"], jp: [] },
  { id: 13, dom: "Droit civil", sd: "Effets du divorce/de la séparation", dem: "Garde d'enfants", mis: "Déterminer les conditions de vie d'un parent", cj: ["Art. 373.2.7 du Code civil"], jp: [] },
  { id: 14, dom: "Droit civil", sd: "Effets du divorce/de la séparation", dem: "Conditions de garde", mis: "Déterminer les carences éducatives", cj: ["Art. 371.4 du Code civil", "Art. 375 du Code civil"], jp: [] },
  { id: 15, dom: "Droit civil", sd: "Filiation / absence et successions", dem: "Enquête de moralité sur mineur", mis: "Déterminer les fréquentations d'un mineur", cj: ["Art. 371.1.2° du Code civil"], jp: [] },
  { id: 16, dom: "Droit civil", sd: "Filiation / absence et successions", dem: "Recherche de paternité", mis: "Déterminer une filiation", cj: ["Art. 327 du Code civil"], jp: [] },
  { id: 17, dom: "Droit civil", sd: "Filiation / absence et successions", dem: "Recherche d'héritiers", mis: "Procédure d'identification des ayants droit", cj: ["Art. 725 du Code civil", "Loi n°2014-617 du 13/06/2014"], jp: [] },
  { id: 18, dom: "Droit civil", sd: "Filiation / absence et successions", dem: "Recherche de personnes", mis: "Établir la disparition", cj: ["Art. 112 du Code civil", "Art. 1240 du Code civil"], jp: [] },
  { id: 19, dom: "Droit civil", sd: "Filiation / absence et successions", dem: "Recherche de débiteur", mis: "Localiser un débiteur", cj: ["Art. 1217 du Code civil"], jp: [] },
  { id: 20, dom: "Droit civil", sd: "Contrats juridiques", dem: "Enquête sur co-contractant", mis: "Suspicion de non respect des conditions de validité", cj: ["Art. 1112.1 du Code civil"], jp: [] },
  { id: 21, dom: "Droit civil", sd: "Contrats juridiques", dem: "Enquête sur les effets d'un contrat", mis: "Suspicion de défaillance d'exécution", cj: ["Art. 1103 du Code civil"], jp: [] },
  { id: 22, dom: "Droit civil", sd: "Faits juridiques", dem: "Responsabilité extra-contractuelle", mis: "Déterminer la responsabilité d'un tiers", cj: ["Art. 1240 du Code civil"], jp: [] },
  { id: 23, dom: "Droit penal des affaires", sd: "Détournements d'actifs", dem: "Vol interne ou externe", mis: "Suspicion d'actes de vols", cj: ["Art. 311-1 du Code penal"], jp: [] },
  { id: 24, dom: "Droit penal des affaires", sd: "Détournements d'actifs", dem: "Escroquerie", mis: "Suspicion d'escroquerie", cj: ["Art. 313-1 du Code penal"], jp: [] },
  { id: 25, dom: "Droit penal des affaires", sd: "Détournements d'actifs", dem: "Abus de confiance", mis: "Suspicion abus de confiance", cj: ["Art. 314-1 du Code penal"], jp: [] },
  { id: 26, dom: "Droit penal des affaires", sd: "Abus de biens sociaux", dem: "Abus de biens sociaux", mis: "Suspicion d'abus", cj: ["Art. L241-3 du Code du commerce"], jp: [] },
  { id: 27, dom: "Droit pénal", sd: "Vols et déprédations", dem: "Vandalisme et vol", mis: "Suspicion de destruction", cj: ["Art. 322-1 du Code penal"], jp: [] },
  { id: 28, dom: "Droit pénal", sd: "Contrefaçon", dem: "Contrefaçon", mis: "Suspicion de contrefaçons", cj: ["Art. L335-2 du CPI"], jp: [] },
  { id: 29, dom: "Droit pénal", sd: "Harcèlement", dem: "Harcèlement", mis: "Suspicion de harcèlement", cj: ["Art. 222-33 du Code pénal"], jp: [] },
  { id: 30, dom: "Droit pénal", sd: "Provocation de mineur", dem: "Provocation de mineur", mis: "Suspicion de mise en péril", cj: ["Art. 227-18 du Code pénal"], jp: [] },
  { id: 31, dom: "Droit pénal", sd: "Trouble de voisinage", dem: "Tapage", mis: "Suspicion de tapage nocturne", cj: ["Art. R623-2 du Code pénal"], jp: [] },
  { id: 32, dom: "Droit pénal", sd: "Révision de justice", dem: "Révision de décision", mis: "Révision de décision de justice", cj: ["Art. 622 du CPP"], jp: [] },
  { id: 33, dom: "Droit du travail", sd: "Relation de travail", dem: "Seconde relation de travail", mis: "Suspicion de travail illégal", cj: ["Art. L1237-3 du Code du travail"], jp: [] },
  { id: 34, dom: "Droit du travail", sd: "Exécution du contrat", dem: "Conditions de travail", mis: "Suspicion de non respect des obligations", cj: ["Art. L3121-27 du Code du travail"], jp: [] },
  { id: 35, dom: "Droit du travail", sd: "Exécution du contrat", dem: "Obligations du salarié", mis: "Suspicion de non respect de loyauté", cj: ["Art. L1222-1 du Code du travail"], jp: [] },
  { id: 36, dom: "Droit du travail", sd: "Concurrence déloyale", dem: "Concurrence déloyale", mis: "Suspicion d'actes de concurrence déloyal", cj: ["Art. 1240 du Code civil"], jp: ["Notions: dénigrement, parasitisme"] },
  { id: 37, dom: "Droit du travail", sd: "Concurrence déloyale", dem: "Clause de non concurrence", mis: "Suspicion de non-respect de clause", cj: ["Art. 1240 du Code civil"], jp: [] },
  { id: 38, dom: "Droit du travail", sd: "Suspension travail", dem: "Arrêt maladie", mis: "Suspicion de non respect de loyauté", cj: ["Art. L1222-1 du Code du travail"], jp: [] },
  { id: 39, dom: "Droit du travail", sd: "Vérification factuels", dem: "Constat commissaire", mis: "Préparation de constat", cj: ["Art. L621-1 du CSI"], jp: [] }
];

const L = ({ className }) => (
  <svg viewBox="0 0 24 24" className={className}>
    <path d="M12 2 C 8 2 4 3 3 5 C 3 5 3 6 3 8 L 3 13 C 3 18 12 22 12 22 C 12 22 21 18 21 13 L 21 8 C 21 6 21 5 21 5 C 20 3 16 2 12 2 Z" className="fill-amber-400/15"/>
    <path d="M12 2 C 8 2 4 3 3 5 C 3 5 3 6 3 8 L 3 13 C 3 18 12 22 12 22 C 12 22 21 18 21 13 L 21 8 C 21 6 21 5 21 5 C 20 3 16 2 12 2 Z" fill="none" className="stroke-amber-400" strokeWidth="1"/>
    <line x1="12" y1="8.5" x2="12" y2="15.5" className="stroke-amber-400" strokeWidth="1.2"/>
    <line x1="8" y1="8.5" x2="16" y2="8.5" className="stroke-amber-400" strokeWidth="1.2"/>
    <path d="M 8 8.5 L 6.8 11.2 L 9.2 11.2 Z" className="fill-amber-400"/>
    <line x1="8" y1="8.5" x2="8" y2="11.2" className="stroke-amber-400" strokeWidth="0.5"/>
    <path d="M 16 8.5 L 14.8 11.2 L 17.2 11.2 Z" className="fill-amber-400"/>
    <line x1="16" y1="8.5" x2="16" y2="11.2" className="stroke-amber-400" strokeWidth="0.5"/>
    <rect x="10.3" y="15.5" width="3.4" height="0.9" className="fill-amber-400" rx="0.2"/>
  </svg>
);

function App() {
  const [t, setT] = useState('dark');
  const [adm, setAdm] = useState(false);
  const [s, setS] = useState('');
  const [d, setD] = useState('tous');
  const [sd, setSd] = useState('tous');
  const [sel, setSel] = useState(null);
  const [rip, setRip] = useState([]);
  const [counters, setCounters] = useState({ domains: 0, subdomains: 0, cadres: 0 });
  const [showScrollTop, setShowScrollTop] = useState(false);
  const [cadresData, setCadresData] = useState(data);
  
  const [authenticated, setAuthenticated] = useState(false);
  const [showLoginModal, setShowLoginModal] = useState(false);
  const [loginPassword, setLoginPassword] = useState('');
  const [loginError, setLoginError] = useState('');
  
  const [adminView, setAdminView] = useState('main');
  const [editingCadre, setEditingCadre] = useState(null);
  const [showEditModal, setShowEditModal] = useState(false);
  const [isAddingNew, setIsAddingNew] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [cadreToDelete, setCadreToDelete] = useState(null);
  const [formData, setFormData] = useState({ dom: '', sd: '', dem: '', mis: '', cj: [], jp: [], note: '' });
  const [isCreatingDomain, setIsCreatingDomain] = useState(false);
  const [isCreatingSubdomain, setIsCreatingSubdomain] = useState(false);
  const [customDomain, setCustomDomain] = useState('');
  const [customSubdomain, setCustomSubdomain] = useState('');
  const [copiedMissionId, setCopiedMissionId] = useState(null);

  const modalDomains = useMemo(() => {
    return [...new Set(cadresData.map(c => c.dom).filter(d => d))].sort();
  }, [cadresData]);

  const modalSubdomains = useMemo(() => {
    if (!formData.dom) return [];
    return [...new Set(cadresData.filter(c => c.dom === formData.dom).map(c => c.sd).filter(s => s))].sort();
  }, [cadresData, formData.dom]);

  useEffect(() => {
    const sv = localStorage.getItem('theme') || 'dark';
    setT(sv);
    
    // Charger les données depuis le serveur au démarrage
    loadFromServer();
  }, []);

  useEffect(() => {
    const totalDomains = new Set(cadresData.map(c => c.dom)).size;
    const totalSubdomains = new Set(cadresData.map(c => c.sd)).size;
    const totalCadres = cadresData.length;
    
    const duration = 2800;
    const startTime = performance.now();
    
    const animate = (currentTime) => {
      const elapsed = currentTime - startTime;
      const progress = Math.min(elapsed / duration, 1);
      const easeOutCubic = 1 - Math.pow(1 - progress, 3);
      
      setCounters({
        domains: Math.round(easeOutCubic * totalDomains),
        subdomains: Math.round(easeOutCubic * totalSubdomains),
        cadres: Math.round(easeOutCubic * totalCadres)
      });
      
      if (progress < 1) {
        requestAnimationFrame(animate);
      }
    };
    
    requestAnimationFrame(animate);
    
    const handleScroll = () => {
      setShowScrollTop(window.scrollY > 300);
    };
    
    window.addEventListener('scroll', handleScroll);
    
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, [cadresData]);

  const tog = () => {
    const nt = t === 'dark' ? 'light' : 'dark';
    setT(nt);
    localStorage.setItem('theme', nt);
  };

  const handleAdminToggle = () => {
    if (authenticated) {
      setAdm(!adm);
      if (!adm) setAdminView('main');
    } else {
      setShowLoginModal(true);
    }
  };

  const handleLogin = async (e) => {
    e.preventDefault();
    setLoginError('');
    
    // Authentification serveur
    const isAuthenticated = await authenticateServer(loginPassword);
    
    if (isAuthenticated) {
      setAuthenticated(true);
      setShowLoginModal(false);
      setLoginPassword('');
      setAdm(true);
    } else {
      setLoginError('Mot de passe incorrect');
      setLoginPassword('');
    }
  };

  const handleLogout = () => {
    setAuthenticated(false);
    setAdm(false);
    setAdminView('main');
  };

  // ========================================
  // FONCTIONS SERVEUR (PHP Backend)
  // ========================================
  
  const loadFromServer = async () => {
    try {
      const timestamp = Date.now();
      const response = await fetch(`load.php?t=${timestamp}`);
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const data = await response.json();
      
      if (Array.isArray(data)) {
        setCadresData(data);
        console.log(`✅ ${data.length} cadres chargés depuis le serveur`);
      } else {
        console.error('❌ Format de données invalide');
      }
    } catch (error) {
      console.error('❌ Erreur chargement serveur:', error);
      // Fallback sur les données locales en cas d'erreur
      console.log('⚠️ Utilisation des données locales (fallback)');
    }
  };

  const saveToServer = async (data) => {
    console.log('🔵 [SAVE] Début de la sauvegarde...', {
      nbCadres: data.length,
      timestamp: new Date().toLocaleTimeString()
    });
    
    try {
      const response = await fetch('save.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify(data)
      });
      
      console.log('🔵 [SAVE] Réponse reçue:', {
        status: response.status,
        ok: response.ok
      });
      
      if (!response.ok) {
        const error = await response.json();
        console.error('🔴 [SAVE] Erreur serveur:', error);
        throw new Error(error.message || `HTTP error! status: ${response.status}`);
      }
      
      const result = await response.json();
      console.log('✅ [SAVE] Sauvegarde réussie:', result);
      return true;
    } catch (error) {
      console.error('❌ [SAVE] Erreur sauvegarde serveur:', error);
      alert('⚠️ Erreur de sauvegarde sur le serveur. Vérifiez votre connexion.');
      return false;
    }
  };

  const authenticateServer = async (password) => {
    try {
      const response = await fetch('auth.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({ password })
      });
      
      if (!response.ok) {
        return false;
      }
      
      const result = await response.json();
      return result.success === true;
    } catch (error) {
      console.error('❌ Erreur authentification serveur:', error);
      return false;
    }
  };




  const exportToCSV = () => {
    const headers = ['ID', 'Domaine', 'Sous-domaine', 'Titre', 'Mission', 'Cadres Juridiques', 'URLs Cadres', 'Jurisprudences', 'URLs Jurisprudences', 'Note'];
    
    const csvContent = [
      headers.join(','),
      ...cadresData.map(c => {
        const cjTexts = c.cj.map(cj => typeof cj === 'string' ? cj : cj.text).join(' | ');
        const cjUrls = c.cj.map(cj => typeof cj === 'object' && cj.url ? cj.url : '').filter(u => u).join(' | ');
        const jpTexts = c.jp.map(jp => typeof jp === 'string' ? jp : jp.text).join(' | ');
        const jpUrls = c.jp.map(jp => typeof jp === 'object' && jp.url ? jp.url : '').filter(u => u).join(' | ');
        
        return [
          c.id,
          `"${c.dom.replace(/"/g, '""')}"`,
          `"${c.sd.replace(/"/g, '""')}"`,
          `"${c.dem.replace(/"/g, '""')}"`,
          `"${c.mis.replace(/"/g, '""')}"`,
          `"${cjTexts.replace(/"/g, '""')}"`,
          `"${cjUrls.replace(/"/g, '""')}"`,
          `"${jpTexts.replace(/"/g, '""')}"`,
          `"${jpUrls.replace(/"/g, '""')}"`,
          `"${(c.note || '').replace(/"/g, '""')}"`
        ].join(',');
      })
    ].join('\n');
    
    const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `ONARP_Cadres_Juridiques_${new Date().toISOString().split('T')[0]}.csv`;
    link.click();
  };

  const exportToJSON = () => {
    const jsonContent = JSON.stringify(cadresData, null, 2);
    const blob = new Blob([jsonContent], { type: 'application/json' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `ONARP_Cadres_Juridiques_${new Date().toISOString().split('T')[0]}.json`;
    link.click();
  };

  const handleEditCadre = (cadre) => {
    setIsAddingNew(false);
    setEditingCadre(cadre);
    setIsCreatingDomain(false);
    setIsCreatingSubdomain(false);
    setCustomDomain('');
    setCustomSubdomain('');
    
    const cjArray = Array.isArray(cadre.cj) && cadre.cj.length > 0 
      ? cadre.cj.map(item => typeof item === 'string' ? { text: item, url: '' } : { text: item.text || '', url: item.url || '' })
      : [];
    
    const jpArray = Array.isArray(cadre.jp) && cadre.jp.length > 0 
      ? cadre.jp.map(item => typeof item === 'string' ? { text: item, url: '' } : { text: item.text || '', url: item.url || '' })
      : [];
    
    setFormData({
      dom: cadre.dom || '',
      sd: cadre.sd || '',
      dem: cadre.dem || '',
      mis: cadre.mis || '',
      cj: cjArray,
      jp: jpArray,
      note: cadre.note || ''
    });
    setShowEditModal(true);
  };

  const handleAddNewCadre = () => {
    setIsAddingNew(true);
    setEditingCadre(null);
    setIsCreatingDomain(false);
    setIsCreatingSubdomain(false);
    setCustomDomain('');
    setCustomSubdomain('');
    setFormData({ dom: '', sd: '', dem: '', mis: '', cj: [], jp: [], note: '' });
    setShowEditModal(true);
  };

  const handleSaveCadre = async () => {
    const finalDomain = isCreatingDomain ? customDomain.trim() : formData.dom;
    const finalSubdomain = isCreatingSubdomain ? customSubdomain.trim() : formData.sd;
    
    if (!finalDomain || !finalSubdomain || !formData.dem || !formData.mis) {
      alert('Veuillez remplir tous les champs obligatoires : Domaine, Sous-domaine, Titre et Mission');
      return;
    }
    
    if (isAddingNew) {
      const newId = Math.max(...cadresData.map(c => c.id), 0) + 1;
      const newCadre = {
        id: newId,
        dom: finalDomain,
        sd: finalSubdomain,
        dem: formData.dem,
        mis: formData.mis,
        cj: formData.cj.map(item => item.url ? { text: item.text, url: item.url } : item.text),
        jp: formData.jp.map(item => item.url ? { text: item.text, url: item.url } : item.text),
        note: formData.note
      };
      const updatedData = [...cadresData, newCadre];
      setCadresData(updatedData);
      console.log('💾 [AJOUT] Appel saveToServer avec', updatedData.length, 'cadres');
      await saveToServer(updatedData);
      alert('✅ Nouveau cadre créé avec succès !');
    } else {
      const updatedCadre = {
        ...editingCadre,
        dom: finalDomain,
        sd: finalSubdomain,
        dem: formData.dem,
        mis: formData.mis,
        cj: formData.cj.map(item => item.url ? { text: item.text, url: item.url } : item.text),
        jp: formData.jp.map(item => item.url ? { text: item.text, url: item.url } : item.text),
        note: formData.note
      };
      
      const updatedData = cadresData.map(c => 
        c.id === editingCadre.id ? updatedCadre : c
      );
      setCadresData(updatedData);
      console.log('💾 [MODIFICATION] Appel saveToServer avec', updatedData.length, 'cadres');
      await saveToServer(updatedData);
      
      if (sel?.id === editingCadre.id) {
        setSel(updatedCadre);
      }
      
      alert('✅ Modifications sauvegardées avec succès !');
    }
    
    setShowEditModal(false);
    setEditingCadre(null);
    setIsAddingNew(false);
    setIsCreatingDomain(false);
    setIsCreatingSubdomain(false);
    setCustomDomain('');
    setCustomSubdomain('');
    setAdminView('main');
  };

  const handleDeleteCadre = (cadreId) => {
    const cadre = cadresData.find(c => c.id === cadreId);
    if (!cadre) {
      alert('Erreur : Cadre introuvable');
      return;
    }
    setCadreToDelete(cadre);
    setShowDeleteConfirm(true);
  };

  const confirmDelete = async () => {
    if (cadreToDelete) {
      const updatedData = cadresData.filter(c => c.id !== cadreToDelete.id);
      setCadresData(updatedData);
      console.log('💾 [SUPPRESSION] Appel saveToServer avec', updatedData.length, 'cadres');
      await saveToServer(updatedData);
      if (sel?.id === cadreToDelete.id) {
        setSel(null);
      }
      setShowDeleteConfirm(false);
      setCadreToDelete(null);
      alert('✅ Cadre supprimé avec succès !');
    }
  };

  const cancelDelete = () => {
    setShowDeleteConfirm(false);
    setCadreToDelete(null);
  };

  const addCjItem = () => {
    setFormData({ ...formData, cj: [...formData.cj, { text: '', url: '' }] });
  };

  const addJpItem = () => {
    setFormData({ ...formData, jp: [...formData.jp, { text: '', url: '' }] });
  };

  const removeCjItem = (index) => {
    setFormData({ ...formData, cj: formData.cj.filter((_, i) => i !== index) });
  };

  const removeJpItem = (index) => {
    setFormData({ ...formData, jp: formData.jp.filter((_, i) => i !== index) });
  };

  const updateCjItem = (index, field, value) => {
    const newCj = [...formData.cj];
    newCj[index][field] = value;
    setFormData({ ...formData, cj: newCj });
  };

  const updateJpItem = (index, field, value) => {
    const newJp = [...formData.jp];
    newJp[index][field] = value;
    setFormData({ ...formData, jp: newJp });
  };

  const moveCjItem = (index, direction) => {
    if ((direction === 'up' && index === 0) || (direction === 'down' && index === formData.cj.length - 1)) return;
    const newCj = [...formData.cj];
    const newIndex = direction === 'up' ? index - 1 : index + 1;
    [newCj[index], newCj[newIndex]] = [newCj[newIndex], newCj[index]];
    setFormData({ ...formData, cj: newCj });
  };

  const moveJpItem = (index, direction) => {
    if ((direction === 'up' && index === 0) || (direction === 'down' && index === formData.jp.length - 1)) return;
    const newJp = [...formData.jp];
    const newIndex = direction === 'up' ? index - 1 : index + 1;
    [newJp[index], newJp[newIndex]] = [newJp[newIndex], newJp[index]];
    setFormData({ ...formData, jp: newJp });
  };

  const handleRip = (e) => {
    const x = e.clientX;
    const y = e.clientY;
    const id = Date.now();
    setRip(prev => [...prev, { x, y, id }]);
    setTimeout(() => setRip(prev => prev.filter(r => r.id !== id)), 1500);
  };

  const scrollToTop = () => {
    const duration = 1500;
    const start = window.pageYOffset;
    const startTime = performance.now();
    
    const animateScroll = (currentTime) => {
      const elapsed = currentTime - startTime;
      const progress = Math.min(elapsed / duration, 1);
      const easeInOutCubic = progress < 0.5 
        ? 4 * progress * progress * progress 
        : 1 - Math.pow(-2 * progress + 2, 3) / 2;
      
      window.scrollTo(0, start * (1 - easeInOutCubic));
      
      if (progress < 1) {
        requestAnimationFrame(animateScroll);
      }
    };
    
    requestAnimationFrame(animateScroll);
  };

  const doms = useMemo(() => ['tous', ...new Set(cadresData.map(c => c.dom))], [cadresData]);
  const sds = useMemo(() => {
    if (d === 'tous') return [];
    return ['tous', ...new Set(cadresData.filter(c => c.dom === d).map(c => c.sd))];
  }, [d, cadresData]);

  const filt = useMemo(() => {
    return cadresData.filter(c => {
      const md = d === 'tous' || c.dom === d;
      const msd = sd === 'tous' || c.sd === sd;
      const ms = !s || c.dem.toLowerCase().includes(s.toLowerCase()) || c.mis.toLowerCase().includes(s.toLowerCase());
      return md && msd && ms;
    });
  }, [d, sd, s, cadresData]);

  const btnClass = (active) => `relative px-5 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 ease-in-out hover:scale-105 active:scale-95 hover:shadow-lg hover:shadow-amber-500/30 hover:ring-2 hover:ring-amber-500/50 ${active ? t==='dark' ? 'bg-amber-500 text-slate-900 shadow-lg ring-2 ring-amber-400' : 'bg-amber-500 text-white shadow-lg ring-2 ring-amber-400' : t==='dark' ? 'bg-slate-700 hover:bg-slate-600 text-white border border-slate-600' : 'bg-[#F0EDE7] hover:bg-[#DDD9D3] text-gray-700 border border-gray-300'}`;

  return (
    <div onClick={handleRip} style={{fontFamily: "'Avenir Next', sans-serif"}} className={`min-h-screen transition-colors duration-500 ${t==='dark'?'bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 text-white':'bg-gradient-to-br from-[#E8E6E0] via-[#E5E3DD] to-[#E2E0DA] text-black'} relative`}>
      
      {rip.map(r => (
        <span key={r.id} className="fixed pointer-events-none z-50 animate-ripple-wave border-2 border-amber-400 rounded-full" style={{left: r.x, top: r.y, width: '0px', height: '0px', transform: 'translate(-50%, -50%)'}} />
      ))}

      <header className={`sticky top-0 z-40 backdrop-blur-sm border-b transition-colors duration-300 ${t==='dark'?'bg-slate-900/90 border-slate-700/50':'bg-[#E5E3DD]/95 border-gray-300'}`}>
        <div className="max-w-6xl mx-auto px-4 sm:px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2 sm:gap-3">
              <L className="w-10 h-10 sm:w-12 sm:h-12"/>
              <div>
                <h1 className={`text-lg sm:text-xl font-bold ${t==='dark'?'text-amber-400':'text-amber-600'}`}>ONARP</h1>
                <p className={`text-xs sm:text-sm font-bold ${t==='dark'?'text-slate-400':'text-gray-600'}`}>Outil d'aide à la détermination du cadre juridique</p>
              </div>
            </div>
            <div className="flex items-center gap-2 sm:gap-4">
              <button onClick={tog} className={`w-10 h-10 sm:w-12 sm:h-12 rounded-full transition-all duration-300 hover:rotate-180 hover:scale-110 hover:ring-2 hover:ring-amber-500/50 hover:shadow-lg hover:shadow-amber-500/30 flex items-center justify-center ${t==='dark'?'bg-slate-800 hover:bg-slate-700 text-amber-400 border-2 border-slate-700':'bg-[#F0EDE7] hover:bg-[#DDD9D3] text-amber-600 border-2 border-gray-300'}`}>
                {t === 'dark' ? (
                  <svg className="w-5 h-5 sm:w-6 sm:h-6" fill="currentColor" viewBox="0 0 20 20">
                    <path d="M10 2a1 1 0 011 1v1a1 1 0 11-2 0V3a1 1 0 011-1zm4 8a4 4 0 11-8 0 4 4 0 018 0zm-.464 4.95l.707.707a1 1 0 001.414-1.414l-.707-.707a1 1 0 00-1.414 1.414zm2.12-10.607a1 1 0 010 1.414l-.706.707a1 1 0 11-1.414-1.414l.707-.707a1 1 0 011.414 0zM17 11a1 1 0 100-2h-1a1 1 0 100 2h1zm-7 4a1 1 0 011 1v1a1 1 0 11-2 0v-1a1 1 0 011-1zM5.05 6.464A1 1 0 106.465 5.05l-.708-.707a1 1 0 00-1.414 1.414l.707.707zm1.414 8.486l-.707.707a1 1 0 01-1.414-1.414l.707-.707a1 1 0 011.414 1.414zM4 11a1 1 0 100-2H3a1 1 0 000 2h1z" fillRule="evenodd" clipRule="evenodd"></path>
                  </svg>
                ) : (
                  <svg className="w-5 h-5 sm:w-6 sm:h-6" fill="currentColor" viewBox="0 0 20 20">
                    <path d="M17.293 13.293A8 8 0 016.707 2.707a8.001 8.001 0 1010.586 10.586z"></path>
                  </svg>
                )}
              </button>
              
              <button onClick={handleAdminToggle} className={`w-10 h-10 sm:w-12 sm:h-12 rounded-full transition-all duration-300 hover:scale-110 hover:ring-2 hover:ring-amber-500/50 hover:shadow-lg hover:shadow-amber-500/30 flex items-center justify-center group ${adm?t==='dark'?'bg-amber-500 text-slate-900 border-2 border-amber-400 rotate-45':'bg-amber-500 text-white border-2 border-amber-400 rotate-45':t==='dark'?'bg-slate-800 hover:bg-slate-700 text-amber-400 border-2 border-slate-700':'bg-[#F0EDE7] hover:bg-[#DDD9D3] text-amber-600 border-2 border-gray-300'}`}>
                <svg viewBox="0 0 24 24" className={`w-5 h-5 sm:w-6 sm:h-6 transition-transform duration-500 group-hover:rotate-90 ${adm?'rotate-180':''}`} fill="currentColor">
                  <path d="M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94L14.4 2.81c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z"/>
                </svg>
              </button>

              {authenticated && (
                <button onClick={handleLogout} className={`w-10 h-10 sm:w-12 sm:h-12 rounded-full transition-all duration-500 ease-out hover:scale-110 active:scale-95 hover:ring-2 hover:ring-red-500/50 hover:shadow-lg hover:shadow-red-500/30 flex items-center justify-center group ${t==='dark'?'bg-red-900/30 hover:bg-red-900/50 text-red-400 border-2 border-red-700':'bg-red-50 hover:bg-red-100 text-red-600 border-2 border-red-300'}`} title="Déconnexion">
                  <svg viewBox="0 0 24 24" className="w-5 h-5 sm:w-6 sm:h-6 transition-transform duration-500 group-hover:translate-x-1 group-hover:scale-110 group-active:scale-90" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
                    <polyline points="16 17 21 12 16 7"/>
                    <line x1="21" y1="12" x2="9" y2="12"/>
                  </svg>
                </button>
              )}
            </div>
          </div>
        </div>
      </header>

      <div className={`border-b ${t==='dark'?'bg-slate-800/30 border-slate-700/50':'bg-amber-50 border-amber-200'}`}>
        <div className="max-w-6xl mx-auto px-4 sm:px-6 py-3">
          <div className="flex items-center justify-center gap-4 sm:gap-8">
            <div className="text-center">
              <div className={`text-xl sm:text-2xl font-bold ${t==='dark'?'text-amber-400':'text-amber-600'}`}>{counters.domains}</div>
              <div className={`text-xs sm:text-sm font-medium ${t==='dark'?'text-slate-400':'text-gray-600'}`}>Domaines juridiques</div>
            </div>
            <div className="text-center">
              <div className={`text-xl sm:text-2xl font-bold ${t==='dark'?'text-amber-400':'text-amber-600'}`}>{counters.subdomains}</div>
              <div className={`text-xs sm:text-sm font-medium ${t==='dark'?'text-slate-400':'text-gray-600'}`}>Sous-domaines juridiques</div>
            </div>
            <div className="text-center">
              <div className={`text-xl sm:text-2xl font-bold ${t==='dark'?'text-amber-400':'text-amber-600'}`}>{counters.cadres}</div>
              <div className={`text-xs sm:text-sm font-medium ${t==='dark'?'text-slate-400':'text-gray-600'}`}>Cadres juridiques</div>
            </div>
          </div>
        </div>
      </div>

      {adm && (
        <div className={`border-b ${t==='dark'?'bg-amber-500/10 border-amber-500/30':'bg-amber-100 border-amber-300'}`}>
          <div className="max-w-6xl mx-auto px-4 sm:px-6 py-3">
            <p className={`text-xs sm:text-sm font-medium ${t==='dark'?'text-amber-400':'text-amber-700'}`}>🔒 Mode Administration</p>
          </div>
        </div>
      )}

      <main className="max-w-6xl mx-auto px-4 sm:px-6 py-6 sm:py-8">
        {adm ? (
          <div className="space-y-6">
            {adminView === 'main' && (
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4 md:gap-6">
                <button onClick={handleAddNewCadre} className={`group p-6 md:p-8 rounded-xl border-2 border-dashed transition-all duration-300 hover:scale-105 hover:ring-2 hover:ring-amber-500/50 ${t==='dark'?'border-slate-600 hover:border-amber-500 bg-slate-800/50':'border-gray-300 hover:border-amber-500 bg-[#F0EDE7]'}`}>
                  <div className="flex justify-center mb-4">
                    <svg className={`w-12 h-12 md:w-16 md:h-16 transition-all duration-300 group-hover:scale-110 group-hover:rotate-90 ${t==='dark'?'text-amber-400':'text-amber-600'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v16m8-8H4" />
                    </svg>
                  </div>
                  <div className={`text-base md:text-lg font-bold mb-2 ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Ajouter un cadre</div>
                  <div className={`text-xs md:text-sm ${t==='dark'?'text-slate-400':'text-gray-600'}`}>Créer un nouveau cadre juridique</div>
                </button>
                
                <button onClick={() => setAdminView('export')} className={`group p-6 md:p-8 rounded-xl border-2 border-dashed transition-all duration-300 hover:scale-105 hover:ring-2 hover:ring-amber-500/50 ${t==='dark'?'border-slate-600 hover:border-amber-500 bg-slate-800/50':'border-gray-300 hover:border-amber-500 bg-[#F0EDE7]'}`}>
                  <div className="flex justify-center mb-4">
                    <svg className={`w-12 h-12 md:w-16 md:h-16 transition-all duration-300 group-hover:scale-110 group-hover:-translate-y-2 ${t==='dark'?'text-amber-400':'text-amber-600'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M9 19l3 3m0 0l3-3m-3 3V10" />
                    </svg>
                  </div>
                  <div className={`text-base md:text-lg font-bold mb-2 ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Exporter les données</div>
                  <div className={`text-xs md:text-sm ${t==='dark'?'text-slate-400':'text-gray-600'}`}>Télécharger en CSV/JSON</div>
                </button>
                
                <button onClick={() => setAdminView('modify')} className={`group p-6 md:p-8 rounded-xl border-2 border-dashed transition-all duration-300 hover:scale-105 hover:ring-2 hover:ring-amber-500/50 ${t==='dark'?'border-slate-600 hover:border-amber-500 bg-slate-800/50':'border-gray-300 hover:border-amber-500 bg-[#F0EDE7]'}`}>
                  <div className="flex justify-center mb-4">
                    <svg className={`w-12 h-12 md:w-16 md:h-16 transition-all duration-300 group-hover:scale-110 group-hover:rotate-12 ${t==='dark'?'text-amber-400':'text-amber-600'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                    </svg>
                  </div>
                  <div className={`text-base md:text-lg font-bold mb-2 ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Modifier un cadre</div>
                  <div className={`text-xs md:text-sm ${t==='dark'?'text-slate-400':'text-gray-600'}`}>Éditer ou supprimer</div>
                </button>
              </div>
            )}

            {adminView === 'export' && (
              <div className={`rounded-xl p-6 ${t==='dark'?'bg-slate-800 border border-slate-700':'bg-[#F0EDE7] border border-gray-300'}`}>
                <div className="flex items-center justify-between mb-6">
                  <h2 className={`text-xl sm:text-2xl font-bold ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Exporter les données</h2>
                  <button onClick={() => setAdminView('main')} className={`px-4 py-2 rounded-lg text-sm sm:text-base transition-all duration-200 hover:scale-105 ${t==='dark'?'bg-slate-700 hover:bg-slate-600 text-white':'bg-gray-100 hover:bg-gray-200 text-gray-700'}`}>← Retour</button>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <button onClick={exportToCSV} className={`p-6 rounded-xl border-2 transition-all duration-300 hover:scale-105 hover:ring-2 hover:ring-amber-500/50 ${t==='dark'?'border-slate-600 hover:border-amber-500 bg-slate-700':'border-gray-300 hover:border-amber-500 bg-gray-50'}`}>
                    <div className={`text-2xl sm:text-3xl font-bold mb-2 ${t==='dark'?'text-amber-400':'text-amber-600'}`}>📄 CSV</div>
                    <div className={`text-xs sm:text-sm ${t==='dark'?'text-slate-400':'text-gray-600'}`}>Export au format tableur</div>
                  </button>
                  <button onClick={exportToJSON} className={`p-6 rounded-xl border-2 transition-all duration-300 hover:scale-105 hover:ring-2 hover:ring-amber-500/50 ${t==='dark'?'border-slate-600 hover:border-amber-500 bg-slate-700':'border-gray-300 hover:border-amber-500 bg-gray-50'}`}>
                    <div className={`text-2xl sm:text-3xl font-bold mb-2 ${t==='dark'?'text-amber-400':'text-amber-600'}`}>🔧 JSON</div>
                    <div className={`text-xs sm:text-sm ${t==='dark'?'text-slate-400':'text-gray-600'}`}>Export au format données brutes</div>
                  </button>
                </div>
              </div>
            )}

            {adminView === 'modify' && (
              <div className="space-y-6">
                <div className={`rounded-xl p-4 sm:p-6 ${t==='dark'?'bg-slate-800 border border-slate-700':'bg-[#F0EDE7] border border-gray-300'}`}>
                  <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-6">
                    <h2 className={`text-xl sm:text-2xl font-bold ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Liste des cadres juridiques ({cadresData.length})</h2>
                    <button onClick={() => setAdminView('main')} className={`px-4 py-2 rounded-lg text-sm sm:text-base transition-all duration-200 hover:scale-105 ${t==='dark'?'bg-slate-700 hover:bg-slate-600 text-white':'bg-gray-100 hover:bg-gray-200 text-gray-700'}`}>← Retour</button>
                  </div>
                  
                  <div className="space-y-3 max-h-[600px] overflow-y-auto">
                    {cadresData.map(c => (
                      <div key={c.id}>
                        <div className={`p-4 rounded-lg flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 transition-all duration-200 hover:ring-2 hover:ring-amber-500/50 ${t==='dark'?'bg-slate-700/50 hover:bg-slate-700':'bg-gray-50 hover:bg-gray-100 border border-gray-200'}`}>
                          <div className="flex-1 w-full sm:w-auto">
                            <div className={`font-bold text-sm sm:text-base mb-1 ${t==='dark'?'text-white':'text-gray-900'}`}>{c.dem}</div>
                            <div className={`text-xs sm:text-sm ${t==='dark'?'text-slate-400':'text-gray-600'}`}>{c.dom} • {c.sd}</div>
                          </div>
                          <div className="flex gap-2 w-full sm:w-auto justify-end">
                            <button type="button" onClick={(e) => {e.stopPropagation();handleEditCadre(c);}} className={`w-10 h-10 rounded-full flex items-center justify-center transition-all duration-200 hover:scale-110 hover:ring-2 hover:ring-amber-500/50 ${t==='dark'?'bg-slate-800 hover:bg-slate-600 text-amber-400':'bg-[#F0EDE7] hover:bg-[#DDD9D3] text-amber-600 border border-gray-300'}`} title="Éditer"><span className="text-lg">✏️</span></button>
                            <button type="button" onClick={(e) => {e.stopPropagation();setSel(sel?.id === c.id ? null : c);}} className={`w-10 h-10 rounded-full flex items-center justify-center transition-all duration-200 hover:scale-110 hover:ring-2 hover:ring-amber-500/50 ${t==='dark'?'bg-slate-800 hover:bg-slate-600 text-amber-400':'bg-[#F0EDE7] hover:bg-[#DDD9D3] text-amber-600 border border-gray-300'}`} title="Prévisualiser"><span className="text-lg">👁️</span></button>
                            <button onClick={() => handleDeleteCadre(c.id)} className={`w-10 h-10 rounded-full flex items-center justify-center transition-all duration-200 hover:scale-110 hover:ring-2 hover:ring-red-500/50 ${t==='dark'?'bg-red-900/30 hover:bg-red-900/50 text-red-400':'bg-red-50 hover:bg-red-100 text-red-600 border border-red-300'}`} title="Supprimer"><span className="text-lg">🗑️</span></button>
                          </div>
                        </div>
                        
                        {sel?.id === c.id && (
                          <div className={`mt-3 p-4 sm:p-6 rounded-lg border-2 ${t==='dark'?'bg-slate-800 border-amber-500':'bg-amber-50 border-amber-400'}`} style={{animation:'fadeIn 300ms'}}>
                            <div className="space-y-4">
                              <div>
                                <h4 className={`text-xs sm:text-sm font-semibold mb-2 ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Mission dévolue</h4>
                                <p className={`text-xs sm:text-sm ${t==='dark'?'text-slate-300':'text-gray-700'}`}>{c.mis}</p>
                              </div>
                              <div>
                                <h4 className={`text-xs sm:text-sm font-semibold mb-2 ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Cadre juridique</h4>
                                <ul className="space-y-1">
                                  {c.cj.map((x,i)=> {
                                    const isObject = typeof x === 'object' && x !== null;
                                    const text = isObject ? x.text : x;
                                    const url = isObject ? x.url : null;
                                    return url ? (
                                      <li key={i}><a href={url} target="_blank" rel="noopener noreferrer" className={`text-xs sm:text-sm pl-4 relative before:content-['•'] before:absolute before:left-0 before:text-amber-400 transition-all duration-200 hover:text-amber-400 ${t==='dark'?'text-slate-300':'text-gray-700'}`}>{text}</a></li>
                                    ) : (
                                      <li key={i} className={`text-xs sm:text-sm pl-4 relative before:content-['•'] before:absolute before:left-0 before:text-amber-400 ${t==='dark'?'text-slate-300':'text-gray-700'}`}>{text}</li>
                                    );
                                  })}
                                </ul>
                              </div>
                              {c.jp.length>0&&(
                                <div>
                                  <h4 className={`text-xs sm:text-sm font-semibold mb-2 ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Jurisprudence</h4>
                                  <ul>
                                    {c.jp.map((j,i)=> {
                                      const isObject = typeof j === 'object' && j !== null;
                                      const text = isObject ? j.text : j;
                                      const url = isObject ? j.url : null;
                                      return url ? (
                                        <li key={i}><a href={url} target="_blank" rel="noopener noreferrer" className={`text-xs sm:text-sm pl-4 relative before:content-['•'] before:absolute before:left-0 before:text-amber-400 transition-all duration-200 hover:text-amber-400 ${t==='dark'?'text-slate-300':'text-gray-700'}`}>{text}</a></li>
                                      ) : (
                                        <li key={i} className={`text-xs sm:text-sm pl-4 relative before:content-['•'] before:absolute before:left-0 before:text-amber-400 ${t==='dark'?'text-slate-300':'text-gray-700'}`}>{text}</li>
                                      );
                                    })}
                                  </ul>
                                </div>
                              )}
                              {c.note && (
                                <div>
                                  <h4 className={`text-xs sm:text-sm font-semibold mb-2 ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Note particulière</h4>
                                  <p className={`text-xs sm:text-sm italic ${t==='dark'?'text-slate-400':'text-gray-600'}`}>{c.note}</p>
                                </div>
                              )}
                            </div>
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            )}
          </div>
        ) : (
          <div>
            <div className="mb-6 sm:mb-8">
              <input type="text" placeholder="Rechercher..." value={s} onChange={(e)=>setS(e.target.value)} className={`w-full px-5 py-3 sm:py-4 pl-12 rounded-xl border focus:outline-none focus:border-amber-500 focus:ring-2 focus:ring-amber-500/50 transition-all duration-200 text-sm sm:text-base ${t==='dark'?'bg-slate-800/50 border-slate-700 text-white placeholder-slate-400':'bg-[#F5F2EC] border-gray-300 text-black placeholder-gray-400'}`}/>
            </div>

            <div className="mb-6">
              <div className="flex flex-wrap gap-2 sm:gap-3 mb-4">
                {doms.map(dm=>(
                  <button key={dm} onClick={()=>{setD(dm);setSd('tous');setSel(null);}} className={btnClass(d===dm)}>
                    {dm==='tous'?'Tous':dm}
                  </button>
                ))}
              </div>
              {sds.length > 0 && (
                <div className="flex flex-wrap gap-2 ml-0 sm:ml-4">
                  {sds.map(s=>(
                    <button key={s} onClick={()=>{setSd(s);setSel(null);}} className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-all duration-200 hover:scale-105 hover:ring-1 hover:ring-amber-500/50 ${sd===s?t==='dark'?'bg-amber-400/20 text-amber-400 ring-1 ring-amber-400':'bg-amber-500/20 text-amber-700 ring-1 ring-amber-500':t==='dark'?'bg-slate-800/50 text-slate-300 border border-slate-700':'bg-[#F0EDE7] text-gray-600 border border-gray-300'}`}>
                      {s==='tous'?'Tous':s}
                    </button>
                  ))}
                </div>
              )}
            </div>

            <div className={`mb-4 sm:mb-6 text-xs sm:text-sm font-medium ${t==='dark'?'text-slate-400':'text-gray-600'}`}>{filt.length} cadre{filt.length>1?'s':''}</div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {filt.map(c=>(
                <div key={c.id} onClick={()=>setSel(sel?.id===c.id?null:c)} className={`p-4 sm:p-6 rounded-xl cursor-pointer border transition-all duration-300 hover:scale-[1.02] hover:shadow-xl hover:shadow-amber-500/20 hover:ring-2 hover:ring-amber-500/50 ${sel?.id===c.id?t==='dark'?'bg-slate-800 border-amber-500 shadow-xl ring-2 ring-amber-400':'bg-amber-50 border-amber-400 ring-2 ring-amber-400':t==='dark'?'bg-slate-800/50 border-slate-700':'bg-[#F0EDE7] border-gray-300'}`}>
                  <div className="flex justify-between mb-3">
                    <span className={`px-3 py-1 rounded-full text-xs font-medium ${t==='dark'?'bg-amber-400/10 text-amber-400':'bg-amber-100 text-amber-700'}`}>{c.dom}</span>
                    <span className={`text-xl transition-transform duration-300 ${sel?.id===c.id?'rotate-180':''} ${t==='dark'?'text-slate-400':'text-gray-400'}`}>▼</span>
                  </div>
                  <h3 className={`text-base sm:text-lg font-semibold mb-2 ${t==='dark'?'text-white':'text-gray-900'}`}>{c.dem}</h3>
                  <p className={`text-xs sm:text-sm ${t==='dark'?'text-slate-300':'text-gray-600'}`}>{c.sd}</p>
                  {sel?.id===c.id&&(
                    <div className={`mt-4 pt-4 border-t space-y-4 ${t==='dark'?'border-slate-700':'border-gray-200'}`} style={{animation:'fadeIn 300ms'}}>
                      <div>
                        <div className="flex items-center justify-between mb-2">
                          <h4 className={`text-xs sm:text-sm font-semibold ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Mission dévolue</h4>
                          <button 
                            onClick={(e) => {
                              e.stopPropagation();
                              navigator.clipboard.writeText(c.mis).then(() => {
                                setCopiedMissionId(c.id);
                                setTimeout(() => setCopiedMissionId(null), 1500);
                              }).catch(err => {
                                console.error('Erreur copie:', err);
                                alert('⚠️ Impossible de copier dans le presse-papiers');
                              });
                            }}
                            className={`px-2 py-1.5 rounded transition-all duration-200 hover:scale-110 active:scale-95 ${
                              copiedMissionId === c.id
                                ? 'bg-green-500 text-white'
                                : t==='dark'
                                  ? 'bg-slate-700 hover:bg-slate-600 text-amber-400'
                                  : 'bg-gray-100 hover:bg-gray-200 text-amber-600'
                            }`}
                            title="Copier la mission dévolue"
                          >
                            {copiedMissionId === c.id ? (
                              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth="2.5">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
                              </svg>
                            ) : (
                              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth="2">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
                              </svg>
                            )}
                          </button>
                        </div>
                        <p className={`text-xs sm:text-sm ${t==='dark'?'text-slate-300':'text-gray-700'}`}>{c.mis}</p>
                      </div>
                      <div>
                        <h4 className={`text-xs sm:text-sm font-semibold mb-2 ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Cadre juridique</h4>
                        <ul className="space-y-1">
                          {c.cj.map((x,i)=> {
                            const isObject = typeof x === 'object' && x !== null;
                            const text = isObject ? x.text : x;
                            const url = isObject ? x.url : null;
                            
                            return url ? (
                              <li key={i}>
                                <a 
                                  href={url} 
                                  target="_blank" 
                                  rel="noopener noreferrer"
                                  className={`text-xs sm:text-sm pl-4 relative before:content-['•'] before:absolute before:left-0 before:text-amber-400 transition-all duration-200 hover:text-amber-400 underline cursor-pointer ${t==='dark'?'text-slate-300':'text-gray-700'}`}
                                >
                                  {text}
                                </a>
                              </li>
                            ) : (
                              <li key={i} className={`text-xs sm:text-sm pl-4 relative before:content-['•'] before:absolute before:left-0 before:text-amber-400 ${t==='dark'?'text-slate-300':'text-gray-700'}`}>{text}</li>
                            );
                          })}
                        </ul>
                      </div>
                      {c.jp.length>0&&(
                        <div>
                          <h4 className={`text-xs sm:text-sm font-semibold mb-2 ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Jurisprudence</h4>
                          <ul>
                            {c.jp.map((j,i)=> {
                              const isObject = typeof j === 'object' && j !== null;
                              const text = isObject ? j.text : j;
                              const url = isObject ? j.url : null;
                              
                              return url ? (
                                <li key={i}>
                                  <a 
                                    href={url} 
                                    target="_blank" 
                                    rel="noopener noreferrer"
                                    className={`text-xs sm:text-sm pl-4 relative before:content-['•'] before:absolute before:left-0 before:text-amber-400 transition-all duration-200 hover:text-amber-400 underline cursor-pointer ${t==='dark'?'text-slate-300':'text-gray-700'}`}
                                  >
                                    {text}
                                  </a>
                                </li>
                              ) : (
                                <li key={i} className={`text-xs sm:text-sm pl-4 relative before:content-['•'] before:absolute before:left-0 before:text-amber-400 ${t==='dark'?'text-slate-300':'text-gray-700'}`}>{text}</li>
                              );
                            })}
                          </ul>
                        </div>
                      )}
                      {c.note && (
                        <div>
                          <h4 className={`text-xs sm:text-sm font-semibold mb-2 ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Note particulière</h4>
                          <p className={`text-xs sm:text-sm italic ${t==='dark'?'text-slate-400':'text-gray-600'}`}>{c.note}</p>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}
      </main>

      {showLoginModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4" style={{background: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(8px)'}}>
          <div className={`w-full max-w-md rounded-3xl shadow-2xl overflow-hidden ${t==='dark'?'bg-gradient-to-br from-slate-800 via-slate-900 to-slate-800':'bg-gradient-to-br from-[#F5F2EC] via-white to-[#F5F2EC]'}`} style={{animation: 'fadeIn 400ms, slideUp 400ms'}}>
            <div className={`relative p-6 sm:p-8 text-center ${t==='dark'?'bg-gradient-to-r from-amber-500/10 to-amber-600/10':'bg-gradient-to-r from-amber-100 to-amber-50'}`}>
              <div className="absolute inset-0 opacity-10">
                <div className="absolute top-0 left-0 w-32 h-32 bg-amber-400 rounded-full blur-3xl animate-pulse"></div>
                <div className="absolute bottom-0 right-0 w-32 h-32 bg-amber-500 rounded-full blur-3xl animate-pulse" style={{animationDelay: '1s'}}></div>
              </div>
              <div className="relative">
                <div className="inline-block mb-4 animate-bounce" style={{animationDuration: '2s'}}>
                  <L className="w-16 sm:w-20 h-16 sm:h-20 drop-shadow-2xl"/>
                </div>
                <h2 className={`text-2xl sm:text-3xl font-bold mb-2 ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Espace Administrateur</h2>
                <p className={`text-xs sm:text-sm ${t==='dark'?'text-slate-400':'text-gray-600'}`}>Authentification sécurisée requise</p>
              </div>
            </div>
            <form onSubmit={handleLogin} className="p-6 sm:p-8 space-y-6">
              <div className="space-y-2">
                <label className={`block text-sm font-bold ${t==='dark'?'text-amber-400':'text-amber-600'}`}>🔐 Mot de passe</label>
                <div className="relative">
                  <input type="password" value={loginPassword} onChange={(e) => { setLoginPassword(e.target.value); setLoginError(''); }} className={`w-full px-5 py-3 sm:py-4 rounded-xl border-2 focus:outline-none focus:ring-4 focus:ring-amber-500/30 transition-all text-base sm:text-lg ${t==='dark'?'bg-slate-800 border-slate-700 text-white focus:border-amber-500':'bg-white border-gray-300 text-black focus:border-amber-500'}`} placeholder="Entrez votre mot de passe" autoFocus required />
                  <div className="absolute right-4 top-1/2 transform -translate-y-1/2">
                    <svg className={`w-5 h-5 sm:w-6 sm:h-6 ${t==='dark'?'text-slate-600':'text-gray-400'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/>
                    </svg>
                  </div>
                </div>
                {loginError && (
                  <div className={`p-3 rounded-lg text-xs sm:text-sm font-medium ${t==='dark'?'bg-red-900/30 text-red-400 border border-red-500/30':'bg-red-50 text-red-600 border border-red-200'}`} style={{animation: 'shake 400ms'}}>⚠️ {loginError}</div>
                )}
              </div>
              <div className="flex flex-col sm:flex-row items-center gap-3 pt-2">
                <button type="button" onClick={() => { setShowLoginModal(false); setLoginPassword(''); setLoginError(''); }} className={`w-full sm:flex-1 px-6 py-3 sm:py-4 rounded-xl font-bold text-sm sm:text-base transition-all duration-200 hover:scale-105 active:scale-95 ${t==='dark'?'bg-slate-700 hover:bg-slate-600 text-white':'bg-gray-200 hover:bg-gray-300 text-gray-700'}`}>Annuler</button>
                <button type="submit" className={`w-full sm:flex-1 px-6 py-3 sm:py-4 rounded-xl font-bold text-sm sm:text-base transition-all duration-200 hover:scale-105 active:scale-95 flex items-center justify-center gap-2 shadow-xl ${t==='dark'?'bg-gradient-to-r from-amber-500 to-amber-600 hover:from-amber-600 hover:to-amber-700 text-slate-900':'bg-gradient-to-r from-amber-500 to-amber-600 hover:from-amber-600 hover:to-amber-700 text-white'}`}>
                  <svg className="w-4 h-4 sm:w-5 sm:h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 11V7a4 4 0 118 0m-4 8v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z"/>
                  </svg>
                  Connexion
                </button>
              </div>
            </form>
            <div className={`px-6 sm:px-8 py-4 text-center border-t ${t==='dark'?'bg-slate-900/50 border-slate-700':'bg-amber-50/50 border-amber-200'}`}>
              <p className={`text-xs ${t==='dark'?'text-slate-500':'text-gray-500'}`}>🛡️ Connexion sécurisée par ONARP</p>
            </div>
          </div>
        </div>
      )}

      {showEditModal && (editingCadre || isAddingNew) && (
        <div className="fixed inset-0 z-50 bg-black/50 backdrop-blur-sm flex items-start justify-center overflow-y-auto p-4 pt-8">
          <div className={`w-full max-w-4xl rounded-2xl shadow-2xl my-8 ${t==='dark'?'bg-slate-800 border-2 border-slate-700':'bg-[#F0EDE7] border-2 border-gray-300'}`} onClick={(e) => e.stopPropagation()}>
            <div className={`p-4 sm:p-6 border-b ${t==='dark'?'bg-slate-800 border-slate-700':'bg-[#F0EDE7] border-gray-300'}`}>
              <div className="flex items-center justify-between">
                <h3 className={`text-lg sm:text-2xl font-bold ${t==='dark'?'text-amber-400':'text-amber-600'}`}>
                  {isAddingNew ? 'Ajouter un cadre juridique' : 'Éditer le cadre juridique'}
                </h3>
                <button onClick={() => { setShowEditModal(false); setIsCreatingDomain(false); setIsCreatingSubdomain(false); setCustomDomain(''); setCustomSubdomain(''); }} className={`w-8 h-8 sm:w-10 sm:h-10 rounded-full flex items-center justify-center transition-all duration-200 hover:scale-110 hover:ring-2 hover:ring-red-500/50 ${t==='dark'?'bg-slate-700 hover:bg-red-900/50 text-red-400':'bg-gray-100 hover:bg-red-50 text-red-600'}`}>
                  <span className="text-xl">✕</span>
                </button>
              </div>
            </div>

            <div className="p-4 sm:p-6 space-y-4 sm:space-y-6 max-h-[70vh] overflow-y-auto">
              <div>
                <label className={`block text-xs sm:text-sm font-semibold mb-2 ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Domaine juridique *</label>
                {!isCreatingDomain ? (
                  <select value={formData.dom} onChange={(e) => { if (e.target.value === '__new__') { setIsCreatingDomain(true); setFormData({...formData, dom: '', sd: ''}); setCustomDomain(''); } else { setFormData({...formData, dom: e.target.value, sd: ''}); } }} className={`w-full px-3 sm:px-4 py-2 sm:py-3 rounded-lg border text-sm sm:text-base focus:outline-none focus:ring-2 focus:ring-amber-500/50 transition-all ${t==='dark'?'bg-slate-700 border-slate-600 text-white':'bg-[#F5F2EC] border-gray-300 text-black'}`}>
                    <option value="">Sélectionner un domaine</option>
                    {modalDomains.map(d => (
                      <option key={d} value={d}>{d}</option>
                    ))}
                    <option value="__new__">+ Créer un nouveau domaine</option>
                  </select>
                ) : (
                  <div className="flex gap-2">
                    <input type="text" value={customDomain} onChange={(e) => setCustomDomain(e.target.value)} placeholder="Ex: Droit administratif" className={`flex-1 px-3 sm:px-4 py-2 sm:py-3 rounded-lg border text-sm sm:text-base focus:outline-none focus:ring-2 focus:ring-amber-500/50 transition-all ${t==='dark'?'bg-slate-700 border-slate-600 text-white placeholder-slate-400':'bg-[#F5F2EC] border-gray-300 text-black placeholder-gray-400'}`} />
                    <button onClick={() => { setIsCreatingDomain(false); setCustomDomain(''); }} className={`px-3 sm:px-4 py-2 sm:py-3 rounded-lg font-medium transition-all duration-200 hover:scale-105 ${t==='dark'?'bg-slate-600 hover:bg-slate-500 text-white':'bg-gray-200 hover:bg-gray-300 text-gray-700'}`} title="Annuler">✕</button>
                  </div>
                )}
              </div>

              <div>
                <label className={`block text-xs sm:text-sm font-semibold mb-2 ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Sous-domaine juridique *</label>
                {!isCreatingSubdomain ? (
                  <select value={formData.sd} onChange={(e) => { if (e.target.value === '__new__') { setIsCreatingSubdomain(true); setFormData({...formData, sd: ''}); setCustomSubdomain(''); } else { setFormData({...formData, sd: e.target.value}); } }} disabled={!formData.dom && !isCreatingDomain} className={`w-full px-3 sm:px-4 py-2 sm:py-3 rounded-lg border text-sm sm:text-base focus:outline-none focus:ring-2 focus:ring-amber-500/50 transition-all ${(!formData.dom && !isCreatingDomain) ? 'opacity-50 cursor-not-allowed' : ''} ${t==='dark'?'bg-slate-700 border-slate-600 text-white':'bg-[#F5F2EC] border-gray-300 text-black'}`}>
                    <option value="">Sélectionner un sous-domaine</option>
                    {modalSubdomains.map(s => (
                      <option key={s} value={s}>{s}</option>
                    ))}
                    <option value="__new__">+ Créer un nouveau sous-domaine</option>
                  </select>
                ) : (
                  <div className="flex gap-2">
                    <input type="text" value={customSubdomain} onChange={(e) => setCustomSubdomain(e.target.value)} placeholder="Ex: Contentieux administratif" className={`flex-1 px-3 sm:px-4 py-2 sm:py-3 rounded-lg border text-sm sm:text-base focus:outline-none focus:ring-2 focus:ring-amber-500/50 transition-all ${t==='dark'?'bg-slate-700 border-slate-600 text-white placeholder-slate-400':'bg-[#F5F2EC] border-gray-300 text-black placeholder-gray-400'}`} />
                    <button onClick={() => { setIsCreatingSubdomain(false); setCustomSubdomain(''); }} className={`px-3 sm:px-4 py-2 sm:py-3 rounded-lg font-medium transition-all duration-200 hover:scale-105 ${t==='dark'?'bg-slate-600 hover:bg-slate-500 text-white':'bg-gray-200 hover:bg-gray-300 text-gray-700'}`} title="Annuler">✕</button>
                  </div>
                )}
              </div>

              <div>
                <label className={`block text-xs sm:text-sm font-semibold mb-2 ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Titre du cadre (Demande usuelle client) *</label>
                <input type="text" value={formData.dem} onChange={(e) => setFormData({...formData, dem: e.target.value})} className={`w-full px-3 sm:px-4 py-2 sm:py-3 rounded-lg border text-sm sm:text-base focus:outline-none focus:ring-2 focus:ring-amber-500/50 transition-all ${t==='dark'?'bg-slate-700 border-slate-600 text-white':'bg-[#F5F2EC] border-gray-300 text-black'}`} placeholder="Ex: Infidélité dans un concubinage" />
              </div>

              <div>
                <label className={`block text-xs sm:text-sm font-semibold mb-2 ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Mission dévolue *</label>
                <textarea value={formData.mis} onChange={(e) => setFormData({...formData, mis: e.target.value})} rows={3} className={`w-full px-3 sm:px-4 py-2 sm:py-3 rounded-lg border text-sm sm:text-base focus:outline-none focus:ring-2 focus:ring-amber-500/50 transition-all ${t==='dark'?'bg-slate-700 border-slate-600 text-white':'bg-[#F5F2EC] border-gray-300 text-black'}`} placeholder="Ex: Suspicion d'un fait constitutif d'infidélité..." />
              </div>

              <div>
                <div className="flex items-center justify-between mb-3">
                  <label className={`text-xs sm:text-sm font-semibold ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Cadres juridiques (optionnel)</label>
                  <button onClick={addCjItem} className={`px-3 py-1.5 rounded-lg text-xs sm:text-sm font-medium transition-all duration-200 hover:scale-105 ${t==='dark'?'bg-slate-700 hover:bg-slate-600 text-amber-400':'bg-amber-50 hover:bg-amber-100 text-amber-600'}`}>+ Ajouter</button>
                </div>
                <div className="space-y-3">
                  {formData.cj.map((item, index) => (
                    <div key={index} className={`p-3 sm:p-4 rounded-lg border ${t==='dark'?'bg-slate-700/50 border-slate-600':'bg-gray-50 border-gray-200'}`}>
                      <div className="flex items-start gap-2 mb-2">
                        <div className="flex flex-col gap-1">
                          <button onClick={() => moveCjItem(index, 'up')} disabled={index === 0} className={`w-6 h-6 rounded flex items-center justify-center text-xs transition-all ${index === 0 ? 'opacity-30 cursor-not-allowed' : 'hover:bg-slate-600'} ${t==='dark'?'text-slate-400':'text-gray-400'}`}>▲</button>
                          <button onClick={() => moveCjItem(index, 'down')} disabled={index === formData.cj.length - 1} className={`w-6 h-6 rounded flex items-center justify-center text-xs transition-all ${index === formData.cj.length - 1 ? 'opacity-30 cursor-not-allowed' : 'hover:bg-slate-600'} ${t==='dark'?'text-slate-400':'text-gray-400'}`}>▼</button>
                        </div>
                        <div className="flex-1 space-y-2">
                          <input type="text" value={item.text} onChange={(e) => updateCjItem(index, 'text', e.target.value)} className={`w-full px-2 sm:px-3 py-1.5 sm:py-2 rounded border text-xs sm:text-sm focus:outline-none focus:ring-2 focus:ring-amber-500/50 ${t==='dark'?'bg-slate-800 border-slate-500 text-white':'bg-[#F5F2EC] border-gray-300 text-black'}`} placeholder="Ex: Art. 515.8 du Code civil" />
                          <input type="url" value={item.url} onChange={(e) => updateCjItem(index, 'url', e.target.value)} className={`w-full px-2 sm:px-3 py-1.5 sm:py-2 rounded border text-xs sm:text-sm focus:outline-none focus:ring-2 focus:ring-amber-500/50 ${t==='dark'?'bg-slate-800 border-slate-500 text-white':'bg-[#F5F2EC] border-gray-300 text-black'}`} placeholder="URL (optionnel)" />
                        </div>
                        <button onClick={() => removeCjItem(index)} className={`w-8 h-8 rounded flex items-center justify-center transition-all hover:scale-110 ${t==='dark'?'text-red-400 hover:bg-red-900/30':'text-red-600 hover:bg-red-50'}`}>🗑️</button>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              <div>
                <div className="flex items-center justify-between mb-3">
                  <label className={`text-xs sm:text-sm font-semibold ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Jurisprudences (optionnel)</label>
                  <button onClick={addJpItem} className={`px-3 py-1.5 rounded-lg text-xs sm:text-sm font-medium transition-all duration-200 hover:scale-105 ${t==='dark'?'bg-slate-700 hover:bg-slate-600 text-amber-400':'bg-amber-50 hover:bg-amber-100 text-amber-600'}`}>+ Ajouter</button>
                </div>
                <div className="space-y-3">
                  {formData.jp.map((item, index) => (
                    <div key={index} className={`p-3 sm:p-4 rounded-lg border ${t==='dark'?'bg-slate-700/50 border-slate-600':'bg-gray-50 border-gray-200'}`}>
                      <div className="flex items-start gap-2 mb-2">
                        <div className="flex flex-col gap-1">
                          <button onClick={() => moveJpItem(index, 'up')} disabled={index === 0} className={`w-6 h-6 rounded flex items-center justify-center text-xs transition-all ${index === 0 ? 'opacity-30 cursor-not-allowed' : 'hover:bg-slate-600'} ${t==='dark'?'text-slate-400':'text-gray-400'}`}>▲</button>
                          <button onClick={() => moveJpItem(index, 'down')} disabled={index === formData.jp.length - 1} className={`w-6 h-6 rounded flex items-center justify-center text-xs transition-all ${index === formData.jp.length - 1 ? 'opacity-30 cursor-not-allowed' : 'hover:bg-slate-600'} ${t==='dark'?'text-slate-400':'text-gray-400'}`}>▼</button>
                        </div>
                        <div className="flex-1 space-y-2">
                          <input type="text" value={item.text} onChange={(e) => updateJpItem(index, 'text', e.target.value)} className={`w-full px-2 sm:px-3 py-1.5 sm:py-2 rounded border text-xs sm:text-sm focus:outline-none focus:ring-2 focus:ring-amber-500/50 ${t==='dark'?'bg-slate-800 border-slate-500 text-white':'bg-[#F5F2EC] border-gray-300 text-black'}`} placeholder="Ex: JP Civ. 30 mai 1838..." />
                          <input type="url" value={item.url} onChange={(e) => updateJpItem(index, 'url', e.target.value)} className={`w-full px-2 sm:px-3 py-1.5 sm:py-2 rounded border text-xs sm:text-sm focus:outline-none focus:ring-2 focus:ring-amber-500/50 ${t==='dark'?'bg-slate-800 border-slate-500 text-white':'bg-[#F5F2EC] border-gray-300 text-black'}`} placeholder="URL (optionnel)" />
                        </div>
                        <button onClick={() => removeJpItem(index)} className={`w-8 h-8 rounded flex items-center justify-center transition-all hover:scale-110 ${t==='dark'?'text-red-400 hover:bg-red-900/30':'text-red-600 hover:bg-red-50'}`}>🗑️</button>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              <div>
                <label className={`block text-xs sm:text-sm font-semibold mb-2 ${t==='dark'?'text-amber-400':'text-amber-600'}`}>Note particulière (optionnel)</label>
                <textarea value={formData.note} onChange={(e) => setFormData({...formData, note: e.target.value})} rows={2} className={`w-full px-3 sm:px-4 py-2 sm:py-3 rounded-lg border text-sm sm:text-base focus:outline-none focus:ring-2 focus:ring-amber-500/50 transition-all ${t==='dark'?'bg-slate-700 border-slate-600 text-white':'bg-[#F5F2EC] border-gray-300 text-black'}`} placeholder="Ajouter une note interne..." />
              </div>
            </div>

            <div className={`p-4 sm:p-6 border-t flex flex-col sm:flex-row items-center justify-end gap-3 sm:gap-4 ${t==='dark'?'bg-slate-800 border-slate-700':'bg-[#F0EDE7] border-gray-300'}`}>
              <button onClick={() => { setShowEditModal(false); setIsCreatingDomain(false); setIsCreatingSubdomain(false); setCustomDomain(''); setCustomSubdomain(''); }} className={`w-full sm:w-auto px-6 py-2.5 sm:py-3 rounded-lg font-medium text-sm sm:text-base transition-all duration-200 hover:scale-105 ${t==='dark'?'bg-slate-700 hover:bg-slate-600 text-white':'bg-gray-100 hover:bg-gray-200 text-gray-700'}`}>Annuler</button>
              <button onClick={handleSaveCadre} className={`w-full sm:w-auto px-6 py-2.5 sm:py-3 rounded-lg font-medium text-sm sm:text-base transition-all duration-200 hover:scale-105 flex items-center justify-center gap-2 ${t==='dark'?'bg-amber-500 hover:bg-amber-600 text-slate-900':'bg-amber-500 hover:bg-amber-600 text-white'}`}>
                <span className="text-xl">💾</span>
                Sauvegarder
              </button>
            </div>
          </div>
        </div>
      )}

      {showDeleteConfirm && cadreToDelete && (
        <div className="fixed inset-0 z-50 bg-black/50 backdrop-blur-sm flex items-center justify-center p-4">
          <div className={`w-full max-w-md rounded-2xl shadow-2xl overflow-hidden ${t==='dark'?'bg-slate-800 border-2 border-red-500':'bg-[#F0EDE7] border-2 border-red-400'}`}>
            <div className={`p-4 sm:p-6 border-b ${t==='dark'?'bg-slate-800 border-slate-700':'bg-[#F0EDE7] border-gray-300'}`}>
              <h3 className={`text-lg sm:text-xl font-bold ${t==='dark'?'text-red-400':'text-red-600'}`}>⚠️ Suppression définitive</h3>
            </div>
            <div className="p-4 sm:p-6 space-y-4">
              <p className={`text-sm sm:text-base ${t==='dark'?'text-white':'text-gray-900'}`}>Êtes-vous sûr de vouloir supprimer ce cadre juridique ?</p>
              <div className={`p-4 rounded-lg ${t==='dark'?'bg-slate-700':'bg-gray-100'}`}>
                <p className={`font-bold text-xs sm:text-sm ${t==='dark'?'text-white':'text-gray-900'}`}>{cadreToDelete.dem}</p>
                <p className={`text-xs sm:text-sm mt-1 ${t==='dark'?'text-slate-400':'text-gray-600'}`}>{cadreToDelete.dom}</p>
              </div>
              <p className={`text-xs sm:text-sm font-bold ${t==='dark'?'text-red-400':'text-red-600'}`}>⚠️ Cette action est irréversible</p>
            </div>
            <div className={`p-4 sm:p-6 border-t flex flex-col sm:flex-row items-center justify-end gap-3 sm:gap-4 ${t==='dark'?'bg-slate-800 border-slate-700':'bg-[#F0EDE7] border-gray-300'}`}>
              <button onClick={cancelDelete} className={`w-full sm:w-auto px-6 py-2.5 sm:py-3 rounded-lg font-medium text-sm sm:text-base transition-all duration-200 hover:scale-105 ${t==='dark'?'bg-slate-700 hover:bg-slate-600 text-white':'bg-gray-100 hover:bg-gray-200 text-gray-700'}`}>Annuler</button>
              <button onClick={confirmDelete} className={`w-full sm:w-auto px-6 py-2.5 sm:py-3 rounded-lg font-medium text-sm sm:text-base transition-all duration-200 hover:scale-105 flex items-center justify-center gap-2 bg-red-600 hover:bg-red-700 text-white`}>
                <span className="text-xl">🗑️</span>
                Supprimer
              </button>
            </div>
          </div>
        </div>
      )}

      <footer className={`mt-12 sm:mt-16 py-6 sm:py-8 border-t text-center ${t==='dark'?'border-slate-700 text-slate-500':'border-gray-200 text-gray-500'}`}>
        <p className="text-xs sm:text-sm font-medium">© ONARP 2026 | Version 1.0</p>
        <p className="text-xs sm:text-sm mt-2">Outil d'aide à la détermination du cadre juridique</p>
        <p className="text-xs mt-3">Propulsé par <a href="https://verum-investigation.fr" target="_blank" rel="noopener noreferrer" className={`font-bold transition-colors hover:text-amber-400 ${t==='dark'?'hover:text-amber-400':'hover:text-amber-600'}`}>verum investigation</a></p>
      </footer>

      {showScrollTop && (
        <button onClick={scrollToTop} className={`fixed bottom-6 sm:bottom-8 right-6 sm:right-8 w-10 h-10 sm:w-12 sm:h-12 rounded-full transition-all duration-300 hover:scale-110 hover:ring-2 hover:ring-amber-500/50 hover:shadow-lg hover:shadow-amber-500/30 hover:-translate-y-1 flex items-center justify-center z-40 ${t==='dark'?'bg-slate-800 hover:bg-slate-700 border-2 border-slate-700':'bg-[#F0EDE7] hover:bg-[#DDD9D3] border-2 border-gray-300'}`} style={{animation: 'fadeIn 300ms'}}>
          <svg className={`w-5 h-5 sm:w-6 sm:h-6 ${t==='dark'?'text-amber-400':'text-amber-600'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 10l7-7m0 0l7 7m-7-7v18" />
          </svg>
        </button>
      )}

      <style>{`
        @keyframes fadeIn { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } }
        @keyframes slideUp { from { transform: translateY(20px) scale(0.95); } to { transform: translateY(0) scale(1); } }
        @keyframes shake { 0%, 100% { transform: translateX(0); } 25% { transform: translateX(-10px); } 75% { transform: translateX(10px); } }
        @keyframes ripple-wave { 0% { width: 0px; height: 0px; opacity: 0.8; } 100% { width: 100px; height: 100px; opacity: 0; } }
        .animate-ripple-wave { animation: ripple-wave 1500ms ease-out forwards; }
        button:hover, a:hover, [role="button"]:hover, input[type="text"]:hover, .cursor-pointer:hover { box-shadow: 0 0 20px rgba(251, 191, 36, 0.3); }
      `}</style>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
