// src/components/Dashboard.jsx

const QUIZZES = [
  {
    id: "q1",
    imageKey: "Q1.jpeg",
    title: { it: "Harmonised compliance", en: "Harmonised compliance" },
    description: {
      it: "Valuta il livello di maturità dei sistemi di governance e l'integrazione multidisciplinare dei processi aziendali.",
      en: "Assess the maturity level of governance systems and the multidisciplinary integration of business processes."
    },
    duration: "5 min"
  },
  {
    id: "q2",
    imageKey: "Q2.png",
    title: { it: "OT Resilience & Integrity", en: "OT Resilience & Integrity" },
    description: {
      it: "Analisi approfondita della sicurezza, segregazione e integrità dei dati nei sistemi industriali e di produzione (PLC/SCADA).",
      en: "Deep dive analysis of security, segregation, and data integrity in industrial and production systems (PLC/SCADA)."
    },
    duration: "5 min"
  },
  {
    id: "q3",
    imageKey: "Q3.png",
    title: { it: "ESG & CSR", en: "ESG & CSR" },
    description: {
      it: "Misura la sostenibilità aziendale, l'impatto ambientale e la responsabilità sociale d'impresa secondo i framework vigenti.",
      en: "Measure corporate sustainability, environmental impact, and corporate social responsibility according to current frameworks."
    },
    duration: "5 min"
  },
  {
    id: "q4",
    imageKey: "Q4.png",
    title: { it: "Digital Validation", en: "Digital Validation" },
    description: {
      it: "Verifica l'efficacia dei protocolli di convalida software, infrastrutture cloud e approcci basati sul rischio (CSA/GxP).",
      en: "Verify the effectiveness of software validation protocols, cloud infrastructures, and risk-based approaches (CSA/GxP)."
    },
    duration: "5 min"
  },
  {
    id: "q5",
    imageKey: "Q5.png",
    title: { it: "Intelligenza Artificiale", en: "Artificial Intelligence" },
    description: {
      it: "Valutazione dei sistemi di Intelligenza Artificiale e Machine Learning, tracciabilità ALCOA+ e protocolli di supervisione umana.",
      en: "Evaluation of Artificial Intelligence and Machine Learning systems, ALCOA+ traceability, and human oversight protocols."
    },
    duration: "5 min"
  }
];

