/* ─────────────────────────────────────────────────────────────────────
   Access control — password gate + private Sunday-pool section
   ─────────────────────────────────────────────────────────────────────

   ┌─────────────────────────────────────────────────────────────────┐
   │  HOW IT WORKS — two shared passwords:                            │
   │                                                                   │
   │  • POOL_PASSWORD   → guest is "pool approved": sees the whole     │
   │                      site, including the private Sunday pool.     │
   │  • GUEST_PASSWORD  → guest sees the wedding & welcome party only; │
   │                      the Sunday pool section stays hidden.        │
   │                                                                   │
   │  TO TURN THE GATE ON:                                            │
   │  1. Set  GATE_ENABLED = true                                      │
   │  2. Set the two passwords below to whatever you like.            │
   │  3. Share the pool password only with pool-approved guests, and   │
   │     the guest password with everyone else.                        │
   │                                                                   │
   │  Password matching ignores case and surrounding spaces.          │
   │                                                                   │
   │  While GATE_ENABLED is false, the site behaves as a normal       │
   │  public site: no gate, and the Sunday pool section is visible    │
   │  to everyone. Nothing is locked until you flip it on.            │
   └─────────────────────────────────────────────────────────────────┘

   Note: this is browser-side gating — perfect for keeping the pool
   invite away from casual eyes, but not bank-grade security. A
   determined guest could read the page source.
*/

const GATE_ENABLED = true;

/* Pool-approved password — these guests see everything, incl. Sunday pool. */
const POOL_PASSWORD = 'quedense';

/* General password — wedding & welcome party only (no Sunday pool). */
const GUEST_PASSWORD = 'bienvenidos';

/* ── normalize: lowercase, trim, and strip accents/diacritics ──
   so "quédense" and "quedense" both match. ── */
function normalizePass(s) {
  return (s || '')
    .toLowerCase()
    .trim()
    .normalize('NFD')                 // split accented letters into base + accent
    .replace(/[\u0300-\u036f]/g, ''); // remove the accent marks
}

const POOL_PASS = normalizePass(POOL_PASSWORD);
const GUEST_PASS = normalizePass(GUEST_PASSWORD);
const STORAGE_KEY = 'sa_wedding_access'; // stores 'pool' | 'guest'

const AccessContext = React.createContext({
  gateEnabled: false, authed: true, poolOK: true, level: 'pool', signOut: function () {}
});
window.AccessContext = AccessContext;

/* Map a typed password to an access level, or null if it doesn't match. */
function levelForPassword(pass) {
  const p = normalizePass(pass);
  if (p && p === POOL_PASS) return 'pool';
  if (p && p === GUEST_PASS) return 'guest';
  return null;
}

/* ───────────────────────── Password gate overlay ─────────────────────────
   The artwork PNGs carry all the visual design (title, copy, password line,
   Enter button). We render the correct PNG full-bleed inside a stage scaled
   to COVER the viewport, then lay transparent interactive fields precisely
   over the baked-in password line and Enter button. */

/* Native artwork dimensions. */
const GATE_ART = {
  desktop: {
    src: 'assets/gate-desktop.png', w: 1672, h: 941, lineBg: 'rgb(151,15,18)', maskUp: 6,
    input: { left: 584, top: 590, width: 508, height: 50 },
    toggle: { left: 942, top: 606, width: 150, size: 15, align: 'right', long: false },
    button: { left: 730, top: 698, width: 212, height: 96 },
    error: { left: 546, top: 650, width: 580, size: 18 }
  },
  mobile: {
    src: 'assets/gate-mobile.png', w: 941, h: 1672, lineBg: 'rgb(47,22,19)', maskUp: 58,
    input: { left: 90, top: 1072, width: 760, height: 52 },
    toggle: { left: 60, top: 1152, width: 820, size: 22, align: 'center', long: true },
    button: { left: 352, top: 1250, width: 238, height: 108 },
    error: { left: 60, top: 1190, width: 820, size: 20 }
  }
};

function useGateArt() {
  const query = '(max-width: 768px)';
  const [isMobile, setIsMobile] = React.useState(function () {
    return typeof window !== 'undefined' && window.matchMedia(query).matches;
  });
  React.useEffect(function () {
    const mq = window.matchMedia(query);
    const on = function (e) { setIsMobile(e.matches); };
    if (mq.addEventListener) mq.addEventListener('change', on);else mq.addListener(on);
    return function () { if (mq.removeEventListener) mq.removeEventListener('change', on);else mq.removeListener(on); };
  }, []);
  return isMobile ? GATE_ART.mobile : GATE_ART.desktop;
}

