// Klyvio — AdminDashboard.jsx
// Dashboard administrateur — lecture depuis klyvio_audits (localStorage)

function AdminDashboard({ onLogout, onViewReport }) {
  const [audits, setAudits] = useState([]);
  const [search, setSearch] = useState("");

  useEffect(() => {
    try {
      const all = JSON.parse(localStorage.getItem("klyvio_audits") || "[]");
      setAudits(all.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)));
    } catch {
      setAudits([]);
    }
  }, []);

  const filtered = audits.filter(a =>
    (a.company?.name || "").toLowerCase().includes(search.toLowerCase()) ||
    (a.email || "").toLowerCase().includes(search.toLowerCase()) ||
    (a.name || "").toLowerCase().includes(search.toLowerCase()) ||
    (a.company?.sectorLabel || "").toLowerCase().includes(search.toLowerCase())
  );

  const avg = audits.length
    ? Math.round(audits.reduce((s, a) => s + (a.score || 0), 0) / audits.length)
    : 0;

  const thisMonth = audits.filter(a => {
    try {
      const d = new Date(a.createdAt);
      const now = new Date();
      return d.getMonth() === now.getMonth() && d.getFullYear() === now.getFullYear();
    } catch { return false; }
  }).length;

  // Métriques business
  const totalAgents = audits.reduce((s, a) => s + (a.offer?.agents || a.roi?.agents || 0), 0);
  const totalCA     = audits.reduce((s, a) => s + (a.roi?.totalInvest || 0), 0);
  const totalGain   = audits.reduce((s, a) => s + (a.roi?.totalGain  || 0), 0);

  function fmtEurK(v) {
    if (!v) return "—";
    if (v >= 1000000) return `${(v / 1000000).toFixed(1).replace(".", ",")} M€`;
    if (v >= 1000)    return `${Math.round(v / 1000)} k€`;
    return `${v} €`;
  }

  function scoreInfo(s) {
    if (s >= 70) return { label: "Avancé",        color: "#10B981", bg: "rgba(16,185,129,0.12)",  border: "rgba(16,185,129,0.3)"  };
    if (s >= 50) return { label: "En transition",  color: "#F59E0B", bg: "rgba(245,158,11,0.12)", border: "rgba(245,158,11,0.3)"  };
    if (s >= 30) return { label: "Débutant",       color: "var(--accent)", bg: "var(--accent-dim)", border: "rgba(0,174,239,0.3)"  };
    return              { label: "Très débutant",  color: "#EF4444", bg: "rgba(239,68,68,0.12)",  border: "rgba(239,68,68,0.3)"   };
  }

  function fmtDate(iso) {
    try {
      return new Date(iso).toLocaleDateString("fr-FR", { day: "numeric", month: "short", year: "numeric" });
    } catch { return "—"; }
  }

  return (
    <div style={{ maxWidth: 1200, margin: "0 auto", padding: "44px 28px 80px" }}>

      {/* ── En-tête ── */}
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 40, flexWrap: "wrap", gap: 16 }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 12 }}>Klyvio — Espace administrateur</div>
          <h1 className="display" style={{ fontSize: 40, margin: 0, color: "var(--white)" }}>Dashboard audits</h1>
        </div>
        <button className="btn btn-ghost" onClick={onLogout} style={{ color: "var(--gray)", marginTop: 4 }}>
          <Icon name="arrowLeft" size={13} /> Déconnexion
        </button>
      </div>

      {/* ── 4 métriques business ── */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16, marginBottom: 20 }}>
        {[
          { label: "Audits réalisés",    value: audits.length || "—", sub: `${thisMonth} ce mois-ci`,    icon: "file",     color: "var(--white)"  },
          { label: "Agents recommandés", value: totalAgents  || "—",  sub: "sur tous les audits",        icon: "sparkles", color: "var(--accent)" },
          { label: "CA potentiel",       value: fmtEurK(totalCA),     sub: "investissement an 1 cumulé", icon: "euro",     color: "#10B981"       },
          { label: "Gain cumulé clients",value: fmtEurK(totalGain),   sub: "gain annuel estimé total",   icon: "trending", color: "#F59E0B"       },
        ].map(({ label, value, sub, icon, color }) => (
          <div key={label} style={{
            padding: "22px 24px",
            background: "rgba(255,255,255,0.03)",
            border: "1px solid var(--border)",
            borderRadius: 16,
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 14 }}>
              <Icon name={icon} size={13} color="var(--gray)" />
              <span style={{ fontSize: 11, color: "var(--gray)", letterSpacing: "0.09em", textTransform: "uppercase", fontWeight: 600 }}>
                {label}
              </span>
            </div>
            <div className="display" style={{ fontSize: 32, color, margin: "0 0 4px", fontVariantNumeric: "tabular-nums" }}>{value}</div>
            <div style={{ fontSize: 12, color: "var(--text-mute)" }}>{sub}</div>
          </div>
        ))}
      </div>

      {/* ── Score moyen ── */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 16, marginBottom: 36 }}>
        {[
          { label: "Score moyen maturité IA", value: audits.length ? `${avg} / 100` : "—", icon: "target"   },
          { label: "Ce mois-ci",              value: thisMonth || "—",                      icon: "calendar" },
        ].map(({ label, value, icon }) => (
          <div key={label} style={{
            padding: "20px 24px",
            background: "rgba(255,255,255,0.02)",
            border: "1px solid var(--border)",
            borderRadius: 16,
            display: "flex", alignItems: "center", gap: 20,
          }}>
            <div style={{ width: 40, height: 40, borderRadius: 10, background: "rgba(255,255,255,0.04)", border: "1px solid var(--border)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
              <Icon name={icon} size={16} color="var(--gray)" />
            </div>
            <div>
              <div style={{ fontSize: 11, color: "var(--gray)", letterSpacing: "0.09em", textTransform: "uppercase", fontWeight: 600, marginBottom: 4 }}>{label}</div>
              <div className="display" style={{ fontSize: 26, color: "var(--white)", margin: 0 }}>{value}</div>
            </div>
          </div>
        ))}
      </div>

      {/* ── Liste audits ── */}
      <div style={{
        background: "rgba(255,255,255,0.02)",
        border: "1px solid var(--border)",
        borderRadius: 18,
        overflow: "hidden",
      }}>
        <div style={{
          padding: "16px 24px",
          borderBottom: "1px solid var(--border)",
          display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16,
          flexWrap: "wrap",
        }}>
          <h2 className="display" style={{ fontSize: 20, margin: 0 }}>
            Tous les audits
            {search && <span style={{ fontSize: 13, color: "var(--gray)", fontWeight: 400, marginLeft: 10 }}>({filtered.length} résultat{filtered.length > 1 ? "s" : ""})</span>}
          </h2>
          <input
            className="input"
            placeholder="Rechercher par entreprise, email…"
            value={search}
            onChange={e => setSearch(e.target.value)}
            style={{ width: 260, background: "rgba(255,255,255,0.04)", fontSize: 13 }}
          />
        </div>

        {audits.length === 0 && (
          <div style={{ padding: "64px", textAlign: "center" }}>
            <Icon name="file" size={32} color="var(--text-mute)" />
            <p style={{ marginTop: 16, color: "var(--gray)", fontSize: 15 }}>Aucun audit complété pour le moment.</p>
            <p style={{ color: "var(--text-mute)", fontSize: 13, marginTop: 4 }}>Les audits apparaîtront ici dès qu'un client aura terminé le questionnaire.</p>
          </div>
        )}

        {audits.length > 0 && filtered.length === 0 && (
          <div style={{ padding: "48px", textAlign: "center", color: "var(--gray)", fontSize: 14 }}>
            Aucun résultat pour "{search}".
          </div>
        )}

        {filtered.length > 0 && (
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 14, tableLayout: "fixed" }}>
            <colgroup>
              <col style={{ width: "26%" }} />
              <col style={{ width: "24%" }} />
              <col style={{ width: "14%" }} />
              <col style={{ width: "12%" }} />
              <col style={{ width: "16%" }} />
              <col style={{ width: "8%" }} />
            </colgroup>
            <thead>
              <tr style={{ borderBottom: "1px solid var(--border)" }}>
                {["Entreprise", "Contact", "Date", "Score", "Niveau", ""].map(h => (
                  <th key={h} style={{
                    padding: "12px 20px", textAlign: "left",
                    fontSize: 11, color: "var(--text-mute)",
                    fontWeight: 600, letterSpacing: "0.08em", textTransform: "uppercase",
                  }}>
                    {h}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.map((audit, i) => {
                const info = scoreInfo(audit.score || 0);
                return (
                  <tr
                    key={audit.id || i}
                    style={{ borderBottom: i < filtered.length - 1 ? "1px solid var(--border)" : "none", transition: "background .12s" }}
                    onMouseEnter={e => e.currentTarget.style.background = "rgba(255,255,255,0.025)"}
                    onMouseLeave={e => e.currentTarget.style.background = "transparent"}
                  >
                    <td style={{ padding: "16px 20px", overflow: "hidden" }}>
                      <div style={{ fontWeight: 600, color: "var(--white)", marginBottom: 3, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                        {audit.company?.name || "—"}
                      </div>
                      <div style={{ fontSize: 12, color: "var(--text-mute)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                        {audit.company?.sectorLabel || ""}
                        {audit.company?.sizeLabel ? ` · ${audit.company.sizeLabel} sal.` : ""}
                      </div>
                    </td>
                    <td style={{ padding: "16px 20px", overflow: "hidden" }}>
                      <div style={{ color: "var(--text-soft)", marginBottom: 3, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                        {audit.name || "—"}
                      </div>
                      <div style={{ fontSize: 12, color: "var(--text-mute)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                        {audit.email || ""}
                      </div>
                    </td>
                    <td style={{ padding: "16px 20px", color: "var(--gray)", whiteSpace: "nowrap" }}>
                      {fmtDate(audit.createdAt)}
                    </td>
                    <td style={{ padding: "16px 20px" }}>
                      <span className="display" style={{ fontSize: 24, color: "var(--white)" }}>{audit.score || 0}</span>
                      <span style={{ fontSize: 12, color: "var(--text-mute)" }}>/100</span>
                    </td>
                    <td style={{ padding: "16px 20px" }}>
                      <span style={{
                        fontSize: 12, fontWeight: 600, padding: "4px 10px", borderRadius: 6,
                        color: info.color, background: info.bg, border: `1px solid ${info.border}`,
                        whiteSpace: "nowrap",
                      }}>
                        {info.label}
                      </span>
                    </td>
                    <td style={{ padding: "16px 20px" }}>
                      <button
                        className="btn btn-ghost btn-sm"
                        onClick={() => onViewReport(audit)}
                        style={{ whiteSpace: "nowrap" }}
                      >
                        Voir <Icon name="arrowRight" size={12} />
                      </button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

window.AdminDashboard = AdminDashboard;
