import './site-mode-switcher.scss';

import { setCookie, getCookie } from 'utils/cookies.js';

Drupal.behaviors.siteModeSwitcher = {
  attach(context) {
    const HTML = document.documentElement;
    const BUTTON_SITE_MODE_SWITCHER = context.querySelector('button[data-js="site-mode-switcher"]');
    const USER_SITE_MODE_VALUE = getCookie('USER_SITE_MODE');

    let siteModeTimeCheckInterval;
    let siteModeTimeCheckTimeout;

    const setDataSiteMode = (siteMode) => {
      if (!document.startViewTransition) {
        HTML.setAttribute('data-site-mode', siteMode);
      }
      else {
        document.startViewTransition(() => {
          HTML.setAttribute('data-site-mode', siteMode);
        });
      }
    }

    const getSiteMode = () => {
      if (USER_SITE_MODE_VALUE) {
        HTML.setAttribute('data-site-mode', USER_SITE_MODE_VALUE);
        return;
      }

      // Create fresh date for accurate time calculation
      const NOW = new Date();

      // Get time in America/New_York time zone (EST/EDT depending on date)
      const DATE_FORMATTER = new Intl.DateTimeFormat('en-US', {
        timeZone: 'America/New_York',
        hour: 'numeric',
        hour12: false,
      });

      const DATE_PARTS = DATE_FORMATTER.formatToParts(NOW);

      const HOURS = Number(DATE_PARTS.find(p => p.type === 'hour').value);

      // Get day of week from the date object directly (0 = Sunday, 1 = Monday, ..., 6 = Saturday)
      const DAY_OF_WEEK = new Date(NOW.toLocaleString("en-US", { timeZone: "America/New_York" })).getDay();

      // Check if it's Monday (1) through Friday (5)
      const IS_WEEKDAY = DAY_OF_WEEK >= 1 && DAY_OF_WEEK <= 5;

      // Check if it's between 9AM (9) and 6PM (18) - (17:59 is still work)
      const IS_WORK_HOURS = HOURS >= 9 && HOURS < 18;

      let siteMode = (IS_WEEKDAY && IS_WORK_HOURS) ? 'at-work' : 'at-play';

      if (siteMode !== getCookie('SYSTEM_SITE_MODE')) {
        setCookie('SYSTEM_SITE_MODE', siteMode);
        setDataSiteMode(siteMode);
      }
    }

    if (BUTTON_SITE_MODE_SWITCHER) {
      BUTTON_SITE_MODE_SWITCHER.addEventListener('click', () => {
        let currentSiteMode = HTML.getAttribute('data-site-mode');
        let newSiteMode = currentSiteMode === 'at-work' ? 'at-play' : 'at-work';

        setCookie('USER_SITE_MODE', newSiteMode);
        setDataSiteMode(newSiteMode);

        // The user set their preference, stop checking for a site mode change.
        clearInterval(siteModeTimeCheckInterval);
        clearTimeout(siteModeTimeCheckTimeout);
      });
    }

    // Prevent setting the site-mode when in storybook.
    if (window.location.hostname === 'localhost') {
      return;
    }

    // If the user has not selected their preference.
    if (!USER_SITE_MODE_VALUE) {
      /**
       * Check every minute if the site-mode should change.
       */
      const siteModeTimeCheck = () => {
        const NOW = new Date();
        const msUntilNextMinute = (60 - NOW.getSeconds()) * 1000 - NOW.getMilliseconds();

        siteModeTimeCheckTimeout = setTimeout(() => {
          getSiteMode();
          siteModeTimeCheckInterval = setInterval(getSiteMode, 60000);
        }, msUntilNextMinute);
      };

      siteModeTimeCheck();
    }

    getSiteMode();
  }
}
