/**
 * @license
 * Copyright 2019 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */

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

@customElement('iu-column')

export class GridColumn extends LitElement {
  static override styles = css`
    :host{
      display: block;
      grid-column: span var(--column-span-sm, 1);
    }
    @media ${unsafeCSS(breakpoints.md)} {
      :host{
          grid-column: span var(--column-span-md, var(--column-span-sm, 1));
      }
    }
    @media ${unsafeCSS(breakpoints.lg)} {
      :host{
          grid-column: span var(--column-span-lg, var(--column-span-md, var(--column-span-sm, 1)));
      }
    }
    @media ${unsafeCSS(breakpoints.xl)} {
      :host{
          grid-column: span var(--column-span-xl, var(--column-span-lg, var(--column-span-md, var(--column-span-sm, 1))));
      }
      :host([sticky]){
        position: sticky;
        top: var(--column-sticky-top, 0);
        align-self: start;
      }
    }
  `;

  @property({type: Number}) sm: number = 12;
  @property({type: Number}) md?: number;
  @property({type: Number}) lg?: number;
  @property({type: Number}) xl?: number;
  @property({type: Boolean}) sticky?: false;
  @property({type: Number}) top?: number;
  
  @query('slot') slotElement!: HTMLSlotElement;

  // make sure that every component inside this component has <iu-container> set 
  // to nested to disable padding left on the container itself
  private updateSlottedElements() {
    // Get all slotted elements
    const slottedElements = this.slotElement.assignedElements({ flatten: true });
    slottedElements.forEach((slot) => {
      if (slot instanceof HTMLElement) {
        console.log('test')
          // Set the `nested` attribute or property
          slot.setAttribute('nested', 'true');
      }
    });
  }
  
  override firstUpdated() {
    super.firstUpdated();
    this.updateSlottedElements();
  }


  override updated(changedProperties) {

    const sizes = ['sm', 'md', 'lg', 'xl'];

    sizes.forEach((size) => {
      if (changedProperties.has(size)) {
        const value = this[size];
        // Update the CSS variable dynamically
        this.style.setProperty(`--column-span-${size}`, value?.toString() || '');
      }
    });

    if(this.sticky){
      this.top && this.style.setProperty(`--column-sticky-top`, `${Math.round(this.top/16)}rem`);
    }

    if(this.sticky && this.top){
    }

  }

  override render() {
    return html`
        <slot></slot>
    `;
  }

}

declare global {
  interface HTMLElementTagNameMap {
    'iu-column': GridColumn;
  }
}