/* PinGate.jsx — single password gate, client-side only. */

const GATE_CONFIG = {
  password: 'letmein',
  sessionKey: 'cs-pleo-unlocked',
  linkedin: 'https://www.linkedin.com/in/zhrusovska-product-design/',
};

function caseIsUnlocked() {
  try { return sessionStorage.getItem(GATE_CONFIG.sessionKey) === '1'; }
  catch (e) { return false; }
}
function markCaseUnlocked() {
  try { sessionStorage.setItem(GATE_CONFIG.sessionKey, '1'); } catch (e) {}
}
function requestPinUnlock(href) {
  window.dispatchEvent(new CustomEvent('pin:request', { detail: { href: href || null } }));
}
Object.assign(window, { caseIsUnlocked, markCaseUnlocked, requestPinUnlock });

function PinGate({ guard = false, onUnlock }) {
  const [open, setOpen]         = React.useState(false);
  const [href, setHref]         = React.useState(null);
  const [password, setPassword] = React.useState('');
  const [error, setError]       = React.useState('');
  const [shake, setShake]       = React.useState(false);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    const onReq = (e) => {
      setHref(e.detail && e.detail.href ? e.detail.href : null);
      setPassword('');
      setError('');
      setOpen(true);
    };
    window.addEventListener('pin:request', onReq);
    return () => window.removeEventListener('pin:request', onReq);
  }, []);

  React.useEffect(() => {
    if (guard && !caseIsUnlocked()) setOpen(true);
  }, [guard]);

  React.useEffect(() => {
    if (!open) return;
    const t = setTimeout(() => inputRef.current && inputRef.current.focus(), 140);
    return () => clearTimeout(t);
  }, [open]);

  React.useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape' && !guard) doClose(); };
    window.addEventListener('keydown', onKey);
    return () => { document.body.style.overflow = prev; window.removeEventListener('keydown', onKey); };
  }, [open, guard]);

  const doShake = () => { setShake(true); setTimeout(() => setShake(false), 440); };

  const attempt = () => {
    const pw = password.trim();
    if (!pw) { setError('Enter the password.'); doShake(); return; }

    if (pw.toLowerCase() === GATE_CONFIG.password.toLowerCase()) {
      markCaseUnlocked();
      if (!guard && href) { window.location.href = href; return; }
      setOpen(false);
      onUnlock && onUnlock();
    } else {
      setError("That password didn't match. Try again.");
      doShake();
      setPassword('');
      setTimeout(() => inputRef.current && inputRef.current.focus(), 0);
    }
  };

  const doClose = () => {
    if (guard) { window.location.href = 'index.html'; return; }
    setOpen(false);
  };

  if (!open) return null;

  const lockIcon = (size) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      <rect x="4.5" y="10.5" width="15" height="10" rx="1.5" stroke="#000B34" strokeWidth="1.6" />
      <path d="M8 10.5V7.5a4 4 0 0 1 8 0v3" stroke="#000B34" strokeWidth="1.6" />
      <circle cx="12" cy="15" r="1.4" fill="#000B34" />
    </svg>
  );

  return (
    <div className="pin-overlay" role="dialog" aria-modal="true" aria-labelledby="pin-title">
      <div className={`pin-card${shake ? ' is-shake' : ''}`}>

        <div className="pin-lock" aria-hidden="true">{lockIcon(26)}</div>

        <h2 id="pin-title" className="pin-title">Protected case study</h2>
        <p className="pin-sub">{"This one's under wraps. Enter the password to take a look."}</p>

        <div className={`pin-field-wrap${error ? ' has-error' : ''}`}>
          <input
            ref={inputRef}
            className="pin-field"
            type="password"
            autoComplete="current-password"
            placeholder="Password"
            value={password}
            onChange={(e) => { setError(''); setPassword(e.target.value); }}
            onKeyDown={(e) => { if (e.key === 'Enter') attempt(); }}
            aria-label="Case study password"
          />
        </div>

        <div className="pin-error" aria-live="polite">{error || ' '}</div>

        <div className="pin-actions">
          <button className="btn primary pin-btn" type="button" onClick={attempt}>
            <span className="btn-label">Unlock</span>
          </button>
          <button className="btn secondary pin-btn" type="button" onClick={doClose}>
            <span className="btn-label">Close</span>
          </button>
        </div>

        <p className="pin-alt">
          {"Don't know the password? "}
          <a href={GATE_CONFIG.linkedin} target="_blank" rel="noopener noreferrer">Ping me on LinkedIn</a>
          {" and ask for it."}
        </p>

      </div>
    </div>
  );
}
window.PinGate = PinGate;
