import { Component, computed, inject } from '@angular/core';
import { RouterOutlet } from '@angular/router';

import { TenantService } from './core/services/tenant.service';
import { DEFAULT_TENANT_BRANDING } from './core/services/tenant-ssr-cache.store';

function hexToRgb(hex: string): string {
  const cleanHex = hex.replace('#', '').trim();
  let r = 0, g = 0, b = 0;
  if (cleanHex.length === 3) {
    r = parseInt(cleanHex[0] + cleanHex[0], 16);
    g = parseInt(cleanHex[1] + cleanHex[1], 16);
    b = parseInt(cleanHex[2] + cleanHex[2], 16);
  } else if (cleanHex.length >= 6) {
    r = parseInt(cleanHex.slice(0, 2), 16);
    g = parseInt(cleanHex.slice(2, 4), 16);
    b = parseInt(cleanHex.slice(4, 6), 16);
  }
  return `${r}, ${g}, ${b}`;
}

@Component({
  selector: 'app-root',
  imports: [RouterOutlet],
  templateUrl: './app.html',
  styleUrl: './app.scss',
  host: {
    '[style.--tenant-primary]': 'tenantPrimaryColor()',
    '[style.--tenant-secondary]': 'tenantSecondaryColor()',
    '[style.--tenant-danger]': 'tenantDangerColor()',
    '[style.--tenant-primary-rgb]': 'tenantPrimaryColorRgb()',
    '[style.--tenant-secondary-rgb]': 'tenantSecondaryColorRgb()',
    '[style.--tenant-danger-rgb]': 'tenantDangerColorRgb()',
    '[style.--tenant-header-footer-bg]': 'tenantHeaderFooterBgColor()'
  }
})
export class App {
  private readonly tenantService = inject(TenantService);

  protected readonly status = this.tenantService.status;

  protected readonly tenantPrimaryColor = computed(
    () => this.tenantService.tenant()?.primary_color ?? DEFAULT_TENANT_BRANDING.primaryColor
  );
  protected readonly tenantSecondaryColor = computed(
    () => this.tenantService.tenant()?.secondary_color ?? DEFAULT_TENANT_BRANDING.secondaryColor
  );
  protected readonly tenantDangerColor = computed(
    () => this.tenantService.tenant()?.danger_color ?? DEFAULT_TENANT_BRANDING.dangerColor
  );
  protected readonly tenantPrimaryColorRgb = computed(() =>
    hexToRgb(this.tenantPrimaryColor())
  );
  protected readonly tenantSecondaryColorRgb = computed(() =>
    hexToRgb(this.tenantSecondaryColor())
  );
  protected readonly tenantDangerColorRgb = computed(() =>
    hexToRgb(this.tenantDangerColor())
  );
  protected readonly tenantHeaderFooterBgColor = computed(
    () =>
      this.tenantService.tenant()?.header_footer_bg_color ??
      DEFAULT_TENANT_BRANDING.headerFooterBgColor
  );
}

