/* RC-SHARE-002 — Viewer-side password challenge.

   Triggered when a shared-report URL includes ?locked=1. Renders a full-viewport
   challenge that gates the real app until the viewer submits the correct password.

   Demo password is 'demo123'. Real impl would POST to /shares/:token/unlock and
   receive a short-lived access cookie. Error paths covered:
     - empty submit     → inline helper
     - wrong password   → red shake + error text, attempt counter
     - 3 wrong attempts → lockout state (Contact owner CTA)

   Once unlocked, we remove ?locked from the URL and the app mounts normally. */

const LOCK_CORRECT_PW = 'demo123';
const LOCK_MAX_ATTEMPTS = 3;

function isLocked() {
  try {
    const q = new URLSearchParams(window.location.search);
    return q.get('locked') === '1';
  } catch (e) { return false; }
}

function clearLockedParam() {
  try {
    const q = new URLSearchParams(window.location.search);
    q.delete('locked');
    const s = q.toString();
    const url = s ? `${window.location.pathname}?${s}` : window.location.pathname;
    window.history.replaceState(null, '', url + window.location.hash);
  } catch (e) {}
}

const ViewerPasswordChallenge = ({ reportName = 'Shared Report', ownerName = 'Timurtek Ölmez', onUnlock }) => {
  const [pwd, setPwd] = React.useState('');
  const [show, setShow] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const [attempts, setAttempts] = React.useState(0);
  const [shake, setShake] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const inputRef = React.useRef(null);

  const lockedOut = attempts >= LOCK_MAX_ATTEMPTS;

  React.useEffect(() => {
    inputRef.current && inputRef.current.focus();
  }, []);

  const submit = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    if (lockedOut || submitting) return;
    if (!pwd.trim()) {
      setErr('Enter the password shared with you.');
      return;
    }
    setSubmitting(true);
    setErr(null);
    // Simulate ~650ms server check
    setTimeout(() => {
      setSubmitting(false);
      if (pwd === LOCK_CORRECT_PW) {
        clearLockedParam();
        onUnlock && onUnlock();
      } else {
        const next = attempts + 1;
        setAttempts(next);
        setShake(true);
        setTimeout(() => setShake(false), 420);
        if (next >= LOCK_MAX_ATTEMPTS) {
          setErr(null);
        } else {
          const left = LOCK_MAX_ATTEMPTS - next;
          setErr(`Incorrect password. ${left} attempt${left === 1 ? '' : 's'} remaining.`);
        }
        setPwd('');
        setTimeout(() => inputRef.current && inputRef.current.focus(), 50);
      }
    }, 650);
  };

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 9999,
      background: 'linear-gradient(180deg, var(--rc-bg) 0%, color-mix(in srgb, var(--rc-green) 4%, var(--rc-bg)) 100%)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24, fontFamily: 'Inter',
      color: 'var(--rc-text)',
    }}>
      <style>{`
        @keyframes rc-shake {
          0%,100% { transform: translateX(0); }
          20% { transform: translateX(-6px); }
          40% { transform: translateX(6px); }
          60% { transform: translateX(-4px); }
          80% { transform: translateX(3px); }
        }
        @keyframes rc-pulse-ring {
          0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--rc-green) 40%, transparent); }
          70% { box-shadow: 0 0 0 14px color-mix(in srgb, var(--rc-green) 0%, transparent); }
          100% { box-shadow: 0 0 0 0 transparent; }
        }
      `}</style>

      {/* MixShift product mark (top-left) */}
      <div style={{
        position: 'absolute', top: 20, left: 24,
        display: 'inline-flex', alignItems: 'center', gap: 10,
        fontSize: 12, color: 'var(--rc-text-sub)', fontFamily: 'Poppins',
      }}>
        <div style={{
          width: 24, height: 24, borderRadius: 6,
          background: 'var(--rc-green)', color: '#fff',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          fontWeight: 700, fontSize: 13,
        }}>M</div>
        <span style={{ fontWeight: 600, color: 'var(--rc-text)' }}>MixShift</span>
        <span style={{ color: 'var(--rc-text-mute)' }}>· Report Center</span>
      </div>

      {/* Spec pill (top-right) */}
      <div
        style={{
          width: 'min(440px, 100%)',
          background: 'var(--rc-card)',
          border: '1px solid var(--rc-border)',
          borderRadius: 14,
          boxShadow: '0 30px 60px -15px rgba(15,23,42,0.18), 0 0 0 1px rgba(15,23,42,0.03)',
          padding: '30px 28px 26px',
          display: 'flex', flexDirection: 'column', gap: 18,
          animation: shake ? 'rc-shake 420ms ease' : undefined,
        }}>
        {/* Lock icon */}
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <div style={{
            width: 56, height: 56, borderRadius: 16,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            background: lockedOut
              ? 'color-mix(in srgb, var(--rc-red, #dc2626) 12%, var(--rc-card))'
              : 'color-mix(in srgb, var(--rc-green) 12%, var(--rc-card))',
            border: `1px solid ${lockedOut
              ? 'color-mix(in srgb, var(--rc-red, #dc2626) 30%, var(--rc-border))'
              : 'color-mix(in srgb, var(--rc-green) 30%, var(--rc-border))'}`,
            color: lockedOut ? 'var(--rc-red, #dc2626)' : 'var(--rc-green-ink)',
            animation: !lockedOut && !submitting ? 'rc-pulse-ring 2.2s ease-out infinite' : undefined,
          }}>
            <Icon name={lockedOut ? 'alert' : 'lock'} size={24} strokeWidth={2} />
          </div>
        </div>

        {/* Title block */}
        <div style={{ textAlign: 'center', display: 'flex', flexDirection: 'column', gap: 6 }}>
          <h1 style={{
            margin: 0, fontFamily: 'Poppins',
            fontSize: 18, fontWeight: 700, letterSpacing: '-0.01em',
            color: 'var(--rc-text)',
          }}>
            {lockedOut ? 'Too many attempts' : 'Password required'}
          </h1>
          <p style={{
            margin: 0, fontSize: 12.5, color: 'var(--rc-text-sub)', lineHeight: 1.5,
          }}>
            {lockedOut
              ? <>For security, we've paused access to this report. Ask <b style={{ color: 'var(--rc-text)' }}>{ownerName}</b> for help unlocking it.</>
              : <>This report is password-protected. Enter the password shared by <b style={{ color: 'var(--rc-text)' }}>{ownerName}</b> to continue.</>
            }
          </p>
        </div>

        {/* Report card */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          padding: '10px 12px', borderRadius: 8,
          background: 'var(--rc-subtle)',
          border: '1px solid var(--rc-border)',
        }}>
          <div style={{
            width: 28, height: 28, borderRadius: 6, flexShrink: 0,
            background: 'var(--rc-card)', border: '1px solid var(--rc-border)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            color: 'var(--rc-text-sub)',
          }}>
            <Icon name="file" size={14} />
          </div>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{
              fontSize: 12.5, fontWeight: 600, color: 'var(--rc-text)',
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
            }}>{reportName}</div>
            <div style={{ fontSize: 10.5, color: 'var(--rc-text-mute)', fontFamily: 'JetBrains Mono, monospace' }}>
              Shared by {ownerName.split(' ')[0].toLowerCase()}@mixshift.io
            </div>
          </div>
        </div>

        {!lockedOut ? (
          <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <div>
              <label style={{
                display: 'block', fontSize: 11, fontWeight: 600,
                color: 'var(--rc-text-sub)', marginBottom: 6,
              }}>
                PASSWORD
              </label>
              <div style={{
                position: 'relative',
                display: 'flex', alignItems: 'stretch',
                border: `1px solid ${err ? 'var(--rc-red, #dc2626)' : 'var(--rc-border)'}`,
                borderRadius: 8,
                background: 'var(--rc-card)',
                transition: 'border-color 120ms',
              }}>
                <input
                  ref={inputRef}
                  type={show ? 'text' : 'password'}
                  value={pwd}
                  onChange={(e) => { setPwd(e.target.value); if (err) setErr(null); }}
                  disabled={submitting}
                  autoComplete="current-password"
                  placeholder="Enter password"
                  style={{
                    flex: 1, padding: '11px 12px', fontSize: 13,
                    border: 0, background: 'transparent', outline: 'none',
                    color: 'var(--rc-text)', fontFamily: 'inherit',
                    letterSpacing: show ? 0 : '0.05em',
                  }}
                  onFocus={e => e.currentTarget.parentElement.style.borderColor = err ? 'var(--rc-red, #dc2626)' : 'var(--rc-green)'}
                  onBlur={e => e.currentTarget.parentElement.style.borderColor = err ? 'var(--rc-red, #dc2626)' : 'var(--rc-border)'}
                />
                <button
                  type="button"
                  onClick={() => setShow(s => !s)}
                  title={show ? 'Hide password' : 'Show password'}
                  tabIndex={-1}
                  style={{
                    padding: '0 12px', border: 0, borderLeft: '1px solid var(--rc-border)',
                    background: 'transparent', cursor: 'pointer',
                    color: 'var(--rc-text-sub)',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    fontFamily: 'inherit',
                  }}>
                  <Icon name={show ? 'eyeOff' : 'eye'} size={14} />
                  <span style={{ fontSize: 11, marginLeft: 6, fontWeight: 500 }}>
                    {show ? 'Hide' : 'Show'}
                  </span>
                </button>
              </div>
              {err && (
                <div style={{
                  marginTop: 8, fontSize: 11.5, color: 'var(--rc-red, #dc2626)',
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                }}>
                  <Icon name="alert" size={11} strokeWidth={2} />
                  {err}
                </div>
              )}
            </div>

            <button
              type="submit"
              disabled={submitting}
              style={{
                padding: '11px 16px', borderRadius: 8, border: 0,
                background: submitting
                  ? 'color-mix(in srgb, var(--rc-green) 60%, transparent)'
                  : 'var(--rc-green)',
                color: '#fff', fontSize: 13, fontWeight: 600,
                cursor: submitting ? 'wait' : 'pointer',
                fontFamily: 'inherit',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                transition: 'background 120ms',
              }}>
              {submitting ? (
                <>
                  <span style={{
                    display: 'inline-block', width: 12, height: 12, borderRadius: '50%',
                    border: '2px solid rgba(255,255,255,0.35)', borderTopColor: '#fff',
                    animation: 'rc-spin 700ms linear infinite',
                  }} />
                  <style>{`@keyframes rc-spin { to { transform: rotate(360deg); } }`}</style>
                  Checking…
                </>
              ) : <>Unlock report</>}
            </button>

            {/* Attempt counter (pre-lockout) */}
            {attempts > 0 && attempts < LOCK_MAX_ATTEMPTS && (
              <div style={{
                textAlign: 'center', fontSize: 10.5, color: 'var(--rc-text-mute)',
                fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.03em',
              }}>
                {attempts} of {LOCK_MAX_ATTEMPTS} failed attempts
              </div>
            )}
          </form>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <a
              href={`mailto:${ownerName.split(' ')[0].toLowerCase()}@mixshift.io?subject=${encodeURIComponent(`Access to "${reportName}"`)}`}
              style={{
                padding: '11px 16px', borderRadius: 8, border: 0,
                background: 'var(--rc-green)', color: '#fff',
                fontSize: 13, fontWeight: 600, cursor: 'pointer',
                fontFamily: 'inherit', textDecoration: 'none',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              }}>
              <Icon name="mail" size={14} />
              Email the owner
            </a>
            <button
              onClick={() => { setAttempts(0); setErr(null); setPwd(''); }}
              style={{
                padding: '11px 16px', borderRadius: 8,
                border: '1px solid var(--rc-border)',
                background: 'var(--rc-card)', color: 'var(--rc-text)',
                fontSize: 12.5, fontWeight: 500, cursor: 'pointer',
                fontFamily: 'inherit',
              }}>
              Try again
            </button>
          </div>
        )}

        {/* Footer legal */}
        <div style={{
          paddingTop: 14, borderTop: '1px solid var(--rc-border)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          fontSize: 10.5, color: 'var(--rc-text-mute)',
        }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <Icon name="lock" size={10} />
            Encrypted in transit
          </span>
          <a href="#" style={{ color: 'var(--rc-text-mute)', textDecoration: 'none' }}
            onMouseEnter={e => e.currentTarget.style.color = 'var(--rc-text-sub)'}
            onMouseLeave={e => e.currentTarget.style.color = 'var(--rc-text-mute)'}>
            Privacy &amp; security
          </a>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, {
  ViewerPasswordChallenge,
  isViewerLocked: isLocked,
});
