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

@customElement('iu-paragraph')

export class Paragraph extends LitElement {
  static override styles = css`
    :host{
      display: block;
      // margin-bottom: var(--iu-spacing-block-xs); 
      margin-bottom: var(--iu-spacing-block-sm); 
    }
    @media ${unsafeCSS(breakpoints.lg)} {
      .column-1{
        grid-column: span 6;
        // width: calc(50% - var(--iu-grid-gutter));
      }
    }
    iu-container{
      margin-bottom: 0;
    }
    .fs-1 {
      --iu-p-f: var(--iu-f-1);
    }
    .fs-2 {
      --iu-p-f: var(--iu-f-2);
    }
    @media ${unsafeCSS(breakpoints.md)} {
      .fs-3{
          --iu-p-f: var(--iu-f-2);
          max-width: 90%
      }
    }
    @media ${unsafeCSS(breakpoints.xl)} {
      .fs-3{
        --iu-p-f: var(--iu-f-4);
      }
    }
    ::slotted(p){
      font: var(--iu-p-f) !important;
      margin-bottom: var(--iu-spacing-2);
      margin-top: 0;
    }
    ::slotted(.last){
      margin-bottom: 0 !important;
    }
  `;

  @property({type: Number}) columns: number = 1;
  @property({type: Number}) size = 1;

  @property({type: Boolean, reflect: true}) nested?: boolean = false;

  @queryAssignedNodes() private slottedElements?: NodeList;

  private updateLastElement() {
    const slotted = this.slottedElements ? Array.from(this.slottedElements) : [];

    if (slotted.length > 0) {
      const lastEl = slotted[slotted.length - 1];
      if (lastEl instanceof HTMLElement) {
        lastEl.classList.add('last');
      }
    }
  }

  private wrapListItems(){
    const lists = this.querySelectorAll('ul, ol');
    lists.forEach((list) => {
      list.classList.add('list')
    })
    const items = this.querySelectorAll('li')
    items.forEach(item => {
      const content = item.innerHTML
      const newContent = `<span>${content}</span>`
      item.innerHTML = newContent
    })
  }

  override firstUpdated(){
    this.updateLastElement();
    this.wrapListItems();
  }

  override render() {
    return html`
      <iu-container ?nested=${this.nested} columns="${this.columns}">
        <div class="fs-${this.size}">
          <slot></slot>
        </div>
      </iu-container>
    `;
  }

}

declare global {
  interface HTMLElementTagNameMap {
    'iu-paragraph': Paragraph;
  }
}