import { ChangeDetectionStrategy, Component, computed, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterLink } from '@angular/router';
import { ProjectEditorFacade } from '../facade/project-editor.facade';
import { TranslatePipe } from '../../../i18n/translate.pipe';
import { TranslateService } from '../../../i18n/translate.service';
import { LanguageService } from '../../../services/language.service';
import { InputComponent } from '../../../shared/ui/input/input.component';
import { FormFieldComponent } from '../../../shared/ui/form-field/form-field.component';
import { SectionCardComponent } from '../../../shared/ui/section-card/section-card.component';

@Component({
  selector: 'app-project-editor-general-section',
  standalone: true,
  imports: [FormsModule, RouterLink, TranslatePipe, InputComponent, FormFieldComponent, SectionCardComponent],
  templateUrl: './general-section.component.html',
  styleUrls: ['./section.shared.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProjectEditorGeneralSectionComponent {
  private readonly facade = inject(ProjectEditorFacade);
  private readonly translate = inject(TranslateService);
  private readonly languageService = inject(LanguageService);

  readonly bootstrap = this.facade.bootstrap;
  readonly fieldError = (key: string): string | null => {
    const messageKey = this.facade.fieldError(key);
    return messageKey ? this.translate.t(messageKey) : null;
  };

  /** Default locale first, so the chip list reads as "primary + others". */
  readonly orderedLocales = computed(() => {
    const localization = this.bootstrap()?.localization;
    if (!localization) {
      return [] as string[];
    }
    const rest = localization.supportedLocales.filter(code => code !== localization.defaultLocale);
    return [localization.defaultLocale, ...rest];
  });

  readonly languagesRoute = computed(() => ['/', this.languageService.currentLanguage(), 'edit', 'languages']);

  isDefaultLocale(code: string): boolean {
    return code === this.bootstrap()?.localization.defaultLocale;
  }

  updateMarketplaceName(value: string): void {
    this.facade.updateBootstrap(current => ({
      ...current,
      branding: { ...current.branding, brandName: value },
      tenant: { ...current.tenant, name: value }
    }));
  }

  updateDomain(value: string): void {
    this.facade.updateBootstrap(current => ({
      ...current,
      tenant: { ...current.tenant, host: value, websiteBaseUrl: `https://${value}` }
    }));
  }

  updateDescription(value: string): void {
    this.facade.updateBootstrap(current => ({
      ...current,
      seo: {
        ...current.seo,
        default: {
          ...current.seo.default,
          description: value
        }
      }
    }));
  }
}
