/* global React, Icon */
// ============================================================================
// Chantier K.6 · Administration / Conformité (super-admin)
// ----------------------------------------------------------------------------
// Permet au super-admin de modifier les coordonnées affichées sur la page
// Conformité publique (?compliance=1) sans déploiement :
//   - Responsable de traitement : nom, adresse, identifiant légal
//   - DPO : nom, email, téléphone/WhatsApp, adresse
//   - Sécurité : email, empreinte PGP, clé PGP publique
//
// L'écran est protégé par la permission orgs.manage (super-admin uniquement).
// La RLS de compliance_settings impose aussi private.is_super_admin_user().
// ============================================================================

const { useState: useStateCA, useEffect: useEffectCA } = React;

function ComplianceAdminScreen({ t, lang, isSuperAdmin }) {
  const { has, loading: permsLoading } = window.melr.useCurrentUserPermissions();
  const { data, loading, refresh } = window.melr.useComplianceSettings
    ? window.melr.useComplianceSettings()
    : { data: null, loading: false, refresh: () => {} };

  // Form state
  const [form, setForm] = useStateCA({});
  const [saving, setSaving] = useStateCA(false);
  const [savedAt, setSavedAt] = useStateCA(null);
  const [err, setErr] = useStateCA(null);

  // Sync form quand on récupère les valeurs depuis la BD
  useEffectCA(() => {
    if (data) setForm(data);
  }, [data]);

  if (permsLoading || loading) {
    return <div className="page"><div style={{ padding: 28 }}>{window.L("Chargement…", "Loading…", "Cargando…")}</div></div>;
  }

  const canEdit = isSuperAdmin || (has && has("orgs.manage"));
  if (!canEdit) {
    return (
      <div className="page">
        <div className="page-header">
          <div className="page-eyebrow">{window.L("CONFORMITÉ", "COMPLIANCE", "CUMPLIMIENTO")}</div>
          <h1 className="page-title">{window.L("Conformité", "Compliance", "Conformidad")}</h1>
        </div>
        <div className="card" style={{ marginTop: 16, padding: 24 }}>
          <div className="text-faint" style={{ textAlign: "center" }}>
            {window.L("Accès réservé aux super-administrateurs (permission orgs.manage).", "Super-admins only (orgs.manage permission required).", "Acceso reservado a los superadministradores (permiso orgs.manage).")}
          </div>
        </div>
      </div>
    );
  }

  const T = (fr, en) => (lang === "fr" ? fr : en);
  const setField = (k) => (e) => setForm((s) => ({ ...s, [k]: e.target.value }));

  const onSave = async () => {
    setSaving(true); setErr(null);
    try {
      const patch = { ...form };
      delete patch.id; delete patch.updated_at; delete patch.updated_by;
      await window.melr.updateComplianceSettings(patch);
      setSavedAt(new Date());
      refresh();
      setTimeout(() => setSavedAt(null), 4000);
    } catch (e) {
      setErr(e.message || String(e));
    } finally {
      setSaving(false);
    }
  };

  const labelStyle  = { display: "block", fontSize: 12, fontWeight: 600, color: "#334155", marginBottom: 4 };
  const inputStyle  = { width: "100%", boxSizing: "border-box", padding: 8, borderRadius: 6, border: "1px solid #cbd5e1", fontSize: 13, fontFamily: "inherit" };
  const textareaStyle = { ...inputStyle, resize: "vertical", minHeight: 60 };
  const fieldRow    = { marginBottom: 14 };
  const cardStyle   = { background: "white", borderRadius: 10, padding: 18, marginBottom: 16, boxShadow: "0 1px 3px rgba(0,0,0,0.04)", border: "1px solid #e2e8f0" };
  const cardTitle   = { fontSize: 14, fontWeight: 600, color: "#0f172a", marginBottom: 12, display: "flex", alignItems: "center", gap: 8 };

  return (
    <div className="page" data-screen-label="App / compliance_admin">
      <div className="page-header">
        <div className="page-eyebrow">{T("ADMINISTRATION", "ADMINISTRATION")}</div>
        <div className="page-header-row" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
          <div>
            <h1 className="page-title">{T("Conformité", "Compliance")}</h1>
            <div className="page-sub" style={{ fontSize: 13, color: "var(--text-faint)", marginTop: 4 }}>
              {T(
                "Coordonnées affichées sur la page Conformité publique (?compliance=1). Modification immédiate sans déploiement.",
                "Contact details shown on the public Compliance page (?compliance=1). Changes apply immediately without redeployment."
              )}
            </div>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <a href="/MELR?compliance=1" target="_blank" rel="noopener" className="btn-secondary"
               style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "8px 14px", fontSize: 13, textDecoration: "none" }}>
              🔗 {T("Voir la page publique", "View public page")}
            </a>
            <button onClick={onSave} disabled={saving}
              style={{
                padding: "8px 16px", borderRadius: 6, border: "1px solid #1d4ed8",
                background: saving ? "#cbd5e1" : "#2563eb", color: "white",
                cursor: saving ? "default" : "pointer", fontWeight: 600, fontSize: 13,
              }}>
              {saving ? T("Enregistrement…", "Saving…") : T("Enregistrer", "Save")}
            </button>
          </div>
        </div>
      </div>

      {/* Bannière statut save */}
      {savedAt && (
        <div style={{
          padding: "10px 14px", background: "#dcfce7", border: "1px solid #86efac",
          color: "#166534", borderRadius: 8, fontSize: 13, marginTop: 14,
        }}>
          ✓ {T("Modifications enregistrées.", "Changes saved.")}{" "}
          <span style={{ color: "#15803d", fontSize: 11.5 }}>
            ({savedAt.toLocaleTimeString(window.L("fr-FR", "en-GB", "es-ES"))})
          </span>
        </div>
      )}
      {err && (
        <div style={{
          padding: 10, marginTop: 14, background: "#fee2e2", border: "1px solid #fca5a5",
          color: "#7f1d1d", borderRadius: 8, fontSize: 13,
        }}>
          {err}
        </div>
      )}

      <div className="page-body" style={{ maxWidth: 880, marginTop: 18 }}>

        {/* === Responsable de traitement === */}
        <div style={cardStyle}>
          <div style={cardTitle}>🏢 {T("Responsable de traitement (RGPD Article 13)", "Data controller (GDPR Article 13)")}</div>

          <div style={fieldRow}>
            <label style={labelStyle}>{T("Organisation", "Organization")}</label>
            <input type="text" value={form.responsible_org_name || ""} onChange={setField("responsible_org_name")} style={inputStyle} maxLength={200} />
          </div>

          <div style={fieldRow}>
            <label style={labelStyle}>{T("Adresse postale (multiligne autorisé)", "Postal address (multiline allowed)")}</label>
            <textarea value={form.responsible_address || ""} onChange={setField("responsible_address")} style={textareaStyle} rows={3} maxLength={500} />
          </div>

          <div style={fieldRow}>
            <label style={labelStyle}>{T("Pays", "Country")}</label>
            <input type="text" value={form.responsible_country || ""} onChange={setField("responsible_country")} style={inputStyle} maxLength={80} />
          </div>

          <div style={fieldRow}>
            <label style={labelStyle}>{T("Identifiants légaux (un par ligne)", "Legal IDs (one per line)")}</label>
            <textarea value={form.responsible_legal_id || ""} onChange={setField("responsible_legal_id")}
              style={{ ...textareaStyle, fontFamily: "ui-monospace, monospace", fontSize: 12 }}
              rows={5} maxLength={500}
              placeholder={T(
                "NINEA : 1234567890123\nRC : SN-DKR-2024-B-1234\nDUNS : 123456789\nNCAGE : ABC12",
                "NINEA: 1234567890123\nRC: SN-DKR-2024-B-1234\nDUNS: 123456789\nNCAGE: ABC12"
              )} />
            <div style={{ fontSize: 11, color: "#94a3b8", marginTop: 3 }}>
              {T(
                "Listez tous les identifiants utiles (NINEA, RC, DUNS, NCAGE…) un par ligne. La page publique respectera les retours à la ligne.",
                "List every relevant ID (NINEA, RC, DUNS, NCAGE…) one per line. Line breaks are preserved on the public page."
              )}
            </div>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <div>
              <label style={labelStyle}>{T("Téléphone (organisation)", "Phone (organization)")}</label>
              <input type="text" value={form.responsible_phone || ""} onChange={setField("responsible_phone")} style={inputStyle} maxLength={50}
                placeholder="+221 ..." />
            </div>
            <div>
              <label style={labelStyle}>{T("Site web", "Website")}</label>
              <input type="url" value={form.responsible_website || ""} onChange={setField("responsible_website")} style={inputStyle} maxLength={200}
                placeholder="https://reft-africa.org" />
            </div>
          </div>
        </div>

        {/* === DPO === */}
        <div style={cardStyle}>
          <div style={cardTitle}>🛡️ {T("Délégué à la Protection des Données (DPO)", "Data Protection Officer (DPO)")}</div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 14 }}>
            <div>
              <label style={labelStyle}>{T("Nom complet", "Full name")} *</label>
              <input type="text" value={form.dpo_name || ""} onChange={setField("dpo_name")} style={inputStyle} maxLength={120} />
            </div>
            <div>
              <label style={labelStyle}>{T("Email", "Email")} *</label>
              <input type="email" value={form.dpo_email || ""} onChange={setField("dpo_email")} style={inputStyle} maxLength={120} />
            </div>
          </div>

          <div style={fieldRow}>
            <label style={labelStyle}>{T("Téléphone / WhatsApp", "Phone / WhatsApp")}</label>
            <input type="text" value={form.dpo_phone || ""} onChange={setField("dpo_phone")} style={inputStyle} maxLength={50}
              placeholder="+221 ..." />
          </div>

          <div style={fieldRow}>
            <label style={labelStyle}>{T("Adresse postale (si différente de l'organisation)", "Postal address (if different from organization)")}</label>
            <textarea value={form.dpo_address || ""} onChange={setField("dpo_address")} style={textareaStyle} rows={2} maxLength={500} />
          </div>
        </div>

        {/* === Équipe sécurité + PGP === */}
        <div style={cardStyle}>
          <div style={cardTitle}>🔐 {T("Équipe sécurité (responsible disclosure)", "Security team (responsible disclosure)")}</div>

          <div style={fieldRow}>
            <label style={labelStyle}>{T("Email équipe sécurité", "Security team email")}</label>
            <input type="email" value={form.security_email || ""} onChange={setField("security_email")} style={inputStyle} maxLength={120} />
          </div>

          <div style={fieldRow}>
            <label style={labelStyle}>{T("Empreinte PGP (PGP fingerprint)", "PGP fingerprint")}</label>
            <input type="text" value={form.security_pgp_fingerprint || ""} onChange={setField("security_pgp_fingerprint")} style={{ ...inputStyle, fontFamily: "ui-monospace, monospace", fontSize: 12 }}
              maxLength={80} placeholder="XXXX XXXX XXXX XXXX XXXX  XXXX XXXX XXXX XXXX XXXX" />
            <div style={{ fontSize: 11, color: "#94a3b8", marginTop: 3 }}>
              {T("Format standard : 40 caractères hexadécimaux, parfois espacés en groupes de 4.", "Standard format: 40 hex characters, sometimes grouped by 4.")}
            </div>
          </div>

          <div style={fieldRow}>
            <label style={labelStyle}>{T("Clé PGP publique (bloc ASCII-armored complet)", "Public PGP key (full ASCII-armored block)")}</label>
            <textarea value={form.security_pgp_key || ""} onChange={setField("security_pgp_key")}
              style={{ ...textareaStyle, fontFamily: "ui-monospace, monospace", fontSize: 11, minHeight: 200 }}
              maxLength={20000}
              placeholder={"-----BEGIN PGP PUBLIC KEY BLOCK-----\n\n...\n\n-----END PGP PUBLIC KEY BLOCK-----"} />
            <div style={{ fontSize: 11, color: "#94a3b8", marginTop: 3 }}>
              {T(
                "Coller ici la sortie de : gpg --armor --export security@reft-africa.org",
                "Paste the output of: gpg --armor --export security@reft-africa.org"
              )}
            </div>
          </div>
        </div>

        {/* Footer info */}
        <div style={{ padding: 14, background: "#eff6ff", border: "1px solid #bfdbfe", borderRadius: 8, color: "#1e40af", fontSize: 12.5, lineHeight: 1.6 }}>
          <strong>{T("💡 À noter :", "💡 Note:")}</strong>{" "}
          {T(
            "ces coordonnées sont publiées sur la page Conformité (?compliance=1) accessible sans authentification. Toute modification est immédiate. Pour des changements de raison sociale ou de DPO, pensez aussi à mettre à jour vos documents juridiques (registre des traitements, CGU, etc.).",
            "these details are published on the public Compliance page (?compliance=1) accessible without authentication. Changes are immediate. For legal name or DPO changes, also update your legal documents (records of processing activities, ToS, etc.)."
          )}
        </div>

        {form.updated_at && (
          <div style={{ marginTop: 10, padding: "6px 10px", fontSize: 11, color: "#64748b", textAlign: "right" }}>
            {T("Dernière modification :", "Last modified:")}{" "}
            {new Date(form.updated_at).toLocaleString(window.L("fr-FR", "en-GB", "es-ES"))}
          </div>
        )}
      </div>
    </div>
  );
}

window.ComplianceAdminScreen = ComplianceAdminScreen;
