/* global React, Btn, Eyebrow, Display, Field */
const { useState: useStateDlg, useEffect: useEffectDlg, useRef: useRefDlg } = React;

// --- Module-level dispatch registry. The DialogHost installs a listener;
// kwistDialog.* helpers enqueue dialog requests through it.
let _dispatch = null;
let _idCounter = 0;
function _enqueue(req) {
  if (typeof _dispatch !== "function") {
    // Fallback to native if the host hasn't mounted yet.
    if (req.kind === "confirm") return req.resolve(window.confirm(req.message));
    if (req.kind === "prompt")  return req.resolve(window.prompt(req.message, req.defaultValue || ""));
    if (req.kind === "alert")   { window.alert(req.message); return req.resolve(); }
    return req.resolve();
  }
  _dispatch({ ...req, id: ++_idCounter });
}

window.kwistDialog = {
  confirm(message, options = {}) {
    return new Promise((resolve) => _enqueue({ kind: "confirm", message, options, resolve }));
  },
  alert(message, options = {}) {
    return new Promise((resolve) => _enqueue({ kind: "alert", message, options, resolve }));
  },
  prompt(message, defaultValue = "", options = {}) {
    return new Promise((resolve) => _enqueue({ kind: "prompt", message, defaultValue, options, resolve }));
  },
};

function DialogHost({ theme }) {
  const [queue, setQueue] = useStateDlg([]);

  useEffectDlg(() => {
    _dispatch = (req) => setQueue((q) => [...q, req]);
    return () => { _dispatch = null; };
  }, []);

  const close = (id, value) => {
    const req = queue.find((r) => r.id === id);
    if (req) req.resolve(value);
    setQueue((q) => q.filter((r) => r.id !== id));
  };

  if (!queue.length) return null;
  const req = queue[0];

  return (
    <DialogModal theme={theme} req={req} onClose={close} />
  );
}

