// ─────────────────────────────────────────────────────────────
// DoricMatch AI — src/components/admin.jsx
// Administration : validation des comptes et réglages.
// Chargé via <script type="text/babel"> dans index.html (ordre important).
// ─────────────────────────────────────────────────────────────

function AdminUsers({ onChanged }) {
  const [rows, setRows] = useState(null);
  const [busyId, setBusyId] = useState(null);
  const [err, setErr] = useState("");
  const load = async () => {
    setErr("");
    const { data, error } = await sb.from("profiles").select("id,email,status,created_at,approved_at").order("created_at", { ascending: false });
    if (error) { setErr("Impossible de charger les utilisateurs : " + error.message); setRows([]); return; }
    const ord = { pending: 0, none: 0, approved: 1, rejected: 2 };
    const sorted = (data || []).slice().sort((a, b) => (ord[a.status] || 0) - (ord[b.status] || 0));
    setRows(sorted);
    if (onChanged) onChanged();
  };
  useEffect(() => { load(); }, []);
  const act = async (id, status) => {
    setBusyId(id); setErr("");
    const patch = { status, approved_at: status === "approved" ? new Date().toISOString() : null };
    const { error } = await sb.from("profiles").update(patch).eq("id", id);
    setBusyId(null);
    if (error) { setErr("Action impossible : " + error.message); return; }
    load();
  };
  const fmt = (d) => d ? new Date(d).toLocaleDateString("fr-FR", { day: "2-digit", month: "short", year: "numeric" }) : "—";
  const badge = (s) => {
    const map = { pending: ["En attente", C.amber], approved: ["Validé", C.emerald], rejected: ["Refusé", C.rose] };
    const m = map[s] || ["Inconnu", C.faint];
    return <span style={{ fontSize: 11.5, fontWeight: 600, color: m[1], background: m[1] + "1a", padding: "3px 9px", borderRadius: 999 }}>{m[0]}</span>;
  };
  const pending = (rows || []).filter(r => r.status === "pending" || r.status === "none");
  return (
    <div className="card rise" style={{ padding: 26, maxWidth: 760 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap", marginBottom: 4 }}>
        <div className="serif" style={{ fontSize: 18, fontWeight: 700 }}>Gestion des accès</div>
        <button className="btn btn-g" onClick={load}>Actualiser</button>
      </div>
      <div style={{ fontSize: 12.5, color: C.dim, marginBottom: 18 }}>Validez ou refusez les comptes qui s'inscrivent. Seuls les comptes <b>validés</b> peuvent utiliser l'application et l'IA.</div>
      {err && <div style={{ fontSize: 12.5, color: C.rose, background: C.rose + "14", border: "1px solid " + C.rose + "33", borderRadius: 10, padding: "9px 12px", marginBottom: 14 }}>{err}</div>}
      {rows === null && <div style={{ fontSize: 13, color: C.faint }}>Chargement…</div>}
      {rows !== null && rows.length === 0 && !err && <div style={{ fontSize: 13, color: C.faint }}>Aucun utilisateur pour le moment.</div>}

      {pending.length > 0 && (
        <div style={{ marginBottom: 18 }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: C.amber, letterSpacing: ".04em", textTransform: "uppercase", marginBottom: 10 }}>À valider ({pending.length})</div>
          {pending.map(r => (
            <div key={r.id} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap", padding: "12px 14px", border: "1px solid " + C.line, borderRadius: 12, marginBottom: 8, background: C.amber + "0d" }}>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, color: C.text, wordBreak: "break-all" }}>{r.email || r.id}</div>
                <div style={{ fontSize: 11.5, color: C.faint, marginTop: 2 }}>Inscrit le {fmt(r.created_at)}</div>
              </div>
              <div style={{ display: "flex", gap: 8 }}>
                <button className="btn btn-p" disabled={busyId === r.id} onClick={() => act(r.id, "approved")}>{busyId === r.id ? "…" : "Valider"}</button>
                <button className="btn btn-g" style={{ color: C.rose }} disabled={busyId === r.id} onClick={() => act(r.id, "rejected")}>Refuser</button>
              </div>
            </div>
          ))}
        </div>
      )}

      {rows !== null && rows.length > 0 && (
        <div>
          <div style={{ fontSize: 12, fontWeight: 700, color: C.faint, letterSpacing: ".04em", textTransform: "uppercase", marginBottom: 10 }}>Tous les comptes</div>
          {rows.map(r => (
            <div key={r.id} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap", padding: "11px 14px", borderBottom: "1px solid " + C.line }}>
              <div style={{ minWidth: 0, display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                <span style={{ fontSize: 13.5, color: C.text, wordBreak: "break-all" }}>{r.email || r.id}</span>
                {badge(r.status)}
                {r.email === ADMIN_EMAIL && <span style={{ fontSize: 11, color: C.indigo, fontWeight: 600 }}>· admin</span>}
              </div>
              <div style={{ display: "flex", gap: 8 }}>
                {r.email !== ADMIN_EMAIL && r.status !== "approved" && <button className="btn btn-g" disabled={busyId === r.id} onClick={() => act(r.id, "approved")}>Valider</button>}
                {r.email !== ADMIN_EMAIL && r.status === "approved" && <button className="btn btn-g" style={{ color: C.rose }} disabled={busyId === r.id} onClick={() => act(r.id, "rejected")}>Révoquer</button>}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function Settings({ settings, setSettings, isAdmin }) {
  const set = (k, v) => setSettings(s => ({ ...s, [k]: v }));
  const onLogo = (fl) => { if (!fl) return; const r = new FileReader(); r.onload = () => set("logo", r.result); r.readAsDataURL(fl); };
  const inp = { width: "100%", padding: "11px 14px", borderRadius: 11, border: `1px solid ${C.line}`, background: C.panel, color: C.text, fontSize: 13.5, outline: "none" };
  const lab = { fontSize: 11.5, color: C.faint, marginBottom: 5, display: "block" };
  const [tab, setTab] = useState("compte");
  const [pendingCount, setPendingCount] = useState(0);
  const loadPending = async () => {
    if (!isAdmin) return;
    const { count } = await sb.from("profiles").select("id", { count: "exact", head: true }).eq("status", "pending");
    setPendingCount(count || 0);
  };
  React.useEffect(() => { loadPending(); }, [isAdmin]);
  return (
    <>
      <H sub="Vos coordonnées, votre logo et votre carte T, utilisés dans l'application et vos communications.">Paramètres du compte</H>
      {isAdmin && (
        <div style={{ display: "flex", gap: 8, marginBottom: 18, flexWrap: "wrap" }}>
          {[["compte", "Mon compte"], ["matching", "Pondérations matching"], ["acces", "Accès utilisateurs"]].map(o => (
            <span key={o[0]} onClick={() => setTab(o[0])} className="chip" style={{ cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 7,
              background: tab === o[0] ? `linear-gradient(100deg,${C.indigo},${C.violet})` : undefined, color: tab === o[0] ? "#fff" : undefined, border: tab === o[0] ? "none" : undefined }}>
              {o[1]}{o[0] === "acces" && pendingCount > 0 && <span style={{ fontSize: 10.5, fontWeight: 700, background: tab === o[0] ? "rgba(255,255,255,.25)" : C.rose, color: "#fff", borderRadius: 999, padding: "1px 6px", minWidth: 16, textAlign: "center" }}>{pendingCount}</span>}
            </span>
          ))}
        </div>
      )}
      {(!isAdmin || tab === "compte") ? (
      <>
      <div className="card rise" style={{ padding: 26, maxWidth: 760 }}>
        <Section title="Identité">
          <div className="grid-2" style={{ gap: 14 }}>
            <div><label style={lab}>Société</label><input style={inp} value={settings.company} onChange={e => set("company", e.target.value)} /></div>
            <div><label style={lab}>Nom du broker</label><input style={inp} value={settings.broker} onChange={e => set("broker", e.target.value)} /></div>
            <div style={{ gridColumn: "1 / -1" }}><label style={lab}>Fonction / titre</label><input style={inp} value={settings.role} onChange={e => set("role", e.target.value)} /></div>
          </div>
        </Section>
        <Section title="Coordonnées">
          <div className="grid-2" style={{ gap: 14 }}>
            <div><label style={lab}>Email</label><input style={inp} type="email" value={settings.email} onChange={e => set("email", e.target.value)} /></div>
            <div><label style={lab}>Téléphone</label><input style={inp} value={settings.phone} onChange={e => set("phone", e.target.value)} /></div>
            <div><label style={lab}>Carte T (n°)</label><input style={inp} value={settings.carteT} onChange={e => set("carteT", e.target.value)} placeholder="CPI…" /></div>
            <div><label style={lab}>Adresse société</label><input style={inp} value={settings.address} onChange={e => set("address", e.target.value)} /></div>
          </div>
        </Section>
        <Section title="Logo de la société">
          <div style={{ display: "flex", alignItems: "center", gap: 18, flexWrap: "wrap" }}>
            <div style={{ width: 120, height: 120, borderRadius: 14, border: `1.5px dashed ${C.lineStrong}`, background: C.panel2, display: "grid", placeItems: "center", overflow: "hidden", flex: "none" }}>
              {settings.logo ? <img src={settings.logo} alt="logo" style={{ maxWidth: "100%", maxHeight: "100%", objectFit: "contain" }} /> : <span style={{ fontSize: 11, color: C.faint, textAlign: "center", padding: 8 }}>Aucun logo</span>}
            </div>
            <div>
              <label className="btn btn-g" style={{ cursor: "pointer", display: "inline-block" }}>
                <input type="file" accept="image/*" style={{ display: "none" }} onChange={e => onLogo(e.target.files[0])} />
                {settings.logo ? "Changer le logo" : "Importer un logo"}
              </label>
              {settings.logo && <button className="btn btn-g" style={{ marginLeft: 8, color: C.rose }} onClick={() => set("logo", "")}>Retirer</button>}
              <div style={{ fontSize: 11.5, color: C.faint, marginTop: 8, maxWidth: 320 }}>PNG ou JPG. Utilisé comme identité de votre compte dans l'application.</div>
            </div>
          </div>
        </Section>
        <Section title="Mention de confidentialité (pied de page)">
          <textarea value={settings.mentions} onChange={e => set("mentions", e.target.value)} style={{ ...inp, height: 64, lineHeight: 1.5, resize: "vertical" }} />
        </Section>
        <div style={{ fontSize: 12.5, color: C.emerald, marginTop: 8 }}>✓ Enregistré automatiquement dans votre compte (Supabase).</div>
      </div>
      </>
      ) : tab === "matching" ? (
        <WeightsPanel settings={settings} set={set} />
      ) : (
        <AdminUsers onChanged={loadPending} />
      )}
    </>
  );
}

// Éditeur des pondérations du matching (investisseurs + enseignes).
function WeightsPanel({ settings, set }) {
  const Editor = ({ title, labels, defaults, saved, onChange }) => {
    const w = { ...defaults, ...(saved || {}) };
    const sum = Object.keys(defaults).reduce((s, k) => s + (Number(w[k]) || 0), 0) || 1;
    return (
      <div className="card rise" style={{ padding: 26, maxWidth: 620, marginBottom: 18 }}>
        <Section title={title}>
          {Object.keys(defaults).map(k => {
            const pct = Math.round((Number(w[k]) || 0) / sum * 100);
            return (
              <div key={k} style={{ display: "flex", alignItems: "center", gap: 14, padding: "7px 0" }}>
                <span style={{ width: 150, fontSize: 13, color: C.dim }}>{labels[k]}</span>
                <input type="range" min="0" max="40" step="1" value={w[k]} onChange={e => onChange({ ...w, [k]: +e.target.value })} style={{ flex: 1, cursor: "pointer" }} />
                <span style={{ width: 48, textAlign: "right", fontWeight: 700, color: C.text }}>{pct} %</span>
              </div>
            );
          })}
          <div style={{ marginTop: 10, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <span style={{ fontSize: 11.5, color: C.faint }}>Les valeurs sont normalisées : seule leur proportion compte.</span>
            <button className="btn btn-g" onClick={() => onChange(null)}>Réinitialiser</button>
          </div>
        </Section>
      </div>
    );
  };
  return (
    <>
      <div style={{ fontSize: 12.5, color: C.dim, marginBottom: 16, maxWidth: 620 }}>
        Ajustez l'importance de chaque critère dans le calcul du score. Les changements s'appliquent immédiatement à tous les matchings et sont enregistrés dans votre compte.
      </div>
      <Editor title="Matching dossier → investisseurs" labels={INV_WEIGHT_LABELS} defaults={DEFAULT_INV_WEIGHTS} saved={settings.invWeights} onChange={v => set("invWeights", v)} />
      <Editor title="Matching local → enseignes" labels={ENS_WEIGHT_LABELS} defaults={DEFAULT_ENS_WEIGHTS} saved={settings.ensWeights} onChange={v => set("ensWeights", v)} />
      <div style={{ fontSize: 12.5, color: C.emerald, marginTop: 4 }}>✓ Enregistré automatiquement (Supabase).</div>
    </>
  );
}