function Dashboard({ user = {}, onSelectQuiz }) {
  const urlParams = new URLSearchParams(window.location.search);
  const isCollegaView = urlParams.get('view') === 'lead';
  
  const langConfig = (window.APP_LANGUAGE_MODE || 'all').toLowerCase();
  const lang = (urlParams.get('lang') || user?.language || (langConfig === 'en' || langConfig === 'it' ? langConfig : 'it')).toLowerCase();

  const [leads, setLeads] = React.useState([]);
  const [isAuthenticated, setIsAuthenticated] = React.useState(false);
  const [password, setPassword] = React.useState("");

  const [selectedQuizFilter, setSelectedQuizFilter] = React.useState("all");
  const [sortByScore, setSortByScore] = React.useState("latest");

  React.useEffect(() => {
    if (!isCollegaView || !isAuthenticated) return;

    if (!window.firebase || !window.firebase.firestore) {
      console.error("Firebase SDK non disponibile.");
      return;
    }

    const db = window.firebase.firestore();
    const unsubscribe = db.collection("lead_fiera_2026")
      .orderBy("createdAt", "desc")
      .onSnapshot((snapshot) => {
        const docs = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
        setLeads(docs);
      }, (err) => console.error("Errore Firestore:", err));

    return () => unsubscribe();
  }, [isAuthenticated, isCollegaView]);

  const texts = {
    it: {
      welcome: "Mettiti alla prova!",
      subtitle: "Seleziona uno dei seguenti assessment per iniziare la tua valutazione specialistica.",
      startBtn: "Inizia Questionario"
    },
    en: {
      welcome: "Challenge yourself!",
      subtitle: "Select one of the following assessments to start your specialized evaluation.",
      startBtn: "Start Quiz"
    }
  };

  const handleLogin = (e) => {
    e.preventDefault();
    if (password === "AFI2026!") {
      setIsAuthenticated(true);
    } else {
      alert("Password errata!");
    }
  };

  const scaricaPDFCertificato = (lead) => {
    const finestraStampa = window.open('', '_blank');
    const htmlFinale = window.generaHtmlCertificato(lead);
    
    finestraStampa.document.write(htmlFinale);
    finestraStampa.document.write(`
      <script>
        window.onload = function() { 
          setTimeout(function() { window.print(); window.close(); }, 450);
        }
      </script>
    `);
    finestraStampa.document.close();
  };

  const filteredAndSortedLeads = React.useMemo(() => {
    let result = [...leads];

    if (selectedQuizFilter !== "all") {
      result = result.filter(l => l.quizId === selectedQuizFilter);
    }

    if (sortByScore === "score_desc") {
      result.sort((a, b) => (Number(b.score) || 0) - (Number(a.score) || 0));
    } else if (sortByScore === "score_asc") {
      result.sort((a, b) => (Number(a.score) || 0) - (Number(b.score) || 0));
    }

    return result;
  }, [leads, selectedQuizFilter, sortByScore]);

  // VISTA LIVE LEADS CON DETTAGLIO RISPOSTE (ADMIN)
  if (isCollegaView) {
    if (!isAuthenticated) {
      return (
        <div className="min-h-screen flex items-center justify-center bg-slate-50 text-slate-900 p-4">
          <form onSubmit={handleLogin} className="max-w-sm w-full bg-white p-8 rounded-2xl border border-slate-200 space-y-4 shadow-xl">
            <h2 className="text-2xl font-bold text-indigo-600 tracking-tight text-center">Dashboard Live Lead</h2>
            <p className="text-xs text-slate-500 text-center !mt-1">Inserisci le credenziali del padiglione</p>
            <input 
              type="password" 
              placeholder="Password Stand" 
              value={password} 
              onChange={(e) => setPassword(e.target.value)}
              className="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl text-slate-900 focus:outline-none focus:border-indigo-500 focus:bg-white text-sm transition-all"
            />
            <button type="submit" className="w-full p-3 bg-indigo-600 hover:bg-indigo-700 rounded-xl font-bold text-sm text-white shadow-md shadow-indigo-600/10 cursor-pointer transition-all">Accedi</button>
          </form>
        </div>
      );
    }

    return (
      <div className="min-h-screen bg-slate-50 text-slate-900 p-6 lg:p-10">
        <div className="max-w-7xl mx-auto space-y-6">
          <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
            <div>
              <h1 className="text-3xl font-extrabold text-slate-900 tracking-tight">Anagrafiche Fiera</h1>
              <p className="text-sm text-slate-500 mt-1">
                Lead visibili: <span className="text-indigo-600 font-bold font-mono text-base">{filteredAndSortedLeads.length}</span> su {leads.length} totali
              </p>
            </div>
            <span className="text-xs bg-emerald-500/10 text-emerald-600 border border-emerald-500/20 px-3 py-1.5 rounded-full font-mono font-bold flex items-center gap-1.5 shadow-sm">
              <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></span> COLLEGATO LIVE
            </span>
          </div>

          <div className="bg-white border border-slate-200 p-4 rounded-2xl shadow-sm flex flex-col md:flex-row gap-4 items-center justify-between">
            <div className="flex items-center gap-3 w-full md:w-auto">
              <label className="text-xs font-bold uppercase tracking-wider text-slate-500 whitespace-nowrap">Filtra per Quiz:</label>
              <select
                value={selectedQuizFilter}
                onChange={(e) => setSelectedQuizFilter(e.target.value)}
                className="bg-slate-50 border border-slate-200 text-slate-800 text-sm rounded-xl px-3 py-2 focus:outline-none focus:border-indigo-500 cursor-pointer w-full md:w-auto"
              >
                <option value="all">Tutti i Questionari</option>
                {QUIZZES.map(q => (
                  <option key={q.id} value={q.id}>{q.title.it}</option>
                ))}
              </select>
            </div>

            <div className="flex items-center gap-3 w-full md:w-auto">
              <label className="text-xs font-bold uppercase tracking-wider text-slate-500 whitespace-nowrap">Ordina Punteggio:</label>
              <select
                value={sortByScore}
                onChange={(e) => setSortByScore(e.target.value)}
                className="bg-slate-50 border border-slate-200 text-slate-800 text-sm rounded-xl px-3 py-2 focus:outline-none focus:border-indigo-500 cursor-pointer w-full md:w-auto"
              >
                <option value="latest">⏱️ Più recenti (Default)</option>
                <option value="score_desc">🥇 Punteggio più alto (Decrescente)</option>
                <option value="score_asc">🥉 Punteggio più basso (Crescente)</option>
              </select>
            </div>
          </div>
          
          <div className="bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-md">
            <div className="overflow-x-auto">
              <table className="w-full text-left border-collapse">
                <thead>
                  <tr className="bg-slate-50 border-b border-slate-200 text-slate-600 text-xs font-bold uppercase tracking-wider">
                    <th className="p-4 w-20">Orario</th>
                    <th className="p-4 w-1/4">Anagrafica</th>
                    <th className="p-4 w-1/4">Contatti</th>
                    <th className="p-4 w-1/3">Dettaglio Domande & Risposte Scelte</th>
                    <th className="p-4 text-center">Score</th>
                    <th className="p-4 text-center w-24">Certificato</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100 text-sm">
                  {filteredAndSortedLeads.map((l) => (
                    <tr key={l.id} className="hover:bg-slate-50/60 transition-colors align-top">
                      <td className="p-4 font-mono text-slate-400 whitespace-nowrap pt-5">
                        {l.createdAt?.toDate 
                          ? l.createdAt.toDate().toLocaleString('it-IT', { 
                              day: '2-digit', 
                              month: '2-digit', 
                              hour: '2-digit', 
                              minute: '2-digit' 
                            }) 
                          : "Ora"}
                      </td>                      
                      <td className="p-4 pt-5">
                        <div className="font-bold text-slate-900 text-base">{l.name} {l.surname}</div>
                        <div className="text-xs text-slate-500 mt-0.5">{l.role} @ <span className="text-indigo-600 font-semibold">{l.company}</span></div>
                      </td>
                      <td className="p-4 pt-5">
                        <div className="font-medium text-slate-700 break-all">{l.email}</div>
                        <div className="text-xs text-slate-400 mt-0.5 font-mono">{l.phone || "-"}</div>
                      </td>
                      <td className="p-4 pt-5">
                        <div className="mb-2 text-indigo-600 font-bold uppercase tracking-wider text-xs">
                          {l.quizTitle} <span className="text-slate-400 font-normal">({l.profileTitle || "N/A"})</span>
                        </div>
                        {l.answers && Array.isArray(l.answers) ? (
                          <div className="space-y-3 bg-slate-50 p-4 rounded-xl border border-slate-100 max-h-64 overflow-y-auto shadow-inner">
                            {l.answers.map((ans, idx) => (
                              <div key={idx} className="text-xs space-y-0.5 border-b border-slate-200/60 pb-2 last:border-none last:pb-0">
                                <div className="text-slate-500 font-medium">Q: {ans.domanda}</div>
                                <div className="text-emerald-600 font-bold">A: {ans.risposta_scelta}</div>
                              </div>
                            ))}
                          </div>
                        ) : (
                          <span className="text-slate-400 italic text-xs">Nessun dettaglio risposte salvato o formato vecchio.</span>
                        )}
                      </td>
                      <td className="p-4 text-center font-mono font-bold text-base text-emerald-600 bg-emerald-50/30 pt-5">
                        {l.score} pt
                      </td>
                      <td className="p-4 text-center pt-5">
                        <button 
                          onClick={() => scaricaPDFCertificato(l)}
                          className="inline-flex items-center justify-center gap-1.5 bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold py-1.5 px-3 rounded-xl shadow-sm hover:shadow transition-all cursor-pointer"
                        >
                          <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3"/>
                          </svg>
                          PDF
                        </button>
                      </td>
                    </tr>
                  ))}
                  {filteredAndSortedLeads.length === 0 && (
                    <tr>
                      <td colSpan="6" className="p-12 text-center text-slate-400 italic text-base">Nessun lead trovato per il filtro selezionato.</td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // INTERFACCIA CLIENTI STANDARD
  return (
    <div className="min-h-screen bg-slate-50 text-slate-900 px-6 py-12 lg:px-16">
      <div className="max-w-7xl mx-auto mb-12 animate-fadeIn">
        <span className="text-xs font-bold tracking-widest text-indigo-600 uppercase bg-indigo-50 px-3 py-1.5 rounded-full border border-indigo-100 shadow-sm">
          {window.APP_EVENT_NAME || "Assessment System"}
        </span>
        <h1 className="text-4xl lg:text-5xl font-extrabold tracking-tight mt-4 text-slate-900">
          {texts[lang]?.welcome || texts.it.welcome}
        </h1>
        <p className="text-slate-500 text-base lg:text-lg mt-2 max-w-2xl">
          {texts[lang]?.subtitle || texts.it.subtitle}
        </p>
      </div>

      <div className="max-w-7xl mx-auto grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 animate-slideUp">
        {QUIZZES.map((quiz) => (
          <div key={quiz.id} className="group relative bg-white border border-slate-200 rounded-2xl overflow-hidden hover:border-indigo-300 hover:shadow-[0_15px_30px_rgba(99,102,241,0.08)] transition-all duration-300 flex flex-col">
            <div className="relative h-48 w-full bg-slate-100 overflow-hidden flex items-center justify-center border-b border-slate-100">
              <div className="absolute inset-0 bg-gradient-to-t from-white/20 to-transparent z-10 opacity-60" />
              <span className="absolute top-4 right-4 z-20 text-[11px] font-bold bg-white/90 border border-slate-200 text-slate-700 px-2.5 py-1 rounded-md backdrop-blur-sm shadow-sm">
                ⏱️ {quiz.duration}
              </span>
              <img
                src={`/assets/quiz-cards/${quiz.imageKey}`} 
                alt={quiz.title[lang] || quiz.title.it}
                className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500 opacity-90 group-hover:opacity-100"
                onError={(e) => {
                  e.target.onerror = null;
                  e.target.style.display = 'none';
                  e.target.parentElement.classList.add('bg-gradient-to-br', 'from-indigo-50', 'to-slate-100');
                }}
              />
            </div>

            <div className="p-6 flex-1 flex flex-col justify-between">
              <div>
                <h3 className="text-xl font-bold tracking-tight text-slate-900 group-hover:text-indigo-600 transition-colors duration-200">
                  {quiz.title[lang] || quiz.title.it}
                </h3>
                <p className="text-slate-500 text-sm mt-2 line-clamp-3 leading-relaxed">
                  {quiz.description[lang] || quiz.description.it}
                </p>
              </div>
              <div className="mt-6">
                <button
                  onClick={() => onSelectQuiz(quiz.id)}
                  className="w-full bg-slate-50 hover:bg-indigo-600 border border-slate-200 hover:border-transparent text-slate-800 hover:text-white font-bold py-3 px-4 rounded-xl transition-all duration-300 transform text-sm tracking-wide shadow-sm flex items-center justify-center gap-2 cursor-pointer"
                >
                  {texts[lang]?.startBtn || texts.it.startBtn}
                  <span className="transform group-hover:translate-x-1 transition-transform">→</span>
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

window.Dashboard = Dashboard;