/* global React */
// ============================================================================
// Chantier K.5 · Status page publique (?status=1)
// ----------------------------------------------------------------------------
// Page accessible sans authentification — pas de sidebar, pas de topbar.
// Affiche :
//   - L'état global de la plateforme (calculé depuis v_status_summary +
//     pings live des composants)
//   - Liste des incidents en cours
//   - Historique sur 90 jours
//
// Si l'utilisateur visiteur se trouve être super-admin authentifié, des
// boutons « Nouvel incident » / « Marquer résolu » s'affichent — pas
// besoin d'écran séparé pour la gestion.
// ============================================================================

const { useState: useStateSP, useEffect: useEffectSP } = React;

function StatusPage({ lang: initialLang }) {
  const [lang, setLang] = useStateSP(initialLang || "fr");
  const T = (fr, en) => (lang === "fr" ? fr : en);

  // Ping des composants — relancé toutes les 60 s
  const [pings, setPings] = useStateSP({ db: "unknown", storage: "unknown", edge: "unknown", front: "ok" });
  useEffectSP(() => {
    let cancelled = false;
    const run = async () => {
      try {
        const r = await window.melr.pingAllComponents();
        if (!cancelled) setPings(r);
      } catch (_) {}
    };
    run();
    const id = setInterval(run, 60_000);
    return () => { cancelled = true; clearInterval(id); };
  }, []);

  // Incidents + résumé
  const { data: summary, refresh: refreshSummary } = window.melr.useStatusSummary
    ? window.melr.useStatusSummary() : { data: null, refresh: () => {} };
  const { data: incidents, refresh: refreshInc } = window.melr.useStatusIncidents
    ? window.melr.useStatusIncidents() : { data: [], refresh: () => {} };

  // Super-admin authentifié ?
  const [isSuperAdmin, setIsSuperAdmin] = useStateSP(false);
  useEffectSP(() => {
    let cancelled = false;
    (async () => {
      try {
        const sb = await window.melr.waitForSupabase
          ? window.melr.waitForSupabase()
          : window.melr.supabase;
        const profile = await window.melr.currentProfile();
        if (cancelled || !profile) return;
        // Heuristique : on tente la liste plans (RLS exige super-admin pour
        // certaines colonnes). Plus simple : on lit la permission.
        const r = await sb.from("user_roles").select("role").eq("user_id", profile.id).maybeSingle();
        // Pas de vraie source unique de vérité ici — on tente la mise à jour
        // d'un incident inexistant ; si refusé par RLS, on n'est pas admin.
        // Plus simple : utiliser useCurrentUserPermissions.
        // → on délègue ça via window.melr et on se contente de tester l'edition.
      } catch (_) {}
    })();
    return () => { cancelled = true; };
  }, []);
  // Utilise plutôt useCurrentUserPermissions si dispo
  const permsHook = window.melr.useCurrentUserPermissions
    ? window.melr.useCurrentUserPermissions()
    : { has: () => false, loading: false };
  const canAdmin = permsHook.has && permsHook.has("orgs.manage");

  // Etat global
  const overall = summary && summary.overall_status ? summary.overall_status : "operational";
  const allPingsOk = pings.db === "ok" && pings.storage === "ok" && pings.edge === "ok";
  // Combine : si déclaré 'operational' + tous pings ok → operational. Sinon, si
  // un ping est down/degraded mais aucun incident déclaré → degraded.
  const effective = overall !== "operational"
    ? overall
    : (allPingsOk ? "operational" : (pings.db === "down" || pings.storage === "down" || pings.edge === "down" ? "major" : "minor"));

  const meta = {
    operational: {
      fr: "Tous les services sont opérationnels", en: "All systems operational", es: "Todos los servicios están operativos",
      bg: "linear-gradient(135deg, #10b981, #059669)", color: "white", emoji: "✓",
    },
    minor: {
      fr: "Incident mineur en cours", en: "Minor incident in progress", es: "Incidente menor en curso",
      bg: "linear-gradient(135deg, #fbbf24, #f59e0b)", color: "#7c2d12", emoji: "⚠",
    },
    major: {
      fr: "Incident majeur en cours", en: "Major incident in progress", es: "Incidente mayor en curso",
      bg: "linear-gradient(135deg, #fb923c, #ea580c)", color: "white", emoji: "⚠",
    },
    critical: {
      fr: "Panne critique en cours", en: "Critical outage", es: "Avería crítica en curso",
      bg: "linear-gradient(135deg, #ef4444, #b91c1c)", color: "white", emoji: "✕",
    },
    maintenance: {
      fr: "Maintenance planifiée", en: "Scheduled maintenance", es: "Mantenimiento planificado",
      bg: "linear-gradient(135deg, #6366f1, #4338ca)", color: "white", emoji: "🔧",
    },
  }[effective] || { fr: "État inconnu", en: "Unknown state", es: "Estado desconocido", bg: "#94a3b8", color: "white", emoji: "?" };

  const fmtDate = (iso) => {
    if (!iso) return "—";
    try { return new Date(iso).toLocaleString(window.L("fr-FR", "en-GB", "es-ES")); }
    catch (_) { return iso; }
  };

  const componentRow = (key, labelFr, labelEn) => {
    const v = pings[key];
    const dotColor = v === "ok" ? "#10b981" : v === "degraded" ? "#f59e0b" : v === "down" ? "#dc2626" : "#94a3b8";
    const label = { ok: T("Opérationnel","Operational"), degraded: T("Dégradé","Degraded"), down: T("Indisponible","Down"), unknown: T("…","…") }[v];
    return (
      <div key={key} style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "12px 16px", borderBottom: "1px solid #e2e8f0", fontSize: 14,
      }}>
        <div style={{ fontWeight: 500 }}>{T(labelFr, labelEn)}</div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{
            display: "inline-block", width: 10, height: 10, borderRadius: "50%",
            background: dotColor,
          }} />
          <span style={{ fontSize: 13, color: dotColor, fontWeight: 600 }}>{label}</span>
        </div>
      </div>
    );
  };

  const sevBadge = (sev) => {
    const m = {
      critical: { bg: "#fee2e2", color: "#991b1b", fr: "Critique", en: "Critical", es: "Crítico" },
      major:    { bg: "#fed7aa", color: "#9a3412", fr: "Majeur",   en: "Major", es: "Mayor" },
      minor:    { bg: "#fef3c7", color: "#92400e", fr: "Mineur",   en: "Minor", es: "Menor" },
      maintenance: { bg: "#e0e7ff", color: "#3730a3", fr: "Maintenance", en: "Maintenance", es: "Mantenimiento" },
    }[sev] || { bg: "#f1f5f9", color: "#475569", fr: sev, en: sev };
    return <span style={{
      display: "inline-block", padding: "2px 8px", borderRadius: 10,
      background: m.bg, color: m.color, fontSize: 11, fontWeight: 600,
    }}>{T(m.fr, m.en)}</span>;
  };

  const statusBadge = (status) => {
    const m = {
      investigating: { fr: "Investigation",    en: "Investigating", es: "Investigación", bg: "#fef3c7", color: "#92400e" },
      identified:    { fr: "Cause identifiée", en: "Identified", es: "Causa identificada",    bg: "#fed7aa", color: "#9a3412" },
      monitoring:    { fr: "Surveillance",     en: "Monitoring", es: "Supervisión",    bg: "#dbeafe", color: "#1e40af" },
      resolved:      { fr: "Résolu",           en: "Resolved", es: "Resuelto",      bg: "#dcfce7", color: "#166534" },
    }[status] || { fr: status, en: status, bg: "#f1f5f9", color: "#475569" };
    return <span style={{
      display: "inline-block", padding: "2px 8px", borderRadius: 10,
      background: m.bg, color: m.color, fontSize: 11, fontWeight: 600,
    }}>{T(m.fr, m.en)}</span>;
  };

  // Modal création/édition d'incident
  const [editorOpen, setEditorOpen] = useStateSP(false);
  const [editing, setEditing]       = useStateSP(null);  // null = create, sinon row

  const onCreated = () => {
    setEditorOpen(false); setEditing(null);
    refreshSummary(); refreshInc();
  };

  const activeIncidents = (incidents || []).filter((i) => i.status !== "resolved");
  const resolvedIncidents = (incidents || []).filter((i) => i.status === "resolved");

  return (
    <div style={{ minHeight: "100vh", background: "#f8fafc", padding: 0 }}>
      {/* Header */}
      <div style={{ background: "#0f172a", color: "white", padding: "20px 28px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <img src="/abas-group.png" alt="MELR" style={{ width: 36, height: 36, borderRadius: 6, background: "white", padding: 2, objectFit: "contain" }} />
          <div>
            <div style={{ fontSize: 18, fontWeight: 700 }}>MELR · {T("Statut", "Status")}</div>
            <div style={{ fontSize: 11.5, color: "#cbd5e1" }}>
              {T("État des services en temps réel", "Real-time service status")}
            </div>
          </div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <select value={lang} onChange={(e) => setLang(e.target.value)}
            style={{ padding: "4px 8px", borderRadius: 6, border: "1px solid #334155", background: "#1e293b", color: "white", fontSize: 12 }}>
            <option value="fr">FR</option>
            <option value="en">EN</option>
          </select>
          <a href="/MELR" style={{ color: "#cbd5e1", fontSize: 12.5, textDecoration: "none" }}>
            ← {T("Retour à l'application", "Back to app")}
          </a>
        </div>
      </div>

      <div style={{ maxWidth: 880, margin: "0 auto", padding: "32px 24px" }}>
        {/* Bannière état global */}
        <div style={{
          background: meta.bg, color: meta.color,
          borderRadius: 12, padding: "24px 28px", marginBottom: 24,
          boxShadow: "0 4px 12px rgba(0,0,0,0.08)",
          display: "flex", alignItems: "center", gap: 18,
        }}>
          <div style={{ fontSize: 40 }}>{meta.emoji}</div>
          <div>
            <div style={{ fontSize: 22, fontWeight: 700, marginBottom: 4 }}>
              {T(meta.fr, meta.en)}
            </div>
            <div style={{ fontSize: 13, opacity: 0.92 }}>
              {T("Mis à jour automatiquement toutes les 60 secondes",
                 "Auto-refreshed every 60 seconds")}
              {summary && summary.last_resolved_at && (
                <> · {T("Dernier incident résolu :", "Last incident resolved:")} {fmtDate(summary.last_resolved_at)}</>
              )}
            </div>
          </div>
        </div>

        {/* Composants */}
        <div style={{ background: "white", borderRadius: 12, padding: 0, boxShadow: "0 1px 3px rgba(0,0,0,0.06)", marginBottom: 24 }}>
          <div style={{ padding: "16px 16px 8px 16px", fontSize: 14, fontWeight: 600, color: "#0f172a" }}>
            {T("Composants", "Components")}
          </div>
          {componentRow("front",   "Application web (front-end)", "Web application (front-end)")}
          {componentRow("db",      "Base de données",             "Database")}
          {componentRow("storage", "Stockage de fichiers",        "File storage")}
          {componentRow("edge",    "Fonctions edge (paiements, emails)", "Edge functions (payments, emails)")}
        </div>

        {/* Incidents actifs */}
        {activeIncidents.length > 0 && (
          <div style={{ background: "white", borderRadius: 12, padding: 16, boxShadow: "0 1px 3px rgba(0,0,0,0.06)", marginBottom: 24, borderLeft: "4px solid #f59e0b" }}>
            <div style={{ fontSize: 15, fontWeight: 600, color: "#0f172a", marginBottom: 12 }}>
              {T("Incidents en cours", "Active incidents")} ({activeIncidents.length})
            </div>
            {activeIncidents.map((inc) => (
              <IncidentCard key={inc.id} incident={inc} lang={lang} canAdmin={canAdmin}
                            onEdit={() => { setEditing(inc); setEditorOpen(true); }}
                            sevBadge={sevBadge} statusBadge={statusBadge} fmtDate={fmtDate} />
            ))}
          </div>
        )}

        {/* Historique */}
        <div style={{ background: "white", borderRadius: 12, padding: 16, boxShadow: "0 1px 3px rgba(0,0,0,0.06)", marginBottom: 24 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
            <div style={{ fontSize: 15, fontWeight: 600, color: "#0f172a" }}>
              {T("Historique (90 derniers jours)", "History (last 90 days)")}
            </div>
            <div style={{ fontSize: 12, color: "#64748b" }}>
              {summary && summary.incidents_90d != null
                ? T(`${summary.incidents_90d} incident(s) total`, `${summary.incidents_90d} total incident(s)`)
                : ""}
            </div>
          </div>
          {resolvedIncidents.length === 0 ? (
            <div style={{ padding: 16, textAlign: "center", color: "#94a3b8", fontSize: 13 }}>
              {T("Aucun incident résolu sur les 90 derniers jours.", "No resolved incident in the last 90 days.")}
            </div>
          ) : (
            resolvedIncidents.map((inc) => (
              <IncidentCard key={inc.id} incident={inc} lang={lang} canAdmin={canAdmin}
                            onEdit={() => { setEditing(inc); setEditorOpen(true); }}
                            sevBadge={sevBadge} statusBadge={statusBadge} fmtDate={fmtDate} />
            ))
          )}
        </div>

        {/* Boutons super-admin */}
        {canAdmin && (
          <div style={{ background: "#f1f5f9", borderRadius: 8, padding: 14, marginBottom: 24, display: "flex", alignItems: "center", gap: 10 }}>
            <div style={{ fontSize: 12.5, color: "#475569", marginRight: "auto" }}>
              <strong>{T("Mode super-admin", "Super-admin mode")}</strong> · {T("vous pouvez créer/modifier les incidents.", "you can create/edit incidents.")}
            </div>
            <button onClick={() => { setEditing(null); setEditorOpen(true); }}
              style={{
                padding: "8px 14px", borderRadius: 6,
                border: "1px solid #1d4ed8", background: "#2563eb", color: "white",
                cursor: "pointer", fontWeight: 600, fontSize: 13,
              }}>
              + {T("Nouvel incident", "New incident")}
            </button>
          </div>
        )}

        {/* Footer */}
        <div style={{ textAlign: "center", fontSize: 11, color: "#94a3b8", padding: "20px 0" }}>
          MELR · REFT Africa · {T("Politique de continuité et reprise après désastre disponible sur demande.",
            "Business continuity & disaster recovery policy available on request.")}
        </div>
      </div>

      {/* Modal editor */}
      {editorOpen && canAdmin && (
        <IncidentEditor incident={editing} lang={lang}
          onClose={() => { setEditorOpen(false); setEditing(null); }}
          onSaved={onCreated} />
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Carte d'incident
// ─────────────────────────────────────────────────────────────────────────────
function IncidentCard({ incident, lang, canAdmin, onEdit, sevBadge, statusBadge, fmtDate }) {
  const T = (fr, en) => (lang === "fr" ? fr : en);
  return (
    <div style={{
      padding: "12px 0", borderTop: "1px solid #f1f5f9",
    }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
          {sevBadge(incident.severity)}
          {statusBadge(incident.status)}
          <span style={{ fontWeight: 600, fontSize: 14 }}>{incident.title}</span>
        </div>
        {canAdmin && (
          <button onClick={onEdit}
            style={{
              padding: "3px 10px", borderRadius: 6, border: "1px solid #cbd5e1",
              background: "white", color: "#334155", cursor: "pointer", fontSize: 11.5,
            }}>
            {T("Modifier", "Edit")}
          </button>
        )}
      </div>
      {incident.description && (
        <div style={{ fontSize: 12.5, color: "#475569", marginTop: 6, whiteSpace: "pre-wrap" }}>
          {incident.description}
        </div>
      )}
      <div style={{ fontSize: 11, color: "#94a3b8", marginTop: 6 }}>
        {T("Début :", "Started:")} {fmtDate(incident.started_at)}
        {incident.resolved_at && <> · {T("Résolu :", "Resolved:")} {fmtDate(incident.resolved_at)}</>}
        {Array.isArray(incident.affected_components) && incident.affected_components.length > 0 && (
          <> · {T("Composants :", "Components:")} {incident.affected_components.join(", ")}</>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Editor super-admin (modal)
// ─────────────────────────────────────────────────────────────────────────────
function IncidentEditor({ incident, lang, onClose, onSaved }) {
  const T = (fr, en) => (lang === "fr" ? fr : en);
  const isNew = !incident;
  const [title,    setTitle]    = useStateSP(incident ? incident.title : "");
  const [description, setDescription] = useStateSP(incident ? (incident.description || "") : "");
  const [severity, setSeverity] = useStateSP(incident ? incident.severity : "minor");
  const [status,   setStatus]   = useStateSP(incident ? incident.status : "investigating");
  const [components, setComponents] = useStateSP(
    incident && Array.isArray(incident.affected_components)
      ? incident.affected_components.join(", ")
      : ""
  );
  const [busy, setBusy] = useStateSP(false);
  const [err,  setErr]  = useStateSP(null);

  const onSubmit = async () => {
    if (!title.trim()) { setErr(T("Titre requis.", "Title required.")); return; }
    setBusy(true); setErr(null);
    try {
      const payload = {
        title: title.trim(),
        description: description.trim() || null,
        severity,
        status,
        affected_components: components.split(",").map((s) => s.trim()).filter(Boolean),
      };
      if (status === "resolved" && (!incident || !incident.resolved_at)) {
        payload.resolved_at = new Date().toISOString();
      }
      if (isNew) {
        await window.melr.statusIncidentsCrud.create(payload);
      } else {
        await window.melr.statusIncidentsCrud.update(incident.id, payload);
      }
      onSaved();
    } catch (e) {
      setErr(e.message || String(e));
    } finally { setBusy(false); }
  };

  const onDelete = async () => {
    if (!incident) return;
    if (!window.confirm(T("Supprimer définitivement cet incident ?", "Permanently delete this incident?"))) return;
    setBusy(true); setErr(null);
    try {
      await window.melr.statusIncidentsCrud.remove(incident.id);
      onSaved();
    } catch (e) { setErr(e.message || String(e)); }
    finally { setBusy(false); }
  };

  return (
    <div style={{
      position: "fixed", inset: 0, background: "rgba(15,23,42,0.55)",
      display: "flex", alignItems: "center", justifyContent: "center",
      zIndex: 1000, padding: 20,
    }} onClick={() => !busy && onClose()}>
      <div style={{
        background: "white", borderRadius: 10, maxWidth: 600, width: "100%",
        padding: 24, boxShadow: "0 20px 50px rgba(0,0,0,0.25)",
        maxHeight: "90vh", overflow: "auto",
      }} onClick={(e) => e.stopPropagation()}>
        <h3 style={{ margin: 0, marginBottom: 16, fontSize: 17 }}>
          {isNew ? T("Nouvel incident", "New incident") : T("Modifier l'incident", "Edit incident")}
        </h3>

        <label style={{ display: "block", fontSize: 12, fontWeight: 600, marginBottom: 4 }}>
          {T("Titre *", "Title *")}
        </label>
        <input value={title} onChange={(e) => setTitle(e.target.value)} maxLength={120}
          style={{ width: "100%", boxSizing: "border-box", padding: 8, borderRadius: 6, border: "1px solid #cbd5e1", marginBottom: 12, fontSize: 13 }} />

        <label style={{ display: "block", fontSize: 12, fontWeight: 600, marginBottom: 4 }}>
          {T("Description (markdown)", "Description (markdown)")}
        </label>
        <textarea value={description} onChange={(e) => setDescription(e.target.value)} rows={4} maxLength={2000}
          style={{ width: "100%", boxSizing: "border-box", padding: 8, borderRadius: 6, border: "1px solid #cbd5e1", marginBottom: 12, fontSize: 13, fontFamily: "inherit", resize: "vertical" }} />

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 12 }}>
          <div>
            <label style={{ display: "block", fontSize: 12, fontWeight: 600, marginBottom: 4 }}>{T("Sévérité", "Severity")}</label>
            <select value={severity} onChange={(e) => setSeverity(e.target.value)} style={{ width: "100%", padding: 8, borderRadius: 6, border: "1px solid #cbd5e1", fontSize: 13 }}>
              <option value="minor">{T("Mineur", "Minor")}</option>
              <option value="major">{T("Majeur", "Major")}</option>
              <option value="critical">{T("Critique", "Critical")}</option>
              <option value="maintenance">{T("Maintenance", "Maintenance")}</option>
            </select>
          </div>
          <div>
            <label style={{ display: "block", fontSize: 12, fontWeight: 600, marginBottom: 4 }}>{T("Statut", "Status")}</label>
            <select value={status} onChange={(e) => setStatus(e.target.value)} style={{ width: "100%", padding: 8, borderRadius: 6, border: "1px solid #cbd5e1", fontSize: 13 }}>
              <option value="investigating">{T("Investigation", "Investigating")}</option>
              <option value="identified">{T("Cause identifiée", "Identified")}</option>
              <option value="monitoring">{T("Surveillance", "Monitoring")}</option>
              <option value="resolved">{T("Résolu", "Resolved")}</option>
            </select>
          </div>
        </div>

        <label style={{ display: "block", fontSize: 12, fontWeight: 600, marginBottom: 4 }}>
          {T("Composants affectés (séparés par virgules)", "Affected components (comma-separated)")}
        </label>
        <input value={components} onChange={(e) => setComponents(e.target.value)}
          placeholder="database, storage, edge, front"
          style={{ width: "100%", boxSizing: "border-box", padding: 8, borderRadius: 6, border: "1px solid #cbd5e1", marginBottom: 12, fontSize: 13 }} />

        {err && (
          <div style={{ padding: 10, marginBottom: 12, background: "#fee2e2", border: "1px solid #fca5a5", borderRadius: 6, color: "#7f1d1d", fontSize: 12 }}>{err}</div>
        )}

        <div style={{ display: "flex", gap: 8, justifyContent: "space-between" }}>
          <div>
            {!isNew && (
              <button onClick={onDelete} disabled={busy}
                style={{ padding: "8px 14px", borderRadius: 6, border: "1px solid #b91c1c", background: "white", color: "#dc2626", cursor: busy ? "default" : "pointer", fontSize: 12.5 }}>
                {T("Supprimer", "Delete")}
              </button>
            )}
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={onClose} disabled={busy}
              style={{ padding: "8px 14px", borderRadius: 6, border: "1px solid #94a3b8", background: "white", color: "#334155", cursor: busy ? "default" : "pointer", fontSize: 13 }}>
              {T("Annuler", "Cancel")}
            </button>
            <button onClick={onSubmit} disabled={busy}
              style={{ padding: "8px 14px", borderRadius: 6, border: "1px solid #1d4ed8", background: busy ? "#cbd5e1" : "#2563eb", color: "white", cursor: busy ? "default" : "pointer", fontWeight: 600, fontSize: 13 }}>
              {busy ? T("Enregistrement…", "Saving…") : (isNew ? T("Créer", "Create") : T("Enregistrer", "Save"))}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.StatusPage = StatusPage;
