const Drops = ({ onAdd, onOpen, user }) => {
  const [unlocked, setUnlocked] = React.useState(() => {
    try {
      return sessionStorage.getItem('obc_drops_unlocked') === '1';
    } catch {
      return false;
    }
  });
  const [code, setCode] = React.useState('');
  const [authState, setAuthState] = React.useState('idle'); // idle | loading | error
  const [products, setProducts] = React.useState([]);
  const [productsLoading, setProductsLoading] = React.useState(false);
  const [productsLoaded, setProductsLoaded] = React.useState(false);

  React.useEffect(() => {
    if (unlocked && !productsLoaded) {
      setProductsLoading(true);
      window.OBC_API.getExclusiveProducts()
        .then(data => {
          setProducts(data || []);
          setProductsLoaded(true);
        })
        .catch(() => {
          setProducts([]);
          setProductsLoaded(true);
        })
        .finally(() => setProductsLoading(false));
    }
  }, [unlocked, productsLoaded]);

  const [errorMsg, setErrorMsg] = React.useState('');

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

  const handleLock = () => {
    try {
      sessionStorage.removeItem('obc_drops_unlocked');
    } catch {}
    setUnlocked(false);
    setProducts([]);
    setProductsLoaded(false);
    setCode('');
    setAuthState('idle');
    setErrorMsg('');
  };

  const styles = {
    container: {
      maxWidth: 1280,
      margin: '0 auto',
      padding: 24,
      fontFamily: 'inherit',
    },
    lockedWrapper: {
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      justifyContent: 'center',
      minHeight: '60vh',
      textAlign: 'center',
    },
    classifiedHeader: {
      fontSize: 48,
      fontWeight: 700,
      color: '#00FF41',
      letterSpacing: '0.15em',
      textTransform: 'uppercase',
      margin: 0,
      fontFamily: 'inherit',
    },
    lockedSubtext: {
      color: '#6E6E6E',
      fontSize: 14,
      marginTop: 12,
      fontFamily: 'inherit',
    },
    form: {
      marginTop: 40,
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      gap: 16,
      width: '100%',
      maxWidth: 440,
    },
    inputRow: {
      display: 'flex',
      alignItems: 'center',
      width: '100%',
      gap: 8,
    },
    inputLabel: {
      color: '#00FF41',
      fontSize: 14,
      fontFamily: 'inherit',
      whiteSpace: 'nowrap',
      flexShrink: 0,
    },
    input: {
      flex: 1,
      background: 'transparent',
      border: '1px solid rgba(255,255,255,0.10)',
      color: '#FFF',
      fontFamily: 'inherit',
      fontSize: 14,
      padding: '10px 12px',
      borderRadius: 2,
      outline: 'none',
      letterSpacing: '0.15em',
      transition: 'border-color 0.2s',
    },
    submitBtn: {
      background: '#00FF41',
      color: '#000',
      border: 'none',
      fontFamily: 'inherit',
      fontSize: 13,
      fontWeight: 700,
      textTransform: 'uppercase',
      letterSpacing: '0.2em',
      padding: '12px 32px',
      borderRadius: 2,
      cursor: 'pointer',
      transition: 'transform 0.15s, box-shadow 0.15s',
      marginTop: 8,
    },
    statusText: {
      fontSize: 13,
      fontFamily: 'inherit',
      marginTop: 8,
    },
    headerRow: {
      display: 'flex',
      alignItems: 'flex-start',
      justifyContent: 'space-between',
      marginBottom: 24,
    },
    sectionHeader: {
      fontSize: 28,
      fontWeight: 700,
      color: '#00FF41',
      letterSpacing: '0.1em',
      textTransform: 'uppercase',
      margin: 0,
      fontFamily: 'inherit',
    },
    sectionSubtext: {
      color: '#6E6E6E',
      fontSize: 13,
      marginTop: 6,
      fontFamily: 'inherit',
    },
    lockBtn: {
      background: 'transparent',
      border: '1px solid rgba(255,255,255,0.10)',
      color: '#B8B8B8',
      fontFamily: 'inherit',
      fontSize: 12,
      textTransform: 'uppercase',
      letterSpacing: '0.15em',
      padding: '6px 14px',
      borderRadius: 2,
      cursor: 'pointer',
      transition: 'border-color 0.2s, color 0.2s',
      flexShrink: 0,
    },
    grid: {
      display: 'grid',
      gridTemplateColumns: 'repeat(auto-fill, minmax(310px, 1fr))',
      gap: 16,
    },
    emptyText: {
      color: '#6E6E6E',
      fontSize: 14,
      fontFamily: 'inherit',
    },
    loadingText: {
      color: '#6E6E6E',
      fontSize: 14,
      fontFamily: 'inherit',
    },
  };

  if (!unlocked) {
    return React.createElement('div', { style: styles.container },
      React.createElement('div', { style: styles.lockedWrapper },
        React.createElement('h1', { style: styles.classifiedHeader }, '> CLASSIFIED'),
        React.createElement('p', { style: styles.lockedSubtext },
          '// this section requires authorization. enter access code to proceed.'
        ),
        React.createElement('form', { style: styles.form, onSubmit: handleSubmit },
          React.createElement('div', { style: styles.inputRow },
            React.createElement('span', { style: styles.inputLabel }, '> ACCESS CODE:'),
            React.createElement('input', {
              type: 'password',
              value: code,
              onChange: (e) => { setCode(e.target.value); if (authState === 'error') setAuthState('idle'); },
              style: styles.input,
              placeholder: '________',
              autoComplete: 'off',
              spellCheck: false,
              disabled: authState === 'loading',
              onFocus: (e) => { e.target.style.borderColor = '#00FF41'; },
              onBlur: (e) => { e.target.style.borderColor = 'rgba(255,255,255,0.10)'; },
            })
          ),
          React.createElement('button', {
            type: 'submit',
            style: {
              ...styles.submitBtn,
              opacity: authState === 'loading' ? 0.7 : 1,
              pointerEvents: authState === 'loading' ? 'none' : 'auto',
            },
            disabled: authState === 'loading',
            onMouseEnter: (e) => {
              e.target.style.transform = 'translateY(-2px)';
              e.target.style.boxShadow = '0 0 12px rgba(0,255,65,0.3)';
            },
            onMouseLeave: (e) => {
              e.target.style.transform = 'translateY(0)';
              e.target.style.boxShadow = 'none';
            },
          }, '[ AUTHENTICATE ]'),
          authState === 'loading' && React.createElement('span', {
            style: { ...styles.statusText, color: '#00FF41' }
          }, '// authenticating...'),
          authState === 'error' && React.createElement('span', {
            style: { ...styles.statusText, color: '#FF3344' }
          }, errorMsg || '// access denied. invalid code.')
        )
      )
    );
  }

  return React.createElement('div', { style: styles.container },
    React.createElement('div', { style: styles.headerRow },
      React.createElement('div', null,
        React.createElement('h1', { style: styles.sectionHeader }, '> EXCLUSIVE DROPS'),
        React.createElement('p', { style: styles.sectionSubtext },
          '// classified inventory. handle with care.'
        )
      ),
      React.createElement('button', {
        style: styles.lockBtn,
        onClick: handleLock,
        onMouseEnter: (e) => {
          e.target.style.borderColor = '#00FF41';
          e.target.style.color = '#00FF41';
        },
        onMouseLeave: (e) => {
          e.target.style.borderColor = 'rgba(255,255,255,0.10)';
          e.target.style.color = '#B8B8B8';
        },
      }, '[ LOCK ]')
    ),
    productsLoading
      ? React.createElement('p', { style: styles.loadingText }, '// loading classified inventory...')
      : products.length === 0 && productsLoaded
        ? React.createElement('p', { style: styles.emptyText }, '// no classified inventory available.')
        : React.createElement('div', { style: styles.grid },
            products.map(item =>
              React.createElement(window.MerchCard, {
                key: item.id,
                item: item,
                onOpen: onOpen,
                user: user,
              })
            )
          )
  );
};

window.Drops = Drops;
