// === Fast Mode ===
// Optional 15-second site optimization. Default OFF.
// Activate via:
//   1. URL flag: append ?fast=1 to any URL (or #/path?fast=1)
//   2. Toggle button (bottom-right of viewport)
// Choice persists in localStorage so reloads survive.

const FAST_MODE_KEY = 'bm_fast_mode';

function detectFastModeFromUrl() {
  // Check both ?fast=1 in search AND in the hash query (#/shop?fast=1)
  const search = window.location.search || '';
  const hash = window.location.hash || '';
  const hashQuery = hash.includes('?') ? hash.split('?')[1] : '';
  const all = (search + '&' + hashQuery).replace(/^\?/, '');
  const params = new URLSearchParams(all);
  if (params.get('fast') === '1') return true;
  if (params.get('fast') === '0') return false;
  return null;
}

const FAST_MODE_EVENT = 'bm-fast-mode-changed';

function readFastFromStorage() {
  const fromUrl = detectFastModeFromUrl();
  if (fromUrl !== null) {
    try { localStorage.setItem(FAST_MODE_KEY, fromUrl ? '1' : '0'); } catch {}
    return fromUrl;
  }
  try { return localStorage.getItem(FAST_MODE_KEY) === '1'; } catch { return false; }
}

function setFastModeGlobal(next) {
  try { localStorage.setItem(FAST_MODE_KEY, next ? '1' : '0'); } catch {}
  window.dispatchEvent(new CustomEvent(FAST_MODE_EVENT, { detail: !!next }));
}

function useFastMode() {
  const [fast, setFast] = React.useState(readFastFromStorage);

  React.useEffect(() => {
    const onChange = (e) => setFast(!!e.detail);
    const onStorage = (e) => {
      if (e.key === FAST_MODE_KEY) setFast(e.newValue === '1');
    };
    const onHash = () => {
      const fromUrl = detectFastModeFromUrl();
      if (fromUrl !== null) setFastModeGlobal(fromUrl);
    };
    window.addEventListener(FAST_MODE_EVENT, onChange);
    window.addEventListener('storage', onStorage);
    window.addEventListener('hashchange', onHash);
    return () => {
      window.removeEventListener(FAST_MODE_EVENT, onChange);
      window.removeEventListener('storage', onStorage);
      window.removeEventListener('hashchange', onHash);
    };
  }, []);

  const toggle = React.useCallback(() => {
    setFastModeGlobal(!readFastFromStorage());
  }, []);

  return [fast, toggle];
}

// Visible toggle button — bottom-right, dismissible
function FastModeToggle() {
  const [fast, toggle] = useFastMode();
  const [hover, setHover] = React.useState(false);

  return (
    <button
      onClick={toggle}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      aria-label={fast ? 'Switch to full site' : 'Switch to fast preview'}
      style={{
        position: 'fixed',
        bottom: 20,
        right: 20,
        zIndex: 9999,
        background: fast ? 'var(--bm-pink)' : 'var(--bm-ink)',
        color: fast ? 'var(--bm-ink)' : 'var(--bm-paper)',
        border: '2px solid var(--bm-ink)',
        borderRadius: 999,
        padding: '10px 16px',
        fontFamily: 'var(--font-mono)',
        fontSize: 11,
        letterSpacing: '0.16em',
        textTransform: 'uppercase',
        fontWeight: 700,
        cursor: 'pointer',
        boxShadow: hover ? '2px 2px 0 0 var(--bm-ink)' : '4px 4px 0 0 var(--bm-ink)',
        transform: hover ? 'translate(2px, 2px)' : 'translate(0, 0)',
        transition: 'transform 120ms, box-shadow 120ms',
        display: 'flex',
        alignItems: 'center',
        gap: 8,
      }}
    >
      <span style={{
        width: 8, height: 8, borderRadius: '50%',
        background: fast ? 'var(--bm-ink)' : 'var(--bm-pink)',
      }} />
      {fast ? 'Fast Mode · ON' : 'Fast Preview'}
    </button>
  );
}

// Sticky Founders bar — top of viewport in fast mode
function FastFoundersBar() {
  const [email, setEmail] = React.useState('');
  const [submitted, setSubmitted] = React.useState(false);
  const [dismissed, setDismissed] = React.useState(() => {
    try { return sessionStorage.getItem('bm_fast_bar_dismissed') === '1'; } catch { return false; }
  });

  const onSubmit = (e) => {
    e.preventDefault();
    if (!email || !/.+@.+\..+/.test(email)) return;
    if (typeof joinKlaviyoWaitlist === 'function') {
      joinKlaviyoWaitlist(email, 'Fast Mode Sticky Bar', { tier: 'Founders Sticky' });
    }
    setSubmitted(true);
  };

  const dismiss = () => {
    setDismissed(true);
    try { sessionStorage.setItem('bm_fast_bar_dismissed', '1'); } catch {}
  };

  if (dismissed) return null;

  return (
    <div style={{
      position: 'sticky',
      top: 0,
      zIndex: 100,
      background: 'var(--bm-pink)',
      color: 'var(--bm-ink)',
      padding: '10px 20px',
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      gap: 16,
      flexWrap: 'wrap',
      borderBottom: '2px solid var(--bm-ink)',
      fontFamily: 'var(--font-mono)',
      fontSize: 12,
      letterSpacing: '0.08em',
    }}>
      <span style={{ fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.12em' }}>
        Founders List · First 500 = launch-day discount
      </span>
      {submitted ? (
        <span style={{ fontWeight: 700 }}>✓ You're in. Watch your inbox.</span>
      ) : (
        <form onSubmit={onSubmit} style={{ display: 'flex', gap: 0, alignItems: 'stretch' }}>
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="email@yours.com"
            required
            style={{
              padding: '6px 12px',
              border: '2px solid var(--bm-ink)',
              borderRight: 'none',
              borderRadius: '4px 0 0 4px',
              fontFamily: 'var(--font-mono)',
              fontSize: 12,
              background: 'var(--bm-paper)',
              color: 'var(--bm-ink)',
              minWidth: 200,
            }}
          />
          <button type="submit" style={{
            padding: '6px 14px',
            border: '2px solid var(--bm-ink)',
            borderRadius: '0 4px 4px 0',
            background: 'var(--bm-ink)',
            color: 'var(--bm-paper)',
            fontFamily: 'var(--font-mono)',
            fontSize: 11,
            letterSpacing: '0.12em',
            textTransform: 'uppercase',
            fontWeight: 700,
            cursor: 'pointer',
          }}>Lock in →</button>
        </form>
      )}
      <button onClick={dismiss} aria-label="Dismiss" style={{
        background: 'transparent', border: 'none', color: 'var(--bm-ink)',
        cursor: 'pointer', fontSize: 18, lineHeight: 1, padding: 4,
      }}>×</button>
    </div>
  );
}

window.useFastMode = useFastMode;
window.FastModeToggle = FastModeToggle;
window.FastFoundersBar = FastFoundersBar;