function PasswordGate({ onSubmit }) {
  const [value, setValue] = React.useState('');
  const [error, setError] = React.useState(false);
  const [showPw, setShowPw] = React.useState(false);
  const art = useGateArt();
  const [scale, setScale] = React.useState(1);

  React.useEffect(function () {
    function fit() { setScale(Math.max(window.innerWidth / art.w, window.innerHeight / art.h)); }
    fit();
    window.addEventListener('resize', fit);
    return function () { window.removeEventListener('resize', fit); };
  }, [art.w, art.h]);

  function handle(e) {
    e.preventDefault();
    const ok = onSubmit(value);
    if (!ok) setError(true);
  }

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 9999,
      background: '#2a0a0e', overflow: 'hidden'
    }}>
      <div style={{
        position: 'absolute', left: '50%', top: '50%',
        width: art.w, height: art.h,
        transform: 'translate(-50%, -50%) scale(' + scale + ')',
        transformOrigin: 'center center'
      }}>
        <img
          src={art.src}
          alt="You&rsquo;re invited &mdash; Sydney &amp; Andr&eacute;s &middot; Tepoztl&aacute;n &middot; April 30 &ndash; May 2, 2027"
          draggable={false}
          style={{ position: 'absolute', inset: 0, width: art.w, height: art.h, display: 'block', userSelect: 'none' }} />

        <form onSubmit={handle} style={{ position: 'absolute', inset: 0, margin: 0 }}>
          {/* Mask the baked-in "Password" placeholder once the guest starts typing. */}
          {value.length > 0 ?
            <div style={{
              position: 'absolute',
              left: art.input.left - 20, top: art.input.top - art.maskUp,
              width: art.input.width + 40, height: art.input.height + art.maskUp,
              background: art.lineBg,
              WebkitMaskImage: 'linear-gradient(to bottom, transparent 0%, #000 40%, #000 100%), linear-gradient(to right, transparent 0%, #000 12%, #000 88%, transparent 100%)',
              maskImage: 'linear-gradient(to bottom, transparent 0%, #000 40%, #000 100%), linear-gradient(to right, transparent 0%, #000 12%, #000 88%, transparent 100%)',
              WebkitMaskComposite: 'source-in',
              maskComposite: 'intersect'
            }} /> : null}

          <input
            type={showPw ? 'text' : 'password'}
            value={value}
            autoFocus
            onChange={function (e) { setValue(e.target.value); if (error) setError(false); }}
            aria-label="Password"
            style={{
              position: 'absolute',
              left: art.input.left, top: art.input.top,
              width: art.input.width, height: art.input.height,
              textAlign: 'center',
              background: 'transparent', border: 'none', outline: 'none',
              color: '#F0E8D0',
              fontFamily: 'var(--font-body)', fontWeight: 300,
              fontSize: 28, letterSpacing: showPw ? '0.06em' : '0.35em'
            }} />

          <button
            type="button"
            onClick={function () { setShowPw(function (s) { return !s; }); }}
            aria-pressed={showPw}
            style={{
              position: 'absolute',
              left: art.toggle.left, top: art.toggle.top, width: art.toggle.width,
              textAlign: art.toggle.align,
              background: 'transparent', border: 'none', cursor: 'pointer',
              padding: 0, appearance: 'none', WebkitTapHighlightColor: 'transparent',
              fontFamily: 'var(--font-body)', fontWeight: 400, fontSize: art.toggle.size,
              letterSpacing: '0.14em', textTransform: 'uppercase', whiteSpace: 'nowrap',
              color: 'color-mix(in srgb, #F0E8D0 82%, transparent)'
            }}>
            {art.toggle.long
              ? (showPw ? 'Hide password' : 'Show password')
              : (showPw ? 'Hide' : 'Show')}
          </button>

          <div style={{
            position: 'absolute',
            left: art.error.left, top: art.error.top, width: art.error.width,
            textAlign: 'center',
            fontFamily: 'var(--font-body)', fontWeight: 400, fontSize: art.error.size,
            color: '#F0E8D0', textShadow: '0 1px 8px rgba(0,0,0,0.65)',
            opacity: error ? 1 : 0, transition: 'opacity 200ms ease',
            pointerEvents: 'none'
          }}>
            That password didn&rsquo;t match &mdash; please check with Sydney &amp; Andr&eacute;s.
          </div>

          <button type="submit" aria-label="Enter" style={{
            position: 'absolute',
            left: art.button.left, top: art.button.top,
            width: art.button.width, height: art.button.height,
            background: 'transparent', border: 'none', cursor: 'pointer',
            borderRadius: '999px', appearance: 'none',
            WebkitTapHighlightColor: 'transparent'
          }} />
        </form>
      </div>
    </div>
  );
}

/* ───────────────────────── Provider ───────────────────────── */
function AccessProvider({ children }) {
  const [level, setLevel] = React.useState(function () {
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      return (stored === 'pool' || stored === 'guest') ? stored : '';
    } catch (e) { return ''; }
  });

  const authed = !GATE_ENABLED || level === 'pool' || level === 'guest';
  const poolOK = !GATE_ENABLED || level === 'pool';

  function submit(pass) {
    const lvl = levelForPassword(pass);
    if (lvl) {
      try { localStorage.setItem(STORAGE_KEY, lvl); } catch (e) {}
      setLevel(lvl);
      return true;
    }
    return false;
  }

  function signOut() {
    try { localStorage.removeItem(STORAGE_KEY); } catch (e) {}
    setLevel('');
  }

  const value = { gateEnabled: GATE_ENABLED, authed: authed, poolOK: poolOK, level: level, signOut: signOut };

  return (
    <AccessContext.Provider value={value}>
      {authed ? children : null}
      {(GATE_ENABLED && !authed) ? <PasswordGate onSubmit={submit} /> : null}
    </AccessContext.Provider>
  );
}
window.AccessProvider = AccessProvider;
