import { Component, computed, inject, signal } from '@angular/core';
import { RouterLink } from '@angular/router';
import { forkJoin } from 'rxjs';
import { ApiService, HallSummary, MatchResult } from '../../core/api.service';
import { LangService } from '../../core/lang.service';
import { WizardStateService } from '../../core/wizard-state.service';
import { RevealDirective } from '../../core/reveal.directive';

interface Row extends MatchResult {
  hall?: HallSummary;
}

@Component({
  selector: 'app-results',
  standalone: true,
  imports: [RouterLink, RevealDirective],
  template: `
    <section class="results">
      <div class="container">
        <div class="head">
          <p class="ornament"><span class="glyph">&#10086;</span></p>
          <p class="eyebrow">{{ lang.t('hero_eyebrow') }}</p>
          <h2>{{ lang.t('results_title') }}</h2>
          <p class="muted">{{ lang.t('results_sub') }}</p>
        </div>

        @if (loading()) {
          <div class="center loading muted">{{ lang.t('loading') }}</div>
        } @else {
          <div class="grid">
            @for (r of rows(); track r.hall_id; let i = $index) {
              <article class="hall card" appReveal [revealDelay]="i * 70" [class.is-match]="r.matched" [routerLink]="['/halls', r.hall_id]">
                <div class="thumb" [style.background-image]="cover(r)">
                  <span class="badge" [class.badge--match]="r.matched">
                    {{ r.matched ? lang.t('match') : lang.t('near') }} · {{ r.score }}%
                  </span>
                </div>
                <div class="body">
                  <h3>{{ name(r) }}</h3>
                  <p class="venue muted">{{ r.venue_name }}</p>
                  @if (r.hall) {
                    <div class="meta muted">
                      <span>{{ lang.t('capacity') }}: {{ r.hall.capacity_min }}–{{ r.hall.capacity_max }} {{ lang.t('guests_unit') }}</span>
                      <span>·</span>
                      <span>{{ lang.t('from') }} {{ money(r.hall.min_budget) }}</span>
                    </div>
                  }
                  @if (r.reasons.length) {
                    <div class="reasons">
                      <span class="reasons-label">{{ lang.t('why_not') }}:</span>
                      <ul>
                        @for (reason of r.reasons; track reason) { <li>{{ reason }}</li> }
                      </ul>
                    </div>
                  }
                </div>
              </article>
            }
          </div>

          <div class="center" style="margin-top:40px;">
            <a routerLink="/wizard" class="btn btn--ghost">{{ lang.t('start_over') }}</a>
          </div>
        }
      </div>
    </section>
  `,
  styles: [`
    .results { padding: 56px 0 90px; min-height: calc(100vh - 72px);
      background: linear-gradient(180deg, var(--cream) 0%, var(--blush) 100%); }
    .head { max-width: 640px; margin: 0 auto 44px; text-align: center; }
    .head .ornament { margin-bottom: 14px; }
    .head h2 { margin: 6px 0 8px; }
    .loading { padding: 80px 0; font-size: 1.1rem; }
    .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 28px; }
    .hall { overflow: hidden; display: flex; flex-direction: column; cursor: pointer;
      position: relative; transition: transform .3s ease, box-shadow .3s ease, border-color .3s ease; }
    .hall:hover { transform: translateY(-6px); box-shadow: var(--shadow); }
    .hall.is-match { border-color: var(--gold-soft); }
    .hall.is-match::before {
      content: ''; position: absolute; top: 0; left: 0; right: 0; height: 3px; z-index: 2;
      background: linear-gradient(90deg, var(--gold-soft), var(--gold), var(--gold-deep));
    }
    .thumb {
      height: 208px; background-size: cover; background-position: center;
      background-color: var(--cream-2); position: relative;
      background-image: linear-gradient(135deg, #f0e6d6, #e2d2bb);
    }
    .thumb::after {
      content: ''; position: absolute; inset: 0;
      background: linear-gradient(180deg, transparent 55%, rgba(42,33,34,.34));
    }
    .badge {
      position: absolute; top: 14px; z-index: 1;
      inset-inline-start: 14px;
      background: rgba(42,33,34,.72); color: #fff; backdrop-filter: blur(4px);
      padding: 7px 15px; border-radius: 999px; font-size: .8rem; font-weight: 600;
      letter-spacing: .3px;
    }
    .badge--match { background: linear-gradient(135deg, var(--gold), var(--gold-deep)); color: #3a2c12; }
    .body { padding: 24px; display: flex; flex-direction: column; gap: 6px; }
    .body h3 { margin: 0; color: var(--onyx); }
    .venue { margin: 0; font-size: .92rem; }
    .meta { display: flex; gap: 8px; font-size: .88rem; margin-top: 4px; flex-wrap: wrap; }
    .reasons { margin-top: 14px; padding-top: 14px; border-top: 1px dashed var(--line); }
    .reasons-label { font-weight: 600; font-size: .82rem; color: var(--gold-deep); }
    .reasons ul { margin: 6px 0 0; padding-inline-start: 18px; }
    .reasons li { font-size: .85rem; color: var(--ink-soft); margin-bottom: 2px; }
  `],
})
export class ResultsComponent {
  lang = inject(LangService);
  private api = inject(ApiService);
  private state = inject(WizardStateService);

  loading = signal(true);
  rows = signal<Row[]>([]);

  constructor() {
    const token = this.state.token();
    if (!token) { this.loading.set(false); return; }

    forkJoin({ match: this.api.match(token), halls: this.api.halls(this.state.answers().event_type) }).subscribe({
      next: ({ match, halls }) => {
        const byId = new Map(halls.data.halls.map((h) => [h.id, h]));
        this.rows.set(match.data.results.map((r) => ({ ...r, hall: byId.get(r.hall_id) })));
        this.loading.set(false);
      },
      error: () => this.loading.set(false),
    });
  }

  name(r: Row): string {
    if (this.lang.lang() === 'ar' && r.hall?.name_ar) return r.hall.name_ar;
    return r.hall_name;
  }

  cover(r: Row): string {
    return r.hall?.cover_url ? `url('${r.hall.cover_url}')` : '';
  }

  money(n: number): string {
    return new Intl.NumberFormat(this.lang.lang() === 'ar' ? 'ar-EG' : 'en-EG').format(n) + ' EGP';
  }
}
