const { useState: useStateEP, useEffect: useEffectEP } = React;

const POPUP_KEY   = 'peripheral-popup-v1';
const PENDING_KEY = 'pvl-patreon-pending';
const POPUP_DELAY = 3500;

function EmailPopup({ onDismiss }) {
  const tier = localStorage.getItem('pvl-patreon-tier');
  const code = localStorage.getItem('pvl-patreon-code');
  const [copied, setCopied] = useStateEP(false);

  const handlePatreon = () => {
    localStorage.setItem(POPUP_KEY, '1');
    localStorage.setItem(PENDING_KEY, '1');
    // Prevent bfcache so back-navigation does a fresh load (fixes cursor re-init)
    window.addEventListener('beforeunload', () => {}, { once: true });
    window.location.href = '/api/patreon/auth';
  };

  const handleCopy = () => {
    navigator.clipboard.writeText(code).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2500);
    });
  };

  if (tier) {
    return (
      <div className="ep-overlay" onClick={onDismiss}>
        <div className="ep-card" onClick={e => e.stopPropagation()}>
          <div className="ep-image">
            <img src="/assets/popup-room.jpg" alt="Peripheral"/>
          </div>
          <div className="ep-body">
            <button className="ep-close" onClick={onDismiss} aria-label="Close"
                    onMouseEnter={() => onCursor('hover')} onMouseLeave={() => onCursor('default')}>
              <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
              </svg>
            </button>
            <div className="eyebrow">You're in!</div>
            <h2 className="h-2"><em>5% off</em> your first order</h2>
            {code
              ? <>
                  <p className="ep-desc" style={{whiteSpace:'nowrap'}}>Copy the code below and paste it at checkout.</p>
                  <button className="btn-primary" onClick={handleCopy}
                          onMouseEnter={() => onCursor('hover')} onMouseLeave={() => onCursor('default')}
                          style={{letterSpacing: copied ? '0.05em' : '0.12em', display:'flex', alignItems:'center', justifyContent:'center', gap:8}}>
                    {copied
                      ? <><svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>Copied!</>
                      : <><svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>{code}</>
                    }
                  </button>
                  <p className="ep-fine" style={{textAlign:'center'}}>
                    <span style={{cursor:'none', textDecoration:'underline', textUnderlineOffset:3}}
                          onClick={onDismiss}
                          onMouseEnter={() => onCursor('hover')} onMouseLeave={() => onCursor('default')}>
                      Start shopping
                    </span>
                  </p>
                </>
              : <>
                  <p className="ep-desc">Your discount will be in your Patreon welcome note.</p>
                  <button className="btn-primary" onClick={onDismiss}
                          onMouseEnter={() => onCursor('hover')} onMouseLeave={() => onCursor('default')}>
                    Start shopping
                  </button>
                </>
            }
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="ep-overlay" onClick={onDismiss}>
      <div className="ep-card" onClick={e => e.stopPropagation()}>
        <div className="ep-image">
          <img src="/assets/popup-room.jpg" alt="Peripheral"/>
        </div>

        <div className="ep-body">
          <button className="ep-close" onClick={onDismiss} aria-label="Close"
                  onMouseEnter={() => onCursor('hover')} onMouseLeave={() => onCursor('default')}>
            <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
            </svg>
          </button>

          <h2 className="h-2"><em>5% off</em> your first order</h2>
          <p className="ep-desc">Join Peripheral on Patreon and get your discount code instantly.</p>
          <button className="btn-primary" onClick={handlePatreon}
                  onMouseEnter={() => onCursor('hover')} onMouseLeave={() => onCursor('default')}>
            Join free on Patreon
          </button>
          <p className="ep-fine" style={{textAlign:'center'}}>Free to join. No card required.</p>
        </div>
      </div>
    </div>
  );
}

function EmailPopupController() {
  const [visible, setVisibleEP] = useStateEP(false);

  useEffectEP(() => {
    const tier    = localStorage.getItem('pvl-patreon-tier');
    const pending = localStorage.getItem(PENDING_KEY);
    // Just returned from Patreon OAuth — open with success state
    if (tier && pending) {
      localStorage.removeItem(PENDING_KEY);
      setVisibleEP(true);
      return;
    }
    // Auto-show join popup for new visitors
    if (!localStorage.getItem(POPUP_KEY) && !tier) {
      const t = setTimeout(() => setVisibleEP(true), POPUP_DELAY);
      return () => clearTimeout(t);
    }
  }, []);

  useEffectEP(() => {
    const handler = () => setVisibleEP(true);
    window.addEventListener('peripheral:open-popup', handler);
    return () => window.removeEventListener('peripheral:open-popup', handler);
  }, []);

  const dismiss = () => {
    setVisibleEP(false);
    localStorage.setItem(POPUP_KEY, '1');
  };

  if (!visible) return null;
  return <EmailPopup onDismiss={dismiss}/>;
}

window.EmailPopupController = EmailPopupController;
window.openEmailPopup = () => window.dispatchEvent(new CustomEvent('peripheral:open-popup'));
