/* Small modal for naming a manual version snapshot. */
{
  const { useEffect, useRef, useState } = React;

  function CheckpointDialog({ open, user, defaultMessage, onCancel, onSave }) {
    const [message, setMessage] = useState(defaultMessage || "");
    const [saving, setSaving] = useState(false);
    const inputRef = useRef(null);

    useEffect(() => {
      if (open) {
        setMessage(defaultMessage || "");
        setSaving(false);
        setTimeout(() => inputRef.current?.focus(), 0);
      }
    }, [open, defaultMessage]);

    if (!open) return null;

    async function handleSave() {
      const m = message.trim();
      setSaving(true);
      try {
        await onSave(m);
      } catch (e) {
        setSaving(false);
      }
    }

    function userInitial() {
      return (user?.displayName || user?.email || "?").trim().charAt(0).toUpperCase() || "?";
    }

    return (
      <div className="modal-backdrop" onClick={() => !saving && onCancel()}>
        <div className="modal checkpoint-dialog" onClick={(e) => e.stopPropagation()}>
          <div className="modal-head">
            <Icon.checkpoint />
            <h3>Save checkpoint</h3>
            <button className="close iconbtn" onClick={onCancel} disabled={saving}><Icon.close /></button>
          </div>
          <div className="modal-body">
            {user && (
              <div className="author-line">
                {user.photoURL
                  ? <img src={user.photoURL} alt="" referrerPolicy="no-referrer" style={{ borderRadius: "50%" }} />
                  : <div className="user-avatar-fallback">{userInitial()}</div>}
                <span>as <strong>{user.displayName || user.email}</strong></span>
              </div>
            )}
            <input
              ref={inputRef}
              type="text"
              placeholder="Describe what changed (optional)"
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter") handleSave();
                else if (e.key === "Escape") onCancel();
              }}
              disabled={saving}
              maxLength={200}
            />
          </div>
          <div className="modal-foot">
            <span className="hint">Keep your working copy intact. A version preserves the current state.</span>
            <button className="btn" onClick={onCancel} disabled={saving}>Cancel</button>
            <button className="btn primary" onClick={handleSave} disabled={saving}>
              {saving ? <><Icon.spinner /> Saving…</> : <><Icon.checkpoint /> Save</>}
            </button>
          </div>
        </div>
      </div>
    );
  }

  window.CheckpointDialog = CheckpointDialog;
}
