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

class Storybook extends Element {
  get iframe() {
    return this.element;
  }

  init() {
    this.setIframeTheme();
    this.listenChangeDisplay();
    window.addEventListener('message', this.handleMessage.bind(this));
  }

  handleMessage(event) {
    if (event.data?.type === 'storybook-height-change' && this.iframe.id === event.data.iframeId) {
      this.setIframeHeight(event.data.height);
    }
  }

  setIframeHeight(height) {
    if (isNaN(height) || !height) {
      this.iframe.style.height = '100%';
    } else {
      this.iframe.style.height = height + 'px';
    }
  }

  setIframeTheme() {
    const theme = document.documentElement.getAttribute('data-fr-theme') || 'light';
    const url = new URL(window.location.origin + this.iframe.dataset.src);
    url.searchParams.set('globals', `theme:${theme}`);
    this.iframe.src = url.toString();
  }

  listenChangeDisplay() {
    const display = document.getElementById('fr-display');
    const radios = display.querySelectorAll('input');
    radios.forEach((radio) => {
      radio.addEventListener('change', () => {
        this.setIframeTheme();
      });
    });
  }
}

export default Storybook;
