import { Component, inject, signal } from '@angular/core';
import { Router, RouterLink } from '@angular/router';
import { ApiService } from '../../core/api.service';
import { LangService } from '../../core/lang.service';
import { SelectionService, SelectedHall, SelectedItem } from '../../core/selection.service';
import { WizardStateService } from '../../core/wizard-state.service';

@Component({
  selector: 'app-selection',
  standalone: true,
  imports: [RouterLink],
  template: `
    <section class="sel">
      <div class="container">
        <div class="head">
          <h2>{{ lang.t('my_selection') }}</h2>
          <p class="muted">{{ selection.count() }} {{ lang.t('selection_count') }}</p>
        </div>

        @if (selection.count() === 0) {
          <div class="card empty center">
            <p class="muted">{{ lang.t('selection_empty') }}</p>
            <a routerLink="/results" class="btn btn--ghost">{{ lang.t('browse_halls') }}</a>
          </div>
        } @else {
          @for (h of selection.items(); track h.hallId) {
            <article class="card item fade-in">
              <div class="thumb" [style.background-image]="h.coverUrl ? 'url(' + h.coverUrl + ')' : ''"></div>
              <div class="info">
                <div class="row-top">
                  <div>
                    <h3>{{ name(h) }}</h3>
                    <p class="venue muted">{{ h.venueName }}</p>
                  </div>
                  <button class="remove" (click)="selection.remove(h.hallId)">✕ {{ lang.t('remove') }}</button>
                </div>
                <div class="lines">
                  @if (h.packageName) {
                    <div class="line"><span class="muted">{{ lang.t('package') }}</span><span>{{ h.packageName }} — {{ lang.money(h.packagePrice) }}</span></div>
                  }
                  @if (h.addons.length) {
                    <div class="line"><span class="muted">{{ lang.t('addons_label') }}</span>
                      <span>@for (a of h.addons; track a.addon_id) {<span class="pill">{{ a.name }}</span>}</span>
                    </div>
                  }
                  @if (variantSwaps(h).length) {
                    <div class="line"><span class="muted">{{ lang.t('swaps') }}</span>
                      <span>@for (it of variantSwaps(h); track it.item_id) {<span class="pill">{{ it.variant_label }} ({{ (it.variant_delta || 0) > 0 ? '+' : '' }}{{ lang.money(it.variant_delta || 0) }})</span>}</span>
                    </div>
                  }
                </div>
                <div class="sub-total">{{ lang.money(selection.hallTotal(h)) }}</div>
              </div>
            </article>
          }

          <div class="card foot">
            <div class="total-box">
              <span>{{ lang.t('estimated_total') }}</span>
              <strong>{{ lang.money(selection.total()) }}</strong>
            </div>
            <button class="btn btn--gold btn--lg" [disabled]="busy()" (click)="proceed()">
              {{ busy() ? lang.t('processing') : lang.t('continue_to_visits') }} <span class="arr">→</span>
            </button>
          </div>
        }
      </div>
    </section>
  `,
  styles: [`
    .sel { padding: 46px 0 90px; min-height: calc(100vh - 72px); }
    .head { text-align: center; margin-bottom: 30px; }
    .head h2 { margin-bottom: 4px; }
    .empty { padding: 56px; display: flex; flex-direction: column; gap: 18px; align-items: center; max-width: 560px; margin: 0 auto; }
    .item { display: grid; grid-template-columns: 180px 1fr; overflow: hidden; margin-bottom: 18px; }
    .thumb { background-size: cover; background-position: center; background-color: var(--cream-2); min-height: 150px; }
    .info { padding: 20px 24px; }
    .row-top { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; }
    .row-top h3 { margin: 0 0 2px; }
    .venue { margin: 0; font-size: .9rem; }
    .remove { background: none; border: none; color: var(--danger); cursor: pointer; font-weight: 600; font-family: inherit; }
    .lines { margin: 14px 0 8px; display: flex; flex-direction: column; gap: 8px; }
    .line { display: flex; gap: 14px; font-size: .94rem; }
    .line > .muted { min-width: 90px; }
    .pill { display: inline-block; background: var(--cream-2); border-radius: 999px; padding: 3px 12px; font-size: .82rem; margin-inline-end: 6px; margin-bottom: 4px; }
    .sub-total { text-align: end; font-weight: 700; color: var(--gold-deep); }
    .foot { display: flex; justify-content: space-between; align-items: center; padding: 22px 26px; margin-top: 8px; gap: 16px; flex-wrap: wrap; }
    .total-box { display: flex; flex-direction: column; }
    .total-box strong { font-size: 1.6rem; }
    .arr { display: inline-block; }
    [dir='rtl'] .arr { transform: scaleX(-1); }
    @media (max-width: 700px) { .item { grid-template-columns: 1fr; } .thumb { min-height: 160px; } }
  `],
})
export class SelectionComponent {
  lang = inject(LangService);
  selection = inject(SelectionService);
  private api = inject(ApiService);
  private state = inject(WizardStateService);
  private router = inject(Router);

  busy = signal(false);

  name(h: { name: string; name_ar?: string }): string {
    return this.lang.lang() === 'ar' && h.name_ar ? h.name_ar : h.name;
  }

  /** Items the guest swapped to a non-base variant (for the breakdown). */
  variantSwaps(h: SelectedHall): SelectedItem[] {
    return (h.items || []).filter((it) => (it.variant_index || 0) > 0);
  }

  proceed(): void {
    const token = this.state.token();
    if (!token) { this.router.navigate(['/visit']); return; }
    this.busy.set(true);
    this.api.selectHalls(token, this.selection.toPayload()).subscribe({
      next: () => { this.busy.set(false); this.router.navigate(['/visit']); },
      error: () => { this.busy.set(false); this.router.navigate(['/visit']); },
    });
  }
}
