import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom/client';
import { ScentFinderModal } from './components/ScentFinder';
import { AskPerfumerWidget } from './components/AskPerfumer/AskPerfumerWidget';
import { SpinWheelModal } from './components/SpinWheel/SpinWheelModal';
import { SpinWheelLauncher } from './components/SpinWheel/SpinWheelLauncher';
import './index.css';

function ScentFinderApp() {
  const [isOpen, setIsOpen] = useState(false);
  const [isSpinOpen, setIsSpinOpen] = useState(false);
  const [spinCoupon, setSpinCoupon] = useState(null);
  const [spinWheelEnabled, setSpinWheelEnabled] = useState(true);

  const isEnabledRef = React.useRef(true);

  useEffect(() => {
    // Expose global triggers for vanilla JS buttons & navigation links
    window.openScentFinder = () => {
      setIsOpen(true);
    };

    window.openSpinWheel = (forceActivate = true) => {
      if (!isEnabledRef.current) {
        console.info('Spin wheel is disabled by store administrator.');
        return;
      }
      if (forceActivate) {
        localStorage.removeItem('dubai_damas_spin_done');
      }
      setIsSpinOpen(true);
    };

    window.activateSpinner = async () => {
      if (!isEnabledRef.current) {
        console.info('Spin wheel is disabled by store administrator.');
        return;
      }
      localStorage.removeItem('dubai_damas_spin_done');
      localStorage.removeItem('dubai_damas_spin_coupon');
      try {
        await fetch('/api/spin-wheel/reset', { method: 'POST' });
      } catch (e) {}
      setSpinCoupon(null);
      setIsSpinOpen(true);
    };

    // Attach delegated click listener to any element with data-scent-finder-trigger or data-spin-wheel-trigger
    const handleDocClick = (e) => {
      const trigger = e.target.closest && e.target.closest('[data-scent-finder-trigger]');
      if (trigger) {
        e.preventDefault();
        setIsOpen(true);
      }

      const spinTrigger = e.target.closest && e.target.closest('[data-spin-wheel-trigger]');
      if (spinTrigger) {
        if (!isEnabledRef.current) return;
        e.preventDefault();
        setIsSpinOpen(true);
      }
    };

    document.addEventListener('click', handleDocClick);

    // Developer / testing query parameter helper (?reset_spin=1 or ?activate_spin=1)
    const urlParams = typeof window !== 'undefined' ? new URLSearchParams(window.location.search) : null;
    if (urlParams && (urlParams.get('reset_spin') === '1' || urlParams.get('activate_spin') === '1')) {
      localStorage.removeItem('dubai_damas_spin_done');
      localStorage.removeItem('dubai_damas_spin_coupon');
      document.cookie = 'dd_spin_vid=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
      fetch('/api/spin-wheel/reset', { method: 'POST' }).catch(() => {});
      setIsSpinOpen(true);
    }

    // Spin the Wheel Eligibility & Saved Coupon Check:
    const localCouponStr = localStorage.getItem('dubai_damas_spin_coupon');
    if (localCouponStr) {
      try {
        const parsed = JSON.parse(localCouponStr);
        if (parsed?.code && new Date(parsed.expiresAt) > new Date()) {
          setSpinCoupon(parsed);
        }
      } catch (e) {}
    }

    // Call GET /api/spin-wheel/status to check server-side state & enabled toggle
    const sessionShown = sessionStorage.getItem('dubai_damas_spin_shown');
    const localDone = localStorage.getItem('dubai_damas_spin_done');
    let timer = null;

    fetch('/api/spin-wheel/status')
      .then(r => r.json())
      .then(data => {
        if (!data) return;
        if (data.enabled === false) {
          isEnabledRef.current = false;
          setSpinWheelEnabled(false);
          document.querySelectorAll('.spin-wheel-nav-link').forEach(el => {
            el.style.display = 'none';
          });
          return;
        }

        isEnabledRef.current = true;
        setSpinWheelEnabled(true);
        if (data.hasActiveCoupon && data.coupon) {
          setSpinCoupon(data.coupon);
        }

        // Auto-appear spinner popup after 2.5 seconds on initial visit only when enabled
        if (!sessionShown && localDone !== '1') {
          timer = setTimeout(() => {
            setIsSpinOpen(true);
            sessionStorage.setItem('dubai_damas_spin_shown', '1');
          }, 2500);
        }
      })
      .catch(err => {
        console.warn('Spin wheel status check error:', err);
      });

    return () => {
      if (timer) clearTimeout(timer);
      document.removeEventListener('click', handleDocClick);
    };
  }, []);

  return (
    <>
      <ScentFinderModal
        isOpen={isOpen}
        onClose={() => setIsOpen(false)}
      />
      <AskPerfumerWidget />
      {spinWheelEnabled && (
        <>
          <SpinWheelLauncher
            onClick={() => {
              localStorage.removeItem('dubai_damas_spin_done');
              setIsSpinOpen(true);
            }}
            hasActiveCoupon={Boolean(spinCoupon)}
            couponCode={spinCoupon?.code}
          />
          <SpinWheelModal
            isOpen={isSpinOpen}
            onClose={() => setIsSpinOpen(false)}
            initialCoupon={spinCoupon}
            startInWheelMode={true}
          />
        </>
      )}
    </>
  );
}

function mountApp() {
  let container = document.getElementById('scent-finder-root');
  if (!container) {
    container = document.createElement('div');
    container.id = 'scent-finder-root';
    document.body.appendChild(container);
  }
  if (!container._reactRoot) {
    const root = ReactDOM.createRoot(container);
    container._reactRoot = root;
    root.render(
      <React.StrictMode>
        <ScentFinderApp />
      </React.StrictMode>
    );
  }
}

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', mountApp);
} else {
  mountApp();
}
