import { CdkPortalOutlet, TemplatePortal } from '@angular/cdk/portal';
import { NgClass } from '@angular/common';
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
  signal,
  TemplateRef,
  ViewContainerRef,
} from '@angular/core';

@Component({
  selector: 'fast-tip-container',
  imports: [CdkPortalOutlet, NgClass],
  template: `
<div class="tooltip" role="tooltip" [ngClass]="position()" [id]="id()">
  @if (contentPortal()) {
  <ng-container [cdkPortalOutlet]="contentPortal()"></ng-container>
  } @else {
  {{ message() }}
  }
</div>
  `,
  styles: `
.tooltip {
  background-color: var(--color-inverse);
  color: var(--color-inverse-foreground);
  padding: 4px 6px;
  border-radius: 4px;
  font-size: 14px;
  transition: opacity 0.3s ease;
  position: relative;
}

.tooltip::after {
  content: '';
  position: absolute;
  width: 0;
  height: 0;
  border-style: solid;
}

.tooltip.top::after {
  top: calc(100% - 1px);
  left: 50%;
  transform: translateX(-50%);
  border-width: 6px 6px 0 6px;
  border-color: var(--color-inverse) transparent transparent transparent;
}

.tooltip.right::after {
  top: 50%;
  left: -5px;
  transform: translateY(-50%);
  border-width: 6px 6px 6px 0;
  border-color: transparent var(--color-inverse) transparent transparent;
}

.tooltip.bottom::after {
  bottom: calc(100% - 1px);
  left: 50%;
  transform: translateX(-50%);
  border-width: 0 6px 6px 6px;
  border-color: transparent transparent var(--color-inverse) transparent;
}

.tooltip.left::after {
  top: 50%;
  right: -5px;
  transform: translateY(-50%);
  border-width: 6px 0 6px 6px;
  border-color: transparent transparent transparent var(--color-inverse);
}
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FastTipContainerComponent {
  message = signal<string>('');

  position = signal<string>('top');

  content = signal<TemplateRef<unknown> | undefined>(undefined);
  vf = inject(ViewContainerRef);

  id = signal<string>('');

  contentPortal = computed(() => {
    const content = this.content();
    if (content) {
      return new TemplatePortal(content, this.vf);
    }
    return;
  });
}