function DialogModal({ theme, req, onClose }) {
  const [value, setValue] = useStateDlg(req.kind === "prompt" ? (req.defaultValue || "") : "");

  useEffectDlg(() => {
    const onKey = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        onClose(req.id, req.kind === "confirm" ? false : (req.kind === "prompt" ? null : undefined));
      } else if (e.key === "Enter" && req.kind !== "prompt") {
        e.preventDefault();
        onClose(req.id, req.kind === "confirm" ? true : undefined);
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [req.id, req.kind]);

  const opts = req.options || {};
  const kindLabel = req.kind === "confirm"
    ? (opts.danger ? "── BEVESTIG" : "── BEVESTIG ACTIE")
    : req.kind === "prompt" ? "── INVOER VEREIST"
    : (opts.kind === "error" ? "── ER GING IETS MIS" : "── BERICHT");
  const title = opts.title || (req.kind === "confirm" ? "Weet je het zeker?"
    : req.kind === "prompt" ? "Vul iets in"
    : (opts.kind === "error" ? "Er ging iets mis" : "Even kijken"));

  const accentColor = (req.kind === "confirm" && opts.danger) || (req.kind === "alert" && opts.kind === "error")
    ? theme.signal
    : theme.accent;

  const submitPrompt = (e) => {
    e?.preventDefault();
    onClose(req.id, value);
  };

  return (
    <div
      onClick={(e) => {
        if (e.target === e.currentTarget) {
          onClose(req.id, req.kind === "confirm" ? false : (req.kind === "prompt" ? null : undefined));
        }
      }}
      style={{
        position: "fixed",
        inset: 0,
        background: "rgba(10,10,10,0.55)",
        backdropFilter: "blur(2px)",
        WebkitBackdropFilter: "blur(2px)",
        display: "grid",
        placeItems: "center",
        padding: 24,
        zIndex: 9999,
        animation: "kwistFade .15s ease-out",
      }}
    >
      <style>{`
        @keyframes kwistFade { from { opacity: 0 } to { opacity: 1 } }
        @keyframes kwistRise { from { transform: translateY(12px) scale(.98); opacity: 0 } to { transform: translateY(0) scale(1); opacity: 1 } }
      `}</style>

      <div style={{
        width: "min(520px, 100%)",
        background: theme.card || "#fff8ec",
        color: theme.fg,
        border: `2.5px solid ${theme.fg}`,
        boxShadow: `8px 8px 0 0 ${theme.fg}`,
        position: "relative",
        animation: "kwistRise .2s ease-out",
      }}>
        <div style={{
          padding: "20px 28px 14px",
          borderBottom: `2px solid ${theme.fg}`,
          background: theme.bg2,
          position: "relative",
        }}>
          <Eyebrow theme={theme} style={{ color: accentColor, marginBottom: 10 }}>{kindLabel}</Eyebrow>
          <Display theme={theme} size={32} style={{ lineHeight: 1.05, paddingRight: 36 }}>{title}</Display>

          <button
            onClick={() => onClose(req.id, req.kind === "confirm" ? false : (req.kind === "prompt" ? null : undefined))}
            aria-label="Sluiten"
            style={{
              position: "absolute", top: 14, right: 16,
              width: 28, height: 28, lineHeight: "26px", textAlign: "center",
              background: "transparent", border: `1.5px solid ${theme.fg}`,
              color: theme.fg, cursor: "pointer",
              fontFamily: theme.fonts.display, fontSize: 16, fontWeight: 700,
            }}
          >×</button>
        </div>

        <div style={{ padding: "22px 28px 24px" }}>
          <p style={{
            margin: 0,
            fontSize: 15, lineHeight: 1.55,
            color: theme.fg, whiteSpace: "pre-wrap",
          }}>{req.message}</p>

          {req.kind === "prompt" && (
            <form onSubmit={submitPrompt} style={{ marginTop: 18 }}>
              <Field
                theme={theme}
                value={value}
                onChange={setValue}
                placeholder={opts.placeholder || ""}
                autoFocus
              />
            </form>
          )}

          <div style={{
            marginTop: 22,
            display: "flex",
            gap: 10,
            justifyContent: "flex-end",
            flexWrap: "wrap",
          }}>
            {req.kind === "confirm" && (
              <>
                <Btn theme={theme} variant="outline" size="md"
                  onClick={() => onClose(req.id, false)}>
                  {opts.cancelLabel || "Annuleren"}
                </Btn>
                <button
                  autoFocus
                  onClick={() => onClose(req.id, true)}
                  style={{
                    background: accentColor,
                    color: "#fff",
                    border: `2px solid ${theme.fg}`,
                    boxShadow: `5px 5px 0 0 ${theme.fg}`,
                    padding: "12px 22px",
                    fontFamily: theme.fonts.display, fontWeight: 800, fontSize: 15,
                    textTransform: "lowercase", letterSpacing: "-0.005em",
                    cursor: "pointer",
                    fontStyle: "italic",
                  }}
                >{opts.confirmLabel || (opts.danger ? "Verwijder" : "Doorgaan")} →</button>
              </>
            )}

            {req.kind === "alert" && (
              <button
                autoFocus
                onClick={() => onClose(req.id, undefined)}
                style={{
                  background: theme.fg,
                  color: theme.cream || "#fff8ec",
                  border: `2px solid ${theme.fg}`,
                  boxShadow: `5px 5px 0 0 ${accentColor}`,
                  padding: "12px 28px",
                  fontFamily: theme.fonts.display, fontWeight: 800, fontSize: 15,
                  textTransform: "lowercase",
                  cursor: "pointer",
                  fontStyle: "italic",
                }}
              >{opts.okLabel || "Begrepen"}</button>
            )}

            {req.kind === "prompt" && (
              <>
                <Btn theme={theme} variant="outline" size="md"
                  onClick={() => onClose(req.id, null)}>
                  Annuleren
                </Btn>
                <button
                  onClick={submitPrompt}
                  style={{
                    background: theme.accent,
                    color: "#fff",
                    border: `2px solid ${theme.fg}`,
                    boxShadow: `5px 5px 0 0 ${theme.fg}`,
                    padding: "12px 22px",
                    fontFamily: theme.fonts.display, fontWeight: 800, fontSize: 15,
                    textTransform: "lowercase",
                    cursor: "pointer",
                    fontStyle: "italic",
                  }}
                >Bevestig →</button>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.DialogHost = DialogHost;
