'use client';

/**
 * PrivacyUnlockModal — session unlock dialog with lockout countdown.
 *
 * - Single password input with autofocus.
 * - Lockout countdown (updates every second).
 * - Shake animation on wrong passphrase.
 * - "Forgot passphrase?" inline confirm with RESET literal.
 *
 * Uses <dialog> element. No emojis — SVG icons only.
 */

import { useEffect, useRef, useState } from 'react';

function formatCountdown(ms) {
  const total = Math.max(0, Math.ceil(ms / 1000));
  const m = Math.floor(total / 60);
  const s = total % 60;
  return `${m}:${s.toString().padStart(2, '0')}`;
}

export function PrivacyUnlockModal({ open, onClose, privacy }) {
  const { unlock, resetPassphrase, busy, failCount, lockoutUntil } = privacy;

  const [passphrase, setPassphrase] = useState('');
  const [localError, setLocalError] = useState('');
  const [shaking, setShaking] = useState(false);
  const [showReset, setShowReset] = useState(false);
  const [resetInput, setResetInput] = useState('');
  const [resetBusy, setResetBusy] = useState(false);
  const [countdown, setCountdown] = useState(0);

  const dialogRef = useRef(null);
  const inputRef = useRef(null);

  // Open/close
  useEffect(() => {
    const el = dialogRef.current;
    if (!el) return;
    if (open && !el.open) {
      el.showModal();
      setPassphrase('');
      setLocalError('');
      setShaking(false);
      setShowReset(false);
      setResetInput('');
    } else if (!open && el.open) {
      el.close();
    }
  }, [open]);

  // Focus input on open
  useEffect(() => {
    if (open) {
      requestAnimationFrame(() => inputRef.current?.focus());
    }
  }, [open]);

  // Escape key
  useEffect(() => {
    const el = dialogRef.current;
    if (!el) return;
    const handleCancel = (e) => {
      e.preventDefault();
      if (!busy && !resetBusy) onClose();
    };
    el.addEventListener('cancel', handleCancel);
    return () => el.removeEventListener('cancel', handleCancel);
  }, [busy, resetBusy, onClose]);

  // Lockout countdown ticker
  useEffect(() => {
    if (!lockoutUntil || lockoutUntil <= Date.now()) {
      setCountdown(0);
      return;
    }
    setCountdown(lockoutUntil - Date.now());
    const interval = setInterval(() => {
      const remaining = lockoutUntil - Date.now();
      if (remaining <= 0) {
        setCountdown(0);
        clearInterval(interval);
      } else {
        setCountdown(remaining);
      }
    }, 1000);
    return () => clearInterval(interval);
  }, [lockoutUntil]);

  const triggerShake = () => {
    setShaking(true);
    setTimeout(() => setShaking(false), 400);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLocalError('');
    if (!passphrase) return;

    const result = await unlock(passphrase);

    if (result.ok) {
      window.dispatchEvent(new CustomEvent('privacy:unlocked'));
      onClose();
      return;
    }

    triggerShake();
    setPassphrase('');

    if (result.error === 'lockout') {
      setLocalError('Too many failed attempts. See countdown above.');
      return;
    }
    if (result.error === 'wrong_passphrase') {
      const remaining = Math.max(0, 5 - (result.failCount || failCount));
      setLocalError(
        remaining > 0
          ? `Incorrect passphrase. ${remaining} attempt${remaining === 1 ? '' : 's'} remaining.`
          : 'Incorrect passphrase.',
      );
      return;
    }
    setLocalError(result.error || 'Could not unlock. Please try again.');
  };

  const handleReset = async (e) => {
    e.preventDefault();
    if (resetInput !== 'RESET') return;
    setResetBusy(true);
    try {
      await resetPassphrase();
      setShowReset(false);
      onClose();
    } finally {
      setResetBusy(false);
    }
  };

  const isLockedOut = countdown > 0;

  return (
    <dialog
      ref={dialogRef}
      className="privacy-modal-dialog"
      aria-labelledby="unlock-modal-title"
      aria-modal="true"
    >
      <div className="privacy-modal-content">
        <header className="privacy-modal-header">
          <div className="privacy-modal-icon" aria-hidden="true">
            <svg width="20" height="20" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
              <rect x="3" y="7" width="10" height="7" rx="1.5" />
              <path d="M5 7V5a3 3 0 0 1 6 0v2" />
            </svg>
          </div>
          <div>
            <b id="unlock-modal-title">Unlock protected artifacts</b>
            <small>Enter your passphrase to reveal protected content for this session.</small>
          </div>
          <button
            type="button"
            className="privacy-modal-close"
            onClick={() => { if (!busy && !resetBusy) onClose(); }}
            aria-label="Close"
            disabled={busy || resetBusy}
          >
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round">
              <line x1="2" y1="2" x2="14" y2="14" />
              <line x1="14" y1="2" x2="2" y2="14" />
            </svg>
          </button>
        </header>

        {!showReset ? (
          <>
            <form className="privacy-modal-body" onSubmit={handleSubmit} id="unlock-form">
              {isLockedOut ? (
                <div className="privacy-lockout-notice" role="status" aria-live="polite">
                  <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    <circle cx="8" cy="8" r="6.5" />
                    <line x1="8" y1="5" x2="8" y2="8.5" />
                    <circle cx="8" cy="11" r=".5" fill="currentColor" />
                  </svg>
                  <span>
                    Too many failed attempts. Try again in{' '}
                    <strong className="privacy-lockout-countdown">{formatCountdown(countdown)}</strong>.
                  </span>
                </div>
              ) : null}

              <label className="project-password-field">
                <span>Passphrase</span>
                <input
                  ref={inputRef}
                  type="password"
                  value={passphrase}
                  onChange={(e) => { setPassphrase(e.target.value); setLocalError(''); }}
                  autoComplete="current-password"
                  required
                  disabled={busy || isLockedOut}
                  placeholder="Enter passphrase"
                  className={shaking ? 'privacy-input-shake' : ''}
                  aria-describedby={localError ? 'unlock-error' : undefined}
                />
              </label>

              {localError ? (
                <p id="unlock-error" className="project-password-error" role="alert">
                  {localError}
                </p>
              ) : null}

              <button
                type="button"
                className="privacy-forgot-link"
                onClick={() => { setShowReset(true); setLocalError(''); }}
              >
                Forgot passphrase? Reset...
              </button>
            </form>

            <footer className="privacy-modal-footer">
              <button
                type="button"
                className="project-password-cancel"
                onClick={() => { if (!busy) onClose(); }}
                disabled={busy}
              >
                Cancel
              </button>
              <button
                type="submit"
                form="unlock-form"
                className="project-password-submit"
                disabled={busy || isLockedOut || !passphrase}
              >
                {busy ? 'Unlocking…' : 'Unlock'}
              </button>
            </footer>
          </>
        ) : (
          <>
            <form className="privacy-modal-body" onSubmit={handleReset} id="reset-form">
              <div className="privacy-reset-warning">
                <svg width="18" height="18" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                  <path d="M8 2L14.5 13H1.5L8 2z" />
                  <line x1="8" y1="6.5" x2="8" y2="9.5" />
                  <circle cx="8" cy="11.5" r=".4" fill="currentColor" />
                </svg>
                <p>
                  Resetting removes passphrase protection from all artifacts.
                  This cannot be undone.
                </p>
              </div>
              <label className="project-password-field">
                <span>Type <strong>RESET</strong> to confirm</span>
                <input
                  type="text"
                  value={resetInput}
                  onChange={(e) => setResetInput(e.target.value)}
                  autoComplete="off"
                  placeholder="RESET"
                  disabled={resetBusy}
                  spellCheck={false}
                />
              </label>
            </form>

            <footer className="privacy-modal-footer">
              <button
                type="button"
                className="project-password-cancel"
                onClick={() => { setShowReset(false); setResetInput(''); }}
                disabled={resetBusy}
              >
                Back
              </button>
              <button
                type="submit"
                form="reset-form"
                className="project-password-submit privacy-reset-submit"
                disabled={resetBusy || resetInput !== 'RESET'}
              >
                {resetBusy ? 'Resetting…' : 'Reset passphrase'}
              </button>
            </footer>
          </>
        )}
      </div>
    </dialog>
  );
}
