/* PinGate.jsx — 4-digit numeric PIN gate.
   Light client-side gating only — PIN lives in source, not real security. */

const PIN_CONFIG = {
  pin: '6729',
  sessionKey: 'cs-pleo-unlocked',
  linkedin: 'https://www.linkedin.com/in/zhrusovska-product-design/',
};

function caseIsUnlocked() {
  try { return sessionStorage.getItem(PIN_CONFIG.sessionKey) === '1'; }
  catch (e) { return false; }
}
function markCaseUnlocked() {
  try { sessionStorage.setItem(PIN_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 [digits, setDigits] = React.useState(['', '', '', '']);
  const [error, setError]   = React.useState('');
  const [shake, setShake]   = React.useState(false);
  const refs = React.useRef([]);

  /* navigate mode — listen for external open requests */
  React.useEffect(() => {
    const onReq = (e) => {
      setHref(e.detail && e.detail.href ? e.detail.href : null);
      setDigits(['', '', '', '']);
      setError('');
      setOpen(true);
    };
    window.addEventListener('pin:request', onReq);
    return () => window.removeEventListener('pin:request', onReq);
  }, []);

  /* guard mode — open immediately if not yet unlocked */
  React.useEffect(() => {
    if (guard && !caseIsUnlocked()) setOpen(true);
  }, [guard]);

  /* focus first box shortly after open */
  React.useEffect(() => {
    if (!open) return;
    const t = setTimeout(() => refs.current[0] && refs.current[0].focus(), 140);
    return () => clearTimeout(t);
  }, [open]);

  /* lock scroll; Esc closes in navigate mode only */
  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 fillFrom = (start, str) => {
    const chars = str.replace(/[^0-9]/g, '').slice(0, 4 - start).split('');
    if (!chars.length) return;
    setError('');
    setDigits((d) => { const next = [...d]; chars.forEach((c, k) => { next[start + k] = c; }); return next; });
    setTimeout(() => { const last = Math.min(start + chars.length, 3); refs.current[last] && refs.current[last].focus(); }, 0);
  };

  const onChange = (i, val) => {
    const v = val.replace(/[^0-9]/g, '');
    if (v.length > 1) { fillFrom(i, v); return; }
    setError('');
    setDigits((d) => { const next = [...d]; next[i] = v; return next; });
    if (v && i < 3) refs.current[i + 1] && refs.current[i + 1].focus();
  };

  const onKeyDown = (i, e) => {
    if (e.key === 'Backspace' && !digits[i] && i > 0) refs.current[i - 1] && refs.current[i - 1].focus();
    else if (e.key === 'ArrowLeft'  && i > 0) refs.current[i - 1] && refs.current[i - 1].focus();
    else if (e.key === 'ArrowRight' && i < 3) refs.current[i + 1] && refs.current[i + 1].focus();
    else if (e.key === 'Enter') attempt();
  };

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

  const attempt = () => {
    const entered = digits.join('');
    if (entered.length < 4) { setError('Enter all four digits.'); doShake(); return; }
    if (entered === PIN_CONFIG.pin) {
      markCaseUnlocked();
      if (!guard && href) { window.location.href = href; return; }
      setOpen(false);
      onUnlock && onUnlock();
    } else {
      setError("That PIN didn't match. Try again.");
      doShake();
      setDigits(['', '', '', '']);
      setTimeout(() => refs.current[0] && refs.current[0].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 4-digit PIN to take a look."}</p>

        <div className={`pin-inputs${error ? ' has-error' : ''}`} role="group" aria-label="4-digit PIN">
          {digits.map((d, i) => (
            <input
              key={i}
              ref={(el) => { refs.current[i] = el; }}
              className="pin-box"
              type="password"
              inputMode="numeric"
              autoComplete="one-time-code"
              maxLength={1}
              value={d}
              onChange={(e) => onChange(i, e.target.value)}
              onKeyDown={(e) => onKeyDown(i, e)}
              onPaste={(e) => { e.preventDefault(); fillFrom(i, e.clipboardData.getData('text')); }}
              onFocus={(e) => e.target.select()}
              aria-label={`PIN digit ${i + 1}`}
            />
          ))}
        </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={PIN_CONFIG.linkedin} target="_blank" rel="noopener noreferrer">Ping me on my LinkedIn</a>
          {" and ask for it."}
        </p>

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