'use client';

/**
 * PrivacyPassphraseModal — two-screen passphrase setup dialog.
 *
 * Screen 1: Intro + risk disclosure checkbox.
 * Screen 2: Passphrase entry + confirm + strength indicator.
 *
 * Uses <dialog> element with autofocus. No emojis — SVG lock icon only.
 */

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

function strengthScore(passphrase) {
  if (!passphrase) return 0;
  let score = 0;
  if (/[a-z]/.test(passphrase)) score += 1;
  if (/[A-Z]/.test(passphrase)) score += 1;
  if (/[0-9]/.test(passphrase)) score += 1;
  if (/[^a-zA-Z0-9]/.test(passphrase)) score += 1;
  if (passphrase.length >= 12) score += 1;
  return score; // 0–5
}

function StrengthBar({ passphrase }) {
  const score = strengthScore(passphrase);
  const label = score <= 1 ? 'Weak' : score <= 3 ? 'OK' : 'Strong';
  const color = score <= 1 ? '#c2452a' : score <= 3 ? '#f0a32c' : '#28a74a';
  const pct = Math.round((score / 5) * 100);
  return (
    <div className="privacy-strength-bar" aria-label={`Passphrase strength: ${label}`}>
      <div className="privacy-strength-track">
        <div
          className="privacy-strength-fill"
          style={{ width: `${pct}%`, background: color }}
        />
      </div>
      <span className="privacy-strength-label" style={{ color }}>{label}</span>
    </div>
  );
}

export function PrivacyPassphraseModal({ open, onClose, privacy }) {
  const { setupPassphrase, busy } = privacy;

  const [screen, setScreen] = useState(1);
  const [understood, setUnderstood] = useState(false);
  const [passphrase, setPassphrase] = useState('');
  const [confirm, setConfirm] = useState('');
  const [localError, setLocalError] = useState('');

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

  // Open/close the <dialog>
  useEffect(() => {
    const el = dialogRef.current;
    if (!el) return;
    if (open && !el.open) {
      el.showModal();
      // Reset state on each open
      setScreen(1);
      setUnderstood(false);
      setPassphrase('');
      setConfirm('');
      setLocalError('');
    } else if (!open && el.open) {
      el.close();
    }
  }, [open]);

  // Focus first interactive element when screen changes
  useEffect(() => {
    if (open) {
      requestAnimationFrame(() => firstInputRef.current?.focus());
    }
  }, [open, screen]);

  // Escape closes via native <dialog> — also call onClose
  useEffect(() => {
    const el = dialogRef.current;
    if (!el) return;
    const handleCancel = (e) => {
      e.preventDefault(); // prevent default close so we control it
      if (!busy) onClose();
    };
    el.addEventListener('cancel', handleCancel);
    return () => el.removeEventListener('cancel', handleCancel);
  }, [busy, onClose]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLocalError('');

    if (passphrase.length < 8) {
      setLocalError('Passphrase must be at least 8 characters.');
      return;
    }
    if (passphrase !== confirm) {
      setLocalError('Passphrases do not match.');
      return;
    }

    const result = await setupPassphrase(passphrase);
    if (result.ok) {
      onClose();
    } else {
      setLocalError(result.error || 'Could not save passphrase. Please try again.');
    }
  };

  return (
    <dialog
      ref={dialogRef}
      className="privacy-modal-dialog"
      aria-labelledby="privacy-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="privacy-modal-title">
              {screen === 1 ? 'Set a privacy passphrase' : 'Choose your passphrase'}
            </b>
            <small>
              {screen === 1
                ? 'Before you start, understand what this protects.'
                : 'Your passphrase never leaves your browser.'}
            </small>
          </div>
          <button
            type="button"
            className="privacy-modal-close"
            onClick={() => { if (!busy) onClose(); }}
            aria-label="Close"
            disabled={busy}
          >
            <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>

        {screen === 1 ? (
          <div className="privacy-modal-body">
            <div className="privacy-modal-info-block">
              <p className="privacy-modal-info-heading">What this protects</p>
              <ul className="privacy-modal-info-list">
                <li>Over-the-shoulder viewing of blurred artifact thumbnails</li>
                <li>Casual access on a shared or borrowed device</li>
                <li>Persistent exposure from a forgotten open tab</li>
              </ul>
            </div>
            <div className="privacy-modal-info-block privacy-modal-info-block--warn">
              <p className="privacy-modal-info-heading">What this does NOT protect against</p>
              <ul className="privacy-modal-info-list">
                <li>Disk access — files are unencrypted on your filesystem</li>
                <li>Someone with DevTools or sessionStorage access</li>
                <li>Server-side API calls (artifact body is still returned to any caller)</li>
              </ul>
            </div>
            <label className="privacy-modal-checkbox" ref={firstInputRef} tabIndex={-1}>
              <input
                ref={firstInputRef}
                type="checkbox"
                checked={understood}
                onChange={(e) => setUnderstood(e.target.checked)}
              />
              <span>I understand this protects against casual access, not determined attackers.</span>
            </label>
          </div>
        ) : (
          <form className="privacy-modal-body" onSubmit={handleSubmit} id="privacy-passphrase-form">
            <label className="project-password-field">
              <span>Passphrase</span>
              <input
                ref={firstInputRef}
                type="password"
                value={passphrase}
                onChange={(e) => { setPassphrase(e.target.value); setLocalError(''); }}
                autoComplete="new-password"
                minLength={8}
                required
                disabled={busy}
                placeholder="At least 8 characters"
              />
            </label>
            {passphrase ? <StrengthBar passphrase={passphrase} /> : null}
            <label className="project-password-field">
              <span>Confirm passphrase</span>
              <input
                type="password"
                value={confirm}
                onChange={(e) => { setConfirm(e.target.value); setLocalError(''); }}
                autoComplete="new-password"
                minLength={8}
                required
                disabled={busy}
                placeholder="Re-enter passphrase"
              />
            </label>
            {localError ? (
              <p className="project-password-error" role="alert">{localError}</p>
            ) : null}
            <p className="project-password-note">
              The passphrase never leaves your browser. There is no recovery — if you forget it,
              resetting privacy removes the protected flag from every artifact.
            </p>
          </form>
        )}

        <footer className="privacy-modal-footer">
          <button
            type="button"
            className="project-password-cancel"
            onClick={() => { if (!busy) onClose(); }}
            disabled={busy}
          >
            Cancel
          </button>
          {screen === 1 ? (
            <button
              type="button"
              className="project-password-submit"
              disabled={!understood}
              onClick={() => setScreen(2)}
            >
              Continue
            </button>
          ) : (
            <button
              type="submit"
              form="privacy-passphrase-form"
              className="project-password-submit"
              disabled={busy || passphrase.length < 8 || passphrase !== confirm}
            >
              {busy ? 'Setting passphrase…' : 'Set passphrase'}
            </button>
          )}
        </footer>
      </div>
    </dialog>
  );
}
