// Klyvio — Booking modal + Admin dashboard (dark theme Klyvio)

function BookingModal({ onClose, company }) {
  const [step, setStep] = useState(0);
  const [form, setForm] = useState({ date: "", slot: "", email: "", phone: "", topic: "" });
  const dates = [
    { d: "28", day: "Lun", month: "avril", slots: ["09:30", "11:00", "14:30", "16:00"] },
    { d: "29", day: "Mar", month: "avril", slots: ["10:00", "11:30", "15:00"] },
    { d: "30", day: "Mer", month: "avril", slots: ["09:00", "10:30", "14:00", "17:00"] },
    { d: "02", day: "Ven", month: "mai",   slots: ["11:00", "14:30"] },
  ];

  return (
    <div style={{
      position: "fixed", inset: 0,
      background: "rgba(8,15,26,0.75)",
      backdropFilter: "blur(8px)",
      display: "flex", alignItems: "center", justifyContent: "center",
      zIndex: 200, padding: 20,
    }}>
      <div className="card" style={{ width: "100%", maxWidth: 720, maxHeight: "90vh", overflow: "auto", padding: 0 }}>
        {step < 2 ? (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1.2fr" }}>
            {/* Gauche — info consultant */}
            <div style={{ background: "var(--bg2)", borderRight: "1px solid var(--border)", padding: 32, borderRadius: "16px 0 0 16px" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 24 }}>
                <div style={{ width: 40, height: 40, borderRadius: 10, background: "var(--accent)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <Icon name="calendar" size={18} color="#000" />
                </div>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: "var(--white)" }}>Romain</div>
                  <div style={{ fontSize: 12, color: "var(--gray)" }}>Fondateur Klyvio</div>
                </div>
              </div>
              <h3 className="display" style={{ fontSize: 24, margin: "0 0 10px", color: "var(--white)" }}>
                30 minutes, 100% utiles.
              </h3>
              <p style={{ fontSize: 13, color: "var(--gray)", lineHeight: 1.6, margin: "0 0 20px" }}>
                On revoit votre rapport ensemble, on priorise les 2–3 chantiers à lancer en premier, et on répond à toutes vos questions.
              </p>
              <div style={{ display: "flex", flexDirection: "column", gap: 12, fontSize: 13, color: "var(--gray)" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}><Icon name="clock" size={14} color="var(--accent)" /> 30 minutes</div>
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}><Icon name="calendar" size={14} color="var(--accent)" /> Visio ou téléphone</div>
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}><Icon name="euro" size={14} color="var(--accent)" /> Offert · sans engagement</div>
              </div>
            </div>

            {/* Droite — formulaire */}
            <div style={{ padding: 28 }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 22 }}>
                <div className="eyebrow">Étape {step + 1} / 2</div>
                <button className="btn btn-ghost btn-sm" onClick={onClose}><Icon name="x" size={12} /></button>
              </div>

              {step === 0 && (
                <>
                  <h4 className="display" style={{ fontSize: 22, margin: "0 0 16px", color: "var(--white)" }}>Choisissez un créneau</h4>
                  <div style={{ display: "flex", flexDirection: "column", gap: 10, maxHeight: 360, overflowY: "auto" }}>
                    {dates.map(d => (
                      <div key={d.d}>
                        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
                          <div style={{ width: 42, textAlign: "center", padding: "6px 0", background: "var(--accent-dim)", border: "1px solid var(--border)", borderRadius: 8 }}>
                            <div style={{ fontSize: 10, color: "var(--text-mute)", letterSpacing: "0.08em", fontWeight: 600 }}>{d.day.toUpperCase()}</div>
                            <div style={{ fontSize: 18, fontWeight: 800, color: "var(--white)" }}>{d.d}</div>
                          </div>
                          <div style={{ fontSize: 13, color: "var(--gray)" }}>{d.day} {d.d} {d.month}</div>
                        </div>
                        <div style={{ display: "flex", gap: 6, flexWrap: "wrap", paddingLeft: 52 }}>
                          {d.slots.map(s => {
                            const selected = form.date === d.d && form.slot === s;
                            return (
                              <button key={s} onClick={() => setForm({ ...form, date: d.d, slot: s, dateLabel: `${d.day} ${d.d} ${d.month}` })}
                                style={{
                                  padding: "7px 14px", fontSize: 13, fontWeight: 500,
                                  background: selected ? "var(--accent)" : "rgba(255,255,255,0.03)",
                                  color: selected ? "#000" : "var(--gray)",
                                  border: `1px solid ${selected ? "var(--accent)" : "var(--gray-dim)"}`,
                                  borderRadius: 8, cursor: "pointer",
                                  transition: "all .15s ease",
                                }}>
                                {s}
                              </button>
                            );
                          })}
                        </div>
                      </div>
                    ))}
                  </div>
                  <button className="btn btn-primary btn-lg" style={{ width: "100%", marginTop: 20, opacity: form.slot ? 1 : 0.4 }}
                    disabled={!form.slot}
                    onClick={() => setStep(1)}>Continuer <Icon name="arrowRight" size={13} /></button>
                </>
              )}

              {step === 1 && (
                <>
                  <h4 className="display" style={{ fontSize: 22, margin: "0 0 16px", color: "var(--white)" }}>Vos coordonnées</h4>
                  <div style={{ padding: "10px 12px", background: "var(--accent-dim)", border: "1px solid var(--border)", borderRadius: 10, fontSize: 13, color: "var(--accent)", marginBottom: 18, display: "flex", alignItems: "center", gap: 10 }}>
                    <Icon name="calendar" size={13} />
                    <span>{form.dateLabel} à <strong>{form.slot}</strong></span>
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                    <div className="field"><label>Email professionnel</label><input className="input" placeholder="marie@atlas-industries.fr" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} /></div>
                    <div className="field"><label>Téléphone</label><input className="input" placeholder="+33 6 12 34 56 78" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} /></div>
                    <div className="field"><label>Sujet principal (optionnel)</label><textarea className="textarea" rows={3} placeholder="Ex : on aimerait surtout parler de l'automatisation du support client…" value={form.topic} onChange={e => setForm({ ...form, topic: e.target.value })} /></div>
                  </div>
                  <div style={{ display: "flex", gap: 10, marginTop: 22 }}>
                    <button className="btn btn-ghost btn-lg" style={{ flex: 1 }} onClick={() => setStep(0)}>Retour</button>
                    <button className="btn btn-primary btn-lg" style={{ flex: 2, opacity: form.email ? 1 : 0.4 }} disabled={!form.email} onClick={() => setStep(2)}>
                      Confirmer le rendez-vous
                    </button>
                  </div>
                </>
              )}
            </div>
          </div>
        ) : (
          <div style={{ padding: "52px 40px", textAlign: "center" }}>
            <div style={{ width: 64, height: 64, margin: "0 auto 20px", borderRadius: 16, background: "var(--success-dim)", border: "1px solid rgba(34,197,94,0.3)", color: "var(--success)", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <Icon name="check" size={28} strokeWidth={2.5} />
            </div>
            <h3 className="display" style={{ fontSize: 30, margin: "0 0 12px", color: "var(--white)" }}>Rendez-vous confirmé !</h3>
            <p style={{ fontSize: 14, color: "var(--gray)", marginBottom: 20, maxWidth: 420, marginLeft: "auto", marginRight: "auto", lineHeight: 1.6 }}>
              Nous avons envoyé une invitation à <strong style={{ color: "var(--white)" }}>{form.email}</strong> pour le {form.dateLabel} à {form.slot}.
            </p>
            <div style={{ padding: "14px 18px", background: "var(--accent-dim)", border: "1px solid var(--border)", borderRadius: 10, display: "inline-flex", alignItems: "center", gap: 10, marginBottom: 24 }}>
              <Icon name="calendar" size={14} color="var(--accent)" />
              <span style={{ fontSize: 13, color: "var(--white)" }}>{form.dateLabel} · {form.slot} · 30 min</span>
            </div>
            <div>
              <button className="btn btn-primary btn-lg" onClick={onClose}>Retour au rapport</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

/* ———————————————————— ADMIN DASHBOARD ———————————————————— */
function AdminDashboard({ onOpenReport }) {
  const [filter, setFilter] = useState("all");
  const audits = [
    { id: "A-1042", company: "Atlas Industries",  person: "Marie Dupont",   sector: "Industrie", size: "42 pers.", score: 62,   status: "ready",   gain: 184000, date: "il y a 2h",  new: true },
    { id: "A-1041", company: "Rosier & Fils",     person: "Nicolas Rosier", sector: "BTP",       size: "28 pers.", score: 34,   status: "ready",   gain: 112000, date: "hier" },
    { id: "A-1040", company: "NeoPharm",           person: "Claire Berteau", sector: "Santé",     size: "85 pers.", score: 71,   status: "ready",   gain: 320000, date: "hier",        flagged: true },
    { id: "A-1039", company: "Mobilio",            person: "Samir Benali",   sector: "Commerce",  size: "15 pers.", score: null, status: "pending", progress: 64, date: "il y a 3h" },
    { id: "A-1038", company: "Cléome Avocats",    person: "Juliette Mari",  sector: "Services",  size: "22 pers.", score: 48,   status: "ready",   gain: 98000,  date: "2 jours" },
    { id: "A-1037", company: "Atelier Bois d'Or", person: "Pierre Leclerc", sector: "Industrie", size: "18 pers.", score: 28,   status: "ready",   gain: 76000,  date: "3 jours" },
    { id: "A-1036", company: "Vivaldi Group",      person: "Léa Fontaine",   sector: "Services",  size: "110 pers.",score: 78,  status: "ready",   gain: 410000, date: "5 jours" },
    { id: "A-1035", company: "ProxiShop",          person: "Karim Osmani",   sector: "Commerce",  size: "35 pers.", score: null, status: "draft",   progress: 22, date: "1 sem." },
  ];

  const filtered = filter === "all" ? audits : audits.filter(a => a.status === filter);
  const totals = {
    count: audits.length,
    ready: audits.filter(a => a.status === "ready").length,
    avg:   Math.round(audits.filter(a => a.score).reduce((s, a) => s + a.score, 0) / audits.filter(a => a.score).length),
    gain:  audits.reduce((s, a) => s + (a.gain || 0), 0),
  };

  return (
    <div style={{ flex: 1, padding: "32px 28px", background: "var(--bg)" }}>
      <div style={{ maxWidth: 1280, margin: "0 auto" }}>
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginBottom: 28 }}>
          <div>
            <div className="eyebrow-line" style={{ marginBottom: 10 }}>Console consultant</div>
            <h1 className="display" style={{ fontSize: 38, margin: 0, color: "var(--white)" }}>Vos audits en cours</h1>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button className="btn btn-ghost"><Icon name="download" size={13} /> Exporter CSV</button>
            <button className="btn btn-primary"><Icon name="plus" size={13} /> Lancer un audit</button>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 24 }}>
          <StatCard eyebrow="Total audits"          value={totals.count}        icon="fileText" />
          <StatCard eyebrow="Rapports prêts"        value={totals.ready}        icon="check" />
          <StatCard eyebrow="Score moyen"           value={totals.avg}  sub="/ 100" icon="target" />
          <StatCard eyebrow="Gain identifié cumulé" value={formatEur(totals.gain)} sub="/ an" icon="euro" tone="accent" />
        </div>

        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          {/* Filtres */}
          <div style={{ display: "flex", alignItems: "center", padding: "14px 20px", borderBottom: "1px solid var(--border)", gap: 8 }}>
            {[
              { id: "all",     label: "Tous" },
              { id: "ready",   label: "Rapports prêts" },
              { id: "pending", label: "En cours" },
              { id: "draft",   label: "Brouillons" },
            ].map(f => (
              <button key={f.id} onClick={() => setFilter(f.id)}
                style={{
                  padding: "5px 12px", fontSize: 13, fontWeight: 500,
                  border: "none", borderRadius: 999, cursor: "pointer",
                  background: filter === f.id ? "var(--accent)" : "transparent",
                  color: filter === f.id ? "#000" : "var(--gray)",
                  transition: "all .15s ease",
                }}>{f.label}</button>
            ))}
            <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 8 }}>
              <div style={{ display: "flex", alignItems: "center", background: "rgba(255,255,255,0.04)", border: "1px solid var(--gray-dim)", borderRadius: 8, padding: "6px 10px", gap: 6 }}>
                <Icon name="search" size={13} color="var(--text-mute)" />
                <input placeholder="Rechercher…" style={{ border: "none", outline: "none", background: "transparent", fontSize: 13, width: 160, color: "var(--white)" }} />
              </div>
              <button className="btn btn-ghost btn-sm"><Icon name="filter" size={13} /> Filtrer</button>
            </div>
          </div>

          <table style={{ width: "100%", borderCollapse: "collapse" }}>
            <thead>
              <tr style={{ background: "rgba(255,255,255,0.02)" }}>
                {["Entreprise", "Contact", "Secteur", "Taille", "Score", "Gain /an", "Statut", "Date", ""].map((h, i) => (
                  <th key={i} style={{
                    padding: "11px 18px", textAlign: "left",
                    fontSize: 10, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase",
                    color: "var(--text-mute)", borderBottom: "1px solid var(--border)",
                  }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.map(a => (
                <tr key={a.id}
                  style={{ borderBottom: "1px solid var(--border)", cursor: "pointer", transition: "background .15s" }}
                  onMouseEnter={e => e.currentTarget.style.background = "rgba(0,174,239,0.04)"}
                  onMouseLeave={e => e.currentTarget.style.background = "transparent"}
                  onClick={() => a.status === "ready" && onOpenReport(a)}>
                  <td style={{ padding: "14px 18px" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <div style={{ width: 30, height: 30, borderRadius: 8, background: "var(--accent-dim)", border: "1px solid var(--border)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 700, color: "var(--accent)" }}>
                        {a.company.split(" ").slice(0, 2).map(w => w[0]).join("").toUpperCase()}
                      </div>
                      <div>
                        <div style={{ fontSize: 13, fontWeight: 500, color: "var(--white)", display: "flex", alignItems: "center", gap: 6 }}>
                          {a.company}
                          {a.new && <span style={{ fontSize: 9, padding: "2px 6px", borderRadius: 4, background: "var(--accent)", color: "#000", fontWeight: 700 }}>NEW</span>}
                          {a.flagged && <Icon name="star" size={11} color="var(--warn)" />}
                        </div>
                        <div className="mono" style={{ fontSize: 10, color: "var(--text-mute)" }}>{a.id}</div>
                      </div>
                    </div>
                  </td>
                  <td style={{ padding: "14px 18px", fontSize: 13, color: "var(--gray)" }}>{a.person}</td>
                  <td style={{ padding: "14px 18px", fontSize: 13, color: "var(--white)" }}>{a.sector}</td>
                  <td style={{ padding: "14px 18px", fontSize: 13, color: "var(--gray)" }}>{a.size}</td>
                  <td style={{ padding: "14px 18px" }}>
                    {a.score ? (
                      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        <div style={{ fontSize: 16, fontWeight: 800, color: "var(--white)", fontVariantNumeric: "tabular-nums" }}>{a.score}</div>
                        <div style={{ width: 44, height: 3, background: "var(--gray-dim)", borderRadius: 999 }}>
                          <div style={{ width: `${a.score}%`, height: "100%", background: a.score > 60 ? "var(--success)" : a.score > 40 ? "var(--warn)" : "var(--danger)", borderRadius: 999 }} />
                        </div>
                      </div>
                    ) : <span style={{ fontSize: 12, color: "var(--text-mute)" }}>—</span>}
                  </td>
                  <td style={{ padding: "14px 18px", fontSize: 13, fontWeight: 600, color: "var(--accent)", fontVariantNumeric: "tabular-nums" }}>
                    {a.gain ? formatEur(a.gain) : <span style={{ color: "var(--text-mute)", fontWeight: 400 }}>—</span>}
                  </td>
                  <td style={{ padding: "14px 18px" }}>
                    {a.status === "ready"   && <span className="chip chip-success">Prêt</span>}
                    {a.status === "pending" && <span className="chip chip-warn">En cours {a.progress}%</span>}
                    {a.status === "draft"   && <span className="chip">Brouillon</span>}
                  </td>
                  <td style={{ padding: "14px 18px", fontSize: 11, color: "var(--text-mute)" }}>{a.date}</td>
                  <td style={{ padding: "14px 18px" }}>
                    {a.status === "ready" && (
                      <button className="btn btn-ghost btn-sm" onClick={(e) => { e.stopPropagation(); onOpenReport(a); }}>
                        Ouvrir <Icon name="arrowRight" size={11} />
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Insights */}
        <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 16, marginTop: 20 }}>
          <div className="card" style={{ padding: "22px 26px" }}>
            <div className="eyebrow" style={{ marginBottom: 14 }}>Insights agrégés · derniers 30 jours</div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }}>
              {[
                { label: "Dimension la plus faible", value: "Données",       color: "var(--viz-teal)" },
                { label: "Automatisation #1 citée",  value: "Support client", color: "var(--viz-violet)" },
                { label: "Secteur le + mature",       value: "Tech / édition", color: "var(--accent)" },
              ].map((item, k) => (
                <div key={k} style={{ padding: "13px 14px", background: "rgba(255,255,255,0.02)", borderRadius: 10, borderLeft: `3px solid ${item.color}` }}>
                  <div style={{ fontSize: 10, fontWeight: 600, color: "var(--text-mute)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 6 }}>{item.label}</div>
                  <div style={{ fontSize: 16, fontWeight: 600, color: "var(--white)" }}>{item.value}</div>
                </div>
              ))}
            </div>
          </div>

          <div className="card" style={{ padding: "22px 26px" }}>
            <div className="eyebrow" style={{ marginBottom: 14 }}>Activité</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {[
                { icon: "check",    color: "var(--success)", text: "Atlas Industries a terminé son audit",            time: "il y a 2h" },
                { icon: "calendar", color: "var(--accent)",  text: "RDV confirmé avec NeoPharm · 29 avril 10:30",    time: "il y a 5h" },
                { icon: "play",     color: "var(--warn)",    text: "Mobilio a démarré son audit",                    time: "il y a 6h" },
              ].map((a, k) => (
                <div key={k} style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <div style={{ width: 28, height: 28, borderRadius: 8, background: `${a.color}18`, border: `1px solid ${a.color}30`, color: a.color, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                    <Icon name={a.icon} size={12} />
                  </div>
                  <div style={{ flex: 1, fontSize: 13, color: "var(--white)" }}>{a.text}</div>
                  <div style={{ fontSize: 11, color: "var(--text-mute)" }}>{a.time}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { BookingModal, AdminDashboard });
