// ============================================================
// modals.jsx · 4 system modals + reusable email mock
// ============================================================

// ---- Modal shell ----
function ModalShell({ width = 500, onClose, dismissable = true, children }) {
  useEffect(() => {
    const onKey = e => { if (e.key === "Escape" && dismissable && onClose) onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [dismissable, onClose]);
  return (
    <div className="xk-modal-backdrop" onClick={() => dismissable && onClose && onClose()} style={{ position: "absolute", inset: 0, zIndex: 100,
      background: "rgba(15,14,12,0.42)", backdropFilter: "blur(3px)", animation: "backdrop-fade 0.2s ease both",
      display: "flex", alignItems: "center", justifyContent: "center", padding: 24 }}>
      <div className="animate-slide-up" onClick={e => e.stopPropagation()} role="dialog" aria-modal="true"
        style={{ width: "100%", maxWidth: width, background: "var(--xk-surface)", borderRadius: 14,
          boxShadow: "var(--xk-shadow-lg)", overflow: "hidden", maxHeight: "calc(100% - 16px)", display: "flex", flexDirection: "column" }}>
        {children}
      </div>
    </div>
  );
}
window.ModalShell = ModalShell;

// ---- M-CONFIRM-CANCEL (soft, no warning icon) ----
function MConfirmCancel({ onClose, onConfirm, description }) {
  return (
    <ModalShell width={480} onClose={onClose}>
      <div style={{ padding: 24 }}>
        <h3 style={{ margin: 0, fontSize: 17, fontWeight: 600 }}>Cancelar configuración</h3>
        <p style={{ margin: "10px 0 0", fontSize: 13.5, color: "var(--xk-text-secondary)", lineHeight: 1.55 }}>
          {description || "Lo configurado hasta ahora se guarda · puedes retomar después con el mismo link."}
        </p>
        <div style={{ display: "flex", gap: 10, marginTop: 22, justifyContent: "flex-end" }}>
          <Btn variant="ghost" onClick={onConfirm}>Sí, salir</Btn>
          <Btn variant="secondary" onClick={onClose}>Seguir configurando</Btn>
        </div>
      </div>
    </ModalShell>
  );
}
window.MConfirmCancel = MConfirmCancel;

// ---- M-CONFIRM-DESTRUCTIVE (with optional type-to-confirm) ----
function MConfirmDestructive({ onClose, onConfirm, title = "Acción irreversible", description, actionLabel = "Sí, continuar", confirmWord, affected }) {
  const [typed, setTyped] = useState("");
  const needsType = !!confirmWord && (affected == null || affected > 100);
  const canConfirm = !needsType || typed.trim().toUpperCase() === confirmWord.toUpperCase();
  return (
    <ModalShell width={500} onClose={onClose} dismissable={true}>
      <div style={{ padding: 24 }}>
        <div style={{ display: "flex", gap: 13, alignItems: "flex-start" }}>
          <span style={{ width: 38, height: 38, borderRadius: 10, background: "var(--xk-danger-tint)", color: "var(--xk-danger)", display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <Icon name="alert-triangle" size={19} />
          </span>
          <div style={{ flex: 1 }}>
            <h3 style={{ margin: 0, fontSize: 17, fontWeight: 600 }}>{title}</h3>
            <p style={{ margin: "8px 0 0", fontSize: 13.5, color: "var(--xk-text-secondary)", lineHeight: 1.55 }}>{description}</p>
          </div>
        </div>
        {needsType && (
          <div style={{ marginTop: 18 }}>
            <Label>Escribe <span style={{ fontFamily: "var(--xk-font-mono)", color: "var(--xk-text)" }}>{confirmWord}</span> para confirmar</Label>
            <input className="xk-input" value={typed} onChange={e => setTyped(e.target.value)} placeholder={confirmWord}
              style={{ fontFamily: "var(--xk-font-mono)", letterSpacing: "0.04em" }} />
          </div>
        )}
        <div style={{ display: "flex", gap: 10, marginTop: 22, justifyContent: "flex-end" }}>
          <Btn variant="secondary" onClick={onClose}>Cancelar</Btn>
          <Btn variant="danger" disabled={!canConfirm} onClick={onConfirm}>{actionLabel}</Btn>
        </div>
      </div>
    </ModalShell>
  );
}
window.MConfirmDestructive = MConfirmDestructive;

// ---- M-IMPORT-PROGRESS (cannot close) ----
function MImportProgress({ title = "Importando personal…", phases, error }) {
  const def = phases || [
    { label: "Validando filas", status: "done" },
    { label: "Creando cuentas", status: "active", pct: 67 },
    { label: "Vinculando con grupos", status: "pending" },
  ];
  return (
    <ModalShell width={460} dismissable={false}>
      <div style={{ padding: 24 }}>
        <h3 style={{ margin: "0 0 18px", fontSize: 16, fontWeight: 600 }}>{title}</h3>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {def.map((p, i) => (
            <div key={i}>
              <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
                <span style={{ width: 22, height: 22, borderRadius: 999, display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
                  background: p.status === "done" ? "var(--xk-success-tint)" : p.status === "error" ? "var(--xk-danger-tint)" : "transparent" }}>
                  {p.status === "done" && <Icon name="check" size={13} color="var(--xk-success)" />}
                  {p.status === "active" && <Spinner size={16} />}
                  {p.status === "error" && <Icon name="x" size={13} color="var(--xk-danger)" />}
                  {p.status === "pending" && <span style={{ width: 8, height: 8, borderRadius: 999, background: "var(--xk-border-strong)" }}></span>}
                </span>
                <span style={{ fontSize: 13.5, fontWeight: p.status === "active" ? 600 : 500,
                  color: p.status === "pending" ? "var(--xk-text-muted)" : "var(--xk-text)" }}>{p.label}</span>
                {p.status === "active" && <span style={{ marginLeft: "auto", fontSize: 12, fontFamily: "var(--xk-font-mono)", color: "var(--xk-accent)" }}>{p.pct}%</span>}
              </div>
              {p.status === "active" && (
                <div style={{ marginLeft: 33, marginTop: 8, height: 5, background: "var(--xk-surface-2)", borderRadius: 999, overflow: "hidden" }}>
                  <div style={{ height: "100%", width: p.pct + "%", background: "var(--xk-accent)", borderRadius: 999, transition: "width 400ms ease" }}></div>
                </div>
              )}
              {p.status === "error" && <div style={{ marginLeft: 33, marginTop: 8 }}><Btn variant="secondary" size="sm" icon="refresh-cw">Reintentar fase</Btn></div>}
            </div>
          ))}
        </div>
        {!error && <p style={{ margin: "18px 0 0", fontSize: 11.5, color: "var(--xk-text-muted)" }}>No cierres esta ventana · se cierra sola al terminar.</p>}
      </div>
    </ModalShell>
  );
}
window.MImportProgress = MImportProgress;

// ============================================================
// Reusable email mock — Xokai outbound OR tenant-branded
// ============================================================
function EmailMock({ branded = false, scale = 1 }) {
  const brand = "var(--tenant-brand)";
  if (branded) {
    return (
      <div style={{ border: "1px solid var(--xk-border)", borderRadius: 12, overflow: "hidden", background: "#fff", maxWidth: 460, margin: "0 auto" }}>
        <div style={{ padding: "10px 16px", background: "var(--xk-surface-2)", borderBottom: "1px solid var(--xk-border)", fontSize: 11.5, color: "var(--xk-text-muted)" }}>
          De: {window.b("school.short_name")} &lt;hola@xokai.app&gt; · Para: ezdraz.padre@gmail.com
        </div>
        <div style={{ padding: "16px 22px", display: "flex", alignItems: "center", borderBottom: "1px solid var(--xk-border)", background: "color-mix(in oklab, var(--tenant-brand) 8%, white)" }}>
          <TenantLockup height={44} />
        </div>
        <div style={{ padding: "22px 24px" }}>
          <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 12 }}>Hola {window.b("guardian.first_name")},</div>
          <p style={{ fontSize: 13.5, color: "var(--xk-text-secondary)", lineHeight: 1.6, margin: "0 0 12px" }}>
            A partir de este ciclo, {window.b("school.short_name")} usa Xokai para acompañar el día a día con las familias · pickup, avisos, calendario y comunicación con los maestros.
          </p>
          <p style={{ fontSize: 13.5, color: "var(--xk-text-secondary)", lineHeight: 1.6, margin: "0 0 18px" }}>
            Tu acceso ya está listo · entra con un click, sin password.
          </p>
          <a href="#" onClick={e => e.preventDefault()} style={{ display: "inline-block", background: brand, color: "#fff", padding: "11px 20px", borderRadius: 9, fontSize: 14, fontWeight: 500, textDecoration: "none" }}>
            Entrar a {window.b("school.short_name")} →
          </a>
          <p style={{ fontSize: 11.5, color: "var(--xk-text-muted)", lineHeight: 1.6, margin: "22px 0 0", borderTop: "1px solid var(--xk-border)", paddingTop: 14 }}>
            El link es personal y expira en 7 días. Para dudas escribe a coordinacion@habitatlc.mx. — Equipo {window.b("school.short_name")}
            <br /><br />Al acceder, aceptas el <a href="#" onClick={e => e.preventDefault()} style={{ color: "var(--xk-text-secondary)", textDecoration: "underline" }}>Aviso de Privacidad</a> de {window.b("school.short_name")} y de <a href="#" onClick={e => e.preventDefault()} style={{ color: "var(--xk-text-secondary)", textDecoration: "underline" }}>Xokai</a>.
          </p>
        </div>
      </div>
    );
  }
  // Xokai outbound (A4 / A5)
  return (
    <div style={{ border: "1px solid var(--xk-border)", borderRadius: 12, overflow: "hidden", background: "#fff", maxWidth: 460, margin: "0 auto" }}>
      <div style={{ padding: "10px 16px", background: "var(--xk-surface-2)", borderBottom: "1px solid var(--xk-border)", fontSize: 11.5, color: "var(--xk-text-muted)" }}>
        De: Xokai &lt;hola@xokai.app&gt; · Para: {window.b("director.email")}
      </div>
      <div style={{ padding: "14px 22px", borderBottom: "1px solid var(--xk-border)" }}><XokaiLockup size={24} /></div>
      <div style={{ padding: "22px 24px" }}>
        <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 12 }}>{window.b("school.short_name")} ya está en Xokai</div>
        <p style={{ fontSize: 13.5, color: "var(--xk-text-secondary)", lineHeight: 1.6, margin: "0 0 12px" }}>
          Hola {window.b("director.first_name")}, la cuenta de Xokai para {window.b("school.name")} ya está creada. Solo faltan unos minutos de configuración para dejarla lista.
        </p>
        <a href="#" onClick={e => e.preventDefault()} style={{ display: "inline-block", background: "var(--xk-accent)", color: "#fff", padding: "11px 20px", borderRadius: 9, fontSize: 14, fontWeight: 500, textDecoration: "none" }}>
          Entrar a configurar →
        </a>
        <p style={{ fontSize: 11.5, color: "var(--xk-text-muted)", lineHeight: 1.6, margin: "22px 0 0", borderTop: "1px solid var(--xk-border)", paddingTop: 14 }}>
          El link expira en 24 h. Para cualquier duda escríbenos a hola@xokai.app. — Equipo Xokai
        </p>
      </div>
    </div>
  );
}
window.EmailMock = EmailMock;

// ---- M-PREVIEW-EMAIL ----
function MPreviewEmail({ onClose, branded = false, onConfirm }) {
  return (
    <ModalShell width={560} onClose={onClose}>
      <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--xk-border)", display: "flex", alignItems: "center" }}>
        <h3 style={{ margin: 0, fontSize: 15, fontWeight: 600 }}>Vista previa del email</h3>
        <button onClick={onClose} className="xk-iconbtn"><Icon name="x" size={18} /></button>
      </div>
      <div className="no-scrollbar" style={{ padding: 22, overflowY: "auto", background: "var(--xk-bg)" }}>
        <EmailMock branded={branded} />
      </div>
      <div style={{ padding: "14px 22px", borderTop: "1px solid var(--xk-border)", display: "flex", justifyContent: "flex-end", gap: 10 }}>
        <Btn variant="ghost" onClick={onClose}>Cerrar</Btn>
        <Btn variant="primary" onClick={onConfirm || onClose}>Confirmar y enviar</Btn>
      </div>
    </ModalShell>
  );
}
window.MPreviewEmail = MPreviewEmail;
