import { Element } from '../core/element.js'

class ConsentCGU extends Element {
  get buttonAccept () {
    return this.element.querySelector('#button-cgu-accept');
  }

  get buttonDeny () {
    return this.element.querySelector('#button-cgu-deny');
  }

  get modalContent () {
    return this.element.querySelector('.fr-modal__body');
  }

  init() {
    this.buttonAccept.addEventListener(
      'click',
      this.handleButtonAcceptClick.bind(this)
    );
    this.buttonDeny.addEventListener(
      'click',
      this.handleButtonDenyClick.bind(this)
    );

    this.handleConsent();
  }

  handleConsent() {
    const modal = document.getElementById('modal-cgu');
    const cguVersion = modal?.getAttribute('data-cgu-version') || null;
    const cguVersionSplit = cguVersion ? cguVersion.split('.') : [];
    const cookieVersion = document.cookie.split('; ').find(row => row.startsWith('cgu-version='))?.split('=')[1];
    const cookieVersionSplit = cookieVersion ? cookieVersion.split('.') : [];
    const isSameVersion = cookieVersion && (cookieVersionSplit[0] === cguVersionSplit[0] && cookieVersionSplit[1] === cguVersionSplit[1]);

    if (isSameVersion) {
      if (modal) modal.remove();
    } else {
      if (modal) {
        window.dsfr(modal).modal.disclose();
        requestAnimationFrame(() => {
          modal.querySelector('.dsfr-doc-modal-cgu__intro')?.focus();
        });
        document.addEventListener('keydown', (e) => {
          if (e.key === 'Escape') {
            if (modal?.classList.contains('fr-modal--opened') && !modal.classList.contains('dsfr-doc-modal-cgu-accepted')) {
              e.preventDefault();
              e.stopImmediatePropagation();
            }
          }
        }, { capture: true });
      }
    }
  }

  getConfirmModalContent() {
    return `
    <div class="fr-modal__header">
        <button aria-controls="modal-cgu" title="Fermer" type="button" id="button-cgu-accepted-close" class="fr-btn fr-btn--close">Fermer</button>
    </div>
    <div class="fr-modal__content dsfr-doc-modal-cgu-accepted__content">
      <div class="dsfr-doc-modal-cgu-accepted__content-center">
        <svg aria-hidden="true" class="fr-artwork fr-artwork--green-emeraude dsfr-doc-modal-cgu-accepted__pictogram" viewBox="0 0 80 80" width="80px" height="80px">
          <use class="fr-artwork-decorative" href="/dist/artwork/pictograms/system/success.svg#artwork-decorative"></use>
          <use class="fr-artwork-minor" href="/dist/artwork/pictograms/system/success.svg#artwork-minor"></use>
          <use class="fr-artwork-major" href="/dist/artwork/pictograms/system/success.svg#artwork-major"></use>
        </svg>
        <p id="modal-cgu-title" role="alert" class="fr-h4">Merci, votre consentement a été enregistré</p>
        <button type="button" id="button-cgu-accepted-confirm" aria-controls="modal-cgu" class="fr-btn dsfr-doc-modal-cgu-accepted__button">Accéder à la documentation</button>
      </div>
      <p class="dsfr-doc-modal-cgu-accepted__info">Le formulaire « Conditions générales d’utilisation du Système de Design de l’État » s’inscrit dans le cadre d’un traitement de données personnelles géré par la Direction des Services Administratifs et Financiers du Premier ministre (DSAF). Vous disposez de droits sur vos données personnelles collectées et utilisées dans ce cadre (opposition, accès, rectification, suppression, limitation, portabilité, testament numérique). Pour en savoir plus, consulter la page “Données personnelles”.</p>
    </div>`;
  }

  handleButtonAcceptClick() {
    this.modalContent.innerHTML = this.getConfirmModalContent();
    this.element.classList.add('dsfr-doc-modal-cgu-accepted');
    const buttonClose = this.modalContent.querySelector('#button-cgu-accepted-close');
    if (buttonClose) buttonClose.focus();
    const cguVersion = this.element.getAttribute('data-cgu-version');
    this.element.removeAttribute('data-fr-concealing-backdrop');
    document.cookie = `cgu-version=${cguVersion}; path=/; max-age=${60 * 60 * 24 * 365 * 2}`;

    fetch('/api/cgu_consent', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        version: cguVersion
      })
    });
  }

  handleButtonDenyClick() {
    window.location.href = '/';
  }
}

export default ConsentCGU;
