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

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

@customElement('iu-card')

export class Card extends LitElement {

  @query('.img') cardImg;
  @query('.content') cardContent;

  static override styles = css`
    :host{
      display: block;
    }
    .card{
      display: block;
      text-decoration: none;
      color: var(--iu-color-black);
      position: relative;
      aspect-ratio: 1/1;
      overflow: hidden;
    }
    .card:hover .img{
      height: 100% !important;
    }
    .img{
      transition: height .2s ease;
      position: absolute;
      top: 0px;
      left: 0px;
      width: 100%;
      overflow: hidden;
      background-image: linear-gradient(to top, var(--iu-color-grey-400), var(--iu-color-grey-200));
    }
    .img img{
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    .header{
      padding-top: 0.75rem;
      padding-bottom: 0.75rem;
      display: flex;
      justify-content: space-between;
      font: var(--iu-f-0);
      color: var(--iu-color-grey-300);
    }
    .content p{
      font: var(--iu-f-2);
      font-weight: bold;
      margin-top: 0;
    }
  `;

  setCardHeight = () => {
    requestAnimationFrame(() => {
      const cardHeight = this.clientHeight
      const cardTextHeight = this.cardContent.clientHeight
      const imgHeight = cardHeight-cardTextHeight
      this.cardImg.style.height = `${imgHeight}px`
      this.cardContent.style.marginTop = `${imgHeight}px`
    })
  }

  override firstUpdated() {
    super.firstUpdated();

    const imgElement = this.cardImg.querySelector('img');
    if (imgElement) {
      imgElement.addEventListener('load', this.setCardHeight);
    }
    
    this.setCardHeight()

    // Observe resizing
    const resizeObserver = new ResizeObserver(() => this.setCardHeight());
    resizeObserver.observe(this);

    
  }

  @property() href : string = '';
  @property() category : string = 'Categoria';
  @property() date : string = '01.01.2024';
  @property() name : string = 'Default';
  @property() img? : string = '';
  
  override render() {
    return html`
        <a href="${this.href}" class="card">
            <div class="img">
                ${this.img && html`<img src="${this.img}">`}
            </div>
            <div class="content">
                <div class="header">
                    <span class="category">${this.category}</span>
                    <span class="date">${this.date}</span>
                </div>
                <p>${this.name}</p>
            </div>
        </a>
    `;
  }

}

declare global {
  interface HTMLElementTagNameMap {
    'iu-card': Card;
  }
}