import { LitElement, html, css, unsafeCSS} from 'lit';
import { customElement, property } from 'lit/decorators.js';
import { breakpoints } from '../../breakpoints';

@customElement('iu-mobile-menu')

export class MobileMenu extends LitElement {

  @property({ type: String }) label? = 'Menu principale';
  @property({ type: Boolean, reflect: true }) open : boolean = false; 

  static override styles = css`
    :host {
        position: fixed;
        display: none;
        left: 0;
        height: calc(100dvh - 50px);
        width: 100%;
        max-width: 48rem;
        background: var(--iu-color-white);
        top: 50px;
        z-index: 50;
        overflow: auto;
    }
    @media ${unsafeCSS(breakpoints.md)} {
      :host{
        width: calc((100% - var(--iu-grid-offset)) - var(--iu-grid-gutter));
      }
    }
    :host([open]){
      display: block;
    }
    /* fallback if event listener doesn't work */
    @media ${unsafeCSS(breakpoints.xl)} {
      :host([open]){
        display: none;
      }
    }
    ul{
      list-style-type: none;
      padding: 0;
      margin: 0;
    }
  `;

  private handleMenuToggle = () => {
    this.open = !this.open;
    this.requestUpdate();
  };  

  override connectedCallback() {
    super.connectedCallback();
    window.addEventListener('toggle-mobile-menu', this.handleMenuToggle);
  }
  
  override disconnectedCallback() {
    window.removeEventListener('toggle-mobile-menu', this.handleMenuToggle);
    super.disconnectedCallback();
  }  

  override render() {
    return html`
        <nav aria-label="${this.label}" role="navigation">
            <ul>
                <slot></slot>
            </ul>
        </nav>
    `;
  }
}

declare global {
    interface HTMLElementTagNameMap {
      'iu-mobile-menu': MobileMenu;
    }
  }