const MobileDrops = ({ onAdd, onOpen, user }) => {
  const { useState, useEffect, useCallback } = React;

  const [unlocked, setUnlocked] = useState(false);
  const [code, setCode] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [products, setProducts] = useState(null);
  const [productsLoading, setProductsLoading] = useState(false);

  // check localStorage on mount
  useEffect(() => {
    try {
      if (sessionStorage.getItem('obc_drops_unlocked') === '1') {
        setUnlocked(true);
      }
    } catch (_) {}
  }, []);

  // fetch products when unlocked
  useEffect(() => {
    if (!unlocked) return;
    let cancelled = false;
    setProductsLoading(true);
    window.OBC_API.getExclusiveProducts()
      .then(data => {
        if (!cancelled) {
          setProducts(data || []);
          setProductsLoading(false);
        }
      })
      .catch(() => {
        if (!cancelled) {
          setProducts([]);
          setProductsLoading(false);
        }
      });
    return () => { cancelled = true; };
  }, [unlocked]);

  const handleSubmit = useCallback(async (e) => {
    e.preventDefault();
    if (!code.trim() || loading) return;
    setLoading(true);
    setError('');
    try {
      const result = await window.OBC_API.verifyDropCode(code.trim());
      if (result && result.valid) {
        try { sessionStorage.setItem('obc_drops_unlocked', '1'); } catch (_) {}
        setUnlocked(true);
      } else {
        setError('// access denied.');
      }
    } catch (err) {
      var msg = (err && err.message) || '';
      if (msg.indexOf('RATE_LIMITED') !== -1) {
        setError('// too many attempts. try again later.');
      } else {
        setError('// access denied. invalid code.');
        console.error('[drops] verify error:', msg);
      }
    }
    setLoading(false);
  }, [code, loading]);

  const handleLock = useCallback(() => {
    try { sessionStorage.removeItem('obc_drops_unlocked'); } catch (_) {}
    setUnlocked(false);
    setProducts(null);
    setCode('');
    setError('');
  }, []);

  const styles = {
    container: {
      padding: 16,
      fontFamily: 'inherit',
      color: '#FFF',
      minHeight: '60vh',
    },
    // locked phase
    header: {
      fontSize: 28,
      fontWeight: 800,
      color: '#00FF41',
      margin: '0 0 8px 0',
      fontFamily: 'inherit',
    },
    subtext: {
      fontSize: 14,
      color: '#6E6E6E',
      margin: '0 0 24px 0',
      fontFamily: 'inherit',
    },
    form: {
      display: 'flex',
      flexDirection: 'column',
      gap: 12,
    },
    input: {
      width: '100%',
      boxSizing: 'border-box',
      fontSize: 18,
      padding: 14,
      fontFamily: 'inherit',
      background: '#0A0A0A',
      border: '1px solid rgba(255,255,255,0.28)',
      color: '#FFF',
      borderRadius: 2,
      outline: 'none',
      WebkitAppearance: 'none',
    },
    button: {
      width: '100%',
      height: 48,
      background: '#00FF41',
      color: '#000',
      border: 'none',
      fontWeight: 800,
      letterSpacing: '0.2em',
      fontSize: 14,
      fontFamily: 'inherit',
      cursor: 'pointer',
      textTransform: 'uppercase',
      borderRadius: 2,
    },
    buttonDisabled: {
      opacity: 0.6,
      cursor: 'not-allowed',
    },
    errorText: {
      color: '#FF3344',
      fontSize: 14,
      fontFamily: 'inherit',
      margin: 0,
    },
    loadingText: {
      color: '#6E6E6E',
      fontSize: 14,
      fontFamily: 'inherit',
      margin: 0,
    },
    // unlocked phase
    unlockedHeader: {
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'flex-start',
    },
    unlockedTitle: {
      fontSize: 22,
      fontWeight: 800,
      color: '#00FF41',
      margin: '0 0 4px 0',
      fontFamily: 'inherit',
    },
    unlockedSubtext: {
      fontSize: 13,
      color: '#6E6E6E',
      margin: '0 0 20px 0',
      fontFamily: 'inherit',
    },
    lockButton: {
      background: 'none',
      border: '1px solid rgba(255,255,255,0.10)',
      color: '#6E6E6E',
      fontFamily: 'inherit',
      fontSize: 12,
      fontWeight: 800,
      letterSpacing: '0.1em',
      cursor: 'pointer',
      padding: '6px 10px',
      borderRadius: 2,
      whiteSpace: 'nowrap',
      flexShrink: 0,
    },
    productList: {
      display: 'flex',
      flexDirection: 'column',
      gap: 16,
    },
    emptyText: {
      color: '#6E6E6E',
      fontSize: 14,
      fontFamily: 'inherit',
    },
  };

  // LOCKED phase
  if (!unlocked) {
    return React.createElement('div', { style: styles.container },
      React.createElement('h2', { style: styles.header }, '> CLASSIFIED'),
      React.createElement('p', { style: styles.subtext }, '// enter access code to proceed.'),
      React.createElement('form', { style: styles.form, onSubmit: handleSubmit },
        React.createElement('input', {
          type: 'password',
          value: code,
          onChange: (e) => setCode(e.target.value),
          placeholder: '> enter code',
          style: styles.input,
          autoComplete: 'off',
          autoCapitalize: 'off',
          spellCheck: false,
          onFocus: (e) => { e.target.style.borderColor = '#00FF41'; },
          onBlur: (e) => { e.target.style.borderColor = 'rgba(255,255,255,0.28)'; },
        }),
        error && React.createElement('p', { style: styles.errorText }, error),
        loading && React.createElement('p', { style: styles.loadingText }, '// authenticating...'),
        React.createElement('button', {
          type: 'submit',
          style: {
            ...styles.button,
            ...(loading ? styles.buttonDisabled : {}),
          },
          disabled: loading,
        }, '[ AUTHENTICATE ]')
      )
    );
  }

  // UNLOCKED phase
  return React.createElement('div', { style: styles.container },
    React.createElement('div', { style: styles.unlockedHeader },
      React.createElement('div', null,
        React.createElement('h2', { style: styles.unlockedTitle }, '> EXCLUSIVE DROPS'),
        React.createElement('p', { style: styles.unlockedSubtext }, '// classified inventory.'),
      ),
      React.createElement('button', {
        style: styles.lockButton,
        onClick: handleLock,
      }, '[ LOCK ]'),
    ),
    productsLoading
      ? React.createElement('p', { style: styles.loadingText }, '// loading...')
      : (!products || products.length === 0)
        ? React.createElement('p', { style: styles.emptyText }, '// no classified inventory available.')
        : React.createElement('div', { style: styles.productList },
            products.map(function(item) {
              return React.createElement(window.MobileMerchCard, {
                key: item.id,
                item: item,
                onOpen: onOpen,
                user: user,
              });
            })
          )
  );
};

window.MobileDrops = MobileDrops;
