import { CommonModule, NgClass } from '@angular/common';
import { Component, OnInit, inject } from '@angular/core';
import { Router, RouterLink } from '@angular/router';
import { ButtonModule } from '@progress/kendo-angular-buttons';

import { CashlineApiService, DemoBootstrapResponse, DemoCredential } from '../core/cashline-api.service';
import { CutoverI18nService } from '../core/cutover-i18n.service';
import { defaultJourneyId, isCustomerSession, isFinanceSession, isIslamicFinanceSession, isOperationsSession, isSupplierSession, resolveJourneyRoute } from '../core/uat-access.util';
import { JOURNEY_ORDER, getDefaultJourneyStepId, getJourneyDefinition } from '../journeys/journey-definitions';
import { JourneyDefinition, JourneyId } from '../journeys/journey.models';

interface DemoJourneyCard {
  journeyId: JourneyId;
  title: string;
  persona: string;
  moduleGroup: string;
  summary: string;
  phase: string;
  stepTitles: string[];
}

interface DemoCredentialCard {
  credential: DemoCredential;
  journeyId: JourneyId;
  route: string;
  packageTone: 'internal' | 'supplier' | 'customer';
}

interface DemoPersonaGroup {
  id: 'internal' | 'supplier' | 'customer';
  title: string;
  summary: string;
  cards: DemoCredentialCard[];
}

@Component({
  selector: 'app-demo-center',
  standalone: true,
  imports: [CommonModule, NgClass, RouterLink, ButtonModule],
  template: `
    <section class="demo-center" [attr.dir]="i18n.dir()">
      <article class="surface-card demo-hero">
        <div class="surface-card__body demo-hero__body">
          <div class="demo-hero__copy">
            <span class="eyebrow">{{ t('Interactive demo center') }}</span>
            <h1>{{ t('CashLine end-to-end client demo') }}</h1>
            <p>
              {{ t('Launch each business role with one click, move through the real journeys, and use the demo guidance layer as a practical operational manual during sales walkthroughs, stakeholder reviews, onboarding, and product familiarization.') }}
            </p>
          </div>

          <div class="demo-hero__actions">
            <button kendoButton type="button" class="primary-action-btn" (click)="openPublicOnboarding('supplier')">
              {{ t('Open supplier onboarding demo') }}
            </button>
            <button kendoButton type="button" fillMode="outline" class="secondary-action-btn" (click)="openPublicOnboarding('customer')">
              {{ t('Open customer onboarding demo') }}
            </button>
          </div>
        </div>
      </article>

      <article class="surface-card demo-section">
        <div class="surface-card__header">
          <div>
            <span class="eyebrow">{{ t('Role launch') }}</span>
            <h2>{{ t('Demo personas and guided access') }}</h2>
          </div>
        </div>
        <div class="surface-card__body">
          <div class="feedback error" *ngIf="bootstrapErrorText">{{ t(bootstrapErrorText) }}</div>
          <div class="feedback" *ngIf="bootstrapLoading">{{ t('Loading interactive demo personas...') }}</div>

          <div class="persona-groups" *ngIf="!bootstrapLoading && personaGroups.length">
            <section class="persona-group" *ngFor="let group of personaGroups">
              <div class="persona-group__head">
                <div>
                  <span class="eyebrow">{{ t(group.title) }}</span>
                  <h3>{{ t(group.summary) }}</h3>
                </div>
              </div>

              <div class="persona-card-grid">
                <article class="persona-card" *ngFor="let card of group.cards" [attr.data-tone]="card.packageTone">
                  <div class="persona-card__meta">
                    <span class="section-pill">{{ t(card.credential.userType) }}</span>
                    <span class="section-pill section-pill--soft">{{ t(getJourneyCard(card.journeyId).title) }}</span>
                  </div>

                  <div class="persona-card__copy">
                    <h4>{{ card.credential.displayName }}</h4>
                    <p>{{ t(card.credential.summary) }}</p>
                    <dl class="persona-card__details">
                      <div>
                        <dt>{{ t('Username') }}</dt>
                        <dd>{{ card.credential.username }}</dd>
                      </div>
                      <div>
                        <dt>{{ t('Workspace') }}</dt>
                        <dd>{{ t(card.credential.workspace) }}</dd>
                      </div>
                    </dl>
                  </div>

                  <div class="persona-card__actions">
                    <button
                      kendoButton
                      type="button"
                      class="primary-action-btn"
                      [disabled]="launchingUsername === card.credential.username"
                      (click)="launchPersona(card.credential)">
                      {{ t(launchingUsername === card.credential.username ? 'Launching demo...' : 'Launch guided demo') }}
                    </button>
                  </div>
                </article>
              </div>
            </section>
          </div>
        </div>
      </article>

      <article class="surface-card demo-section">
        <div class="surface-card__header">
          <div>
            <span class="eyebrow">{{ t('Journey map') }}</span>
            <h2>{{ t('Modules and business walkthroughs') }}</h2>
          </div>
        </div>
        <div class="surface-card__body">
          <div class="journey-card-grid">
            <article class="journey-card" *ngFor="let card of journeyCards">
              <div class="journey-card__head">
                <div>
                  <h3>{{ t(card.title) }}</h3>
                  <p>{{ t(card.summary) }}</p>
                </div>
                <span class="section-pill section-pill--soft">{{ t(card.phase) }}</span>
              </div>

              <div class="journey-card__meta-grid">
                <article class="summary-card">
                  <span class="meta-label">{{ t('Primary role') }}</span>
                  <strong>{{ t(card.persona) }}</strong>
                </article>
                <article class="summary-card">
                  <span class="meta-label">{{ t('Module group') }}</span>
                  <strong>{{ t(card.moduleGroup) }}</strong>
                </article>
                <article class="summary-card">
                  <span class="meta-label">{{ t('Key screens') }}</span>
                  <strong>{{ card.stepTitles.length }}</strong>
                </article>
              </div>

              <div class="journey-card__steps">
                <span class="meta-label">{{ t('Guided screens') }}</span>
                <ul>
                  <li *ngFor="let stepTitle of card.stepTitles">{{ t(stepTitle) }}</li>
                </ul>
              </div>
            </article>
          </div>
        </div>
      </article>
    </section>
  `,
  styles: [`
    :host {
      display: block;
    }

    .demo-center {
      display: grid;
      gap: 18px;
    }

    .surface-card__header,
    .surface-card__body {
      padding: 22px;
    }

    .demo-hero__body,
    .persona-group,
    .journey-card,
    .persona-card {
      display: grid;
      gap: 16px;
    }

    .demo-hero {
      border: 1px solid var(--card-frame-strong);
      background:
        linear-gradient(180deg, rgba(255,255,255,.95), rgba(246,241,232,.92)),
        linear-gradient(135deg, rgba(23,71,104,.08), rgba(183,130,54,.12));
    }

    .demo-hero__actions,
    .persona-card__actions {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }

    .demo-section,
    .persona-card,
    .journey-card {
      border: 1px solid var(--card-frame);
      border-radius: var(--radius-2xl);
      background: rgba(255, 255, 255, 0.9);
      box-shadow: var(--shadow-md);
    }

    .persona-groups,
    .journey-card-grid {
      display: grid;
      gap: 18px;
    }

    .persona-card-grid,
    .journey-card-grid {
      grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
    }

    .persona-group__head h3,
    .journey-card__head h3,
    .persona-card__copy h4,
    .demo-hero__copy h1,
    .surface-card__header h2 {
      margin: 0;
    }

    .persona-group__head h3,
    .surface-card__header h2 {
      font-size: 1.08rem;
      line-height: 1.35;
    }

    .demo-hero__copy h1 {
      font-size: clamp(1.85rem, 2.8vw, 2.7rem);
      line-height: 1.08;
      letter-spacing: -0.03em;
    }

    .demo-hero__copy p,
    .journey-card__head p,
    .persona-card__copy p {
      margin: 0;
      color: var(--muted);
      line-height: 1.65;
    }

    .persona-card {
      padding: 18px;
    }

    .persona-card[data-tone='internal'] {
      border-color: color-mix(in srgb, var(--brand-deep) 28%, var(--card-frame));
    }

    .persona-card[data-tone='supplier'] {
      border-color: color-mix(in srgb, #9f6d22 44%, var(--card-frame));
    }

    .persona-card[data-tone='customer'] {
      border-color: color-mix(in srgb, #6c8b4b 40%, var(--card-frame));
    }

    .persona-card__meta,
    .journey-card__head {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      gap: 10px;
      align-items: flex-start;
    }

    .persona-card__details {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
      gap: 10px;
      margin: 0;
    }

    .persona-card__details div {
      padding: 10px 12px;
      border-radius: var(--radius-lg);
      border: 1px solid var(--card-frame);
      background: rgba(255, 255, 255, 0.76);
    }

    .persona-card__details dt,
    .meta-label,
    .eyebrow {
      margin: 0 0 4px;
      color: var(--muted);
      text-transform: uppercase;
      letter-spacing: 0.11em;
      font-size: 0.7rem;
    }

    .persona-card__details dd {
      margin: 0;
      color: var(--ink);
      font-weight: 700;
    }

    .journey-card {
      padding: 18px;
    }

    .journey-card__meta-grid {
      display: grid;
      gap: 10px;
      grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    }

    .journey-card__steps ul {
      margin: 8px 0 0;
      padding-inline-start: 18px;
      display: grid;
      gap: 7px;
      color: var(--ink);
    }

    .primary-action-btn,
    .secondary-action-btn {
      min-height: 42px;
    }

    .feedback {
      padding: 13px 15px;
      border-radius: var(--radius-xl);
      border: 1px solid var(--card-frame);
      background: rgba(255, 255, 255, 0.86);
    }

    .feedback.error {
      background: rgba(169, 68, 66, 0.12);
      color: #a94442;
    }

    @media (max-width: 720px) {
      .surface-card__header,
      .surface-card__body,
      .persona-card,
      .journey-card {
        padding: 18px;
      }

      .demo-hero__actions,
      .persona-card__actions {
        display: grid;
      }
    }
  `]
})
export class DemoCenterComponent implements OnInit {
  private readonly api = inject(CashlineApiService);
  private readonly router = inject(Router);
  protected readonly i18n = inject(CutoverI18nService);

  protected bootstrapLoading = true;
  protected bootstrapErrorText = '';
  protected launchingUsername = '';
  protected personaGroups: DemoPersonaGroup[] = [];
  protected readonly journeyCards: DemoJourneyCard[] = JOURNEY_ORDER.map((journeyId) => this.buildJourneyCard(getJourneyDefinition(journeyId)));

  async ngOnInit(): Promise<void> {
    await this.loadBootstrap();
  }

  protected t(value: string): string {
    return this.i18n.text(value);
  }

  protected getJourneyCard(journeyId: JourneyId): DemoJourneyCard {
    return this.journeyCards.find((card) => card.journeyId === journeyId) ?? this.journeyCards[0];
  }

  protected async launchPersona(credential: DemoCredential): Promise<void> {
    this.launchingUsername = credential.username;
    this.bootstrapErrorText = '';

    try {
      this.setDemoMode(true);
      const session = await this.api.authenticate(credential.username, credential.password, credential.clientType);
      const journeyId = this.resolveSessionJourneyId(session);
      await this.router.navigateByUrl(
        `${resolveJourneyRoute(journeyId)}?step=${encodeURIComponent(getDefaultJourneyStepId(journeyId))}&demo=1`
      );
    } catch (error) {
      this.bootstrapErrorText = error instanceof Error ? error.message : 'Unable to launch the selected demo persona.';
    } finally {
      this.launchingUsername = '';
    }
  }

  protected async openPublicOnboarding(prospectType: 'supplier' | 'customer'): Promise<void> {
    this.setDemoMode(true);
    await this.router.navigate(['/become', prospectType], { queryParams: { demo: '1' } });
  }

  private async loadBootstrap(): Promise<void> {
    this.bootstrapLoading = true;
    this.bootstrapErrorText = '';

    try {
      const bootstrap = await this.api.getBootstrap();
      this.personaGroups = this.buildPersonaGroups(bootstrap);
    } catch (error) {
      this.bootstrapErrorText = error instanceof Error ? error.message : 'Unable to load interactive demo personas.';
    } finally {
      this.bootstrapLoading = false;
    }
  }

  private buildPersonaGroups(bootstrap: DemoBootstrapResponse): DemoPersonaGroup[] {
    const cards = bootstrap.credentials.map((credential) => {
      const journeyId = this.resolveCredentialJourneyId(credential);
      return {
        credential,
        journeyId,
        route: resolveJourneyRoute(journeyId),
        packageTone: this.resolvePackageTone(journeyId)
      } satisfies DemoCredentialCard;
    });

    const groups: DemoPersonaGroup[] = [
      {
        id: 'internal',
        title: 'Internal demo roles',
        summary: 'Operations, finance, Islamic Finance, and monitoring personas for internal walkthroughs and business validation.',
        cards: cards.filter((card) => card.packageTone === 'internal')
      },
      {
        id: 'supplier',
        title: 'Supplier-facing demo roles',
        summary: 'Supplier personas for onboarding, documents, orders, invoicing, payments, reports, and financing walkthroughs.',
        cards: cards.filter((card) => card.packageTone === 'supplier')
      },
      {
        id: 'customer',
        title: 'Customer-facing demo roles',
        summary: 'Customer personas for onboarding, requests, orders, payments, reports, and account-service walkthroughs.',
        cards: cards.filter((card) => card.packageTone === 'customer')
      }
    ];

    return groups.filter((group) => group.cards.length > 0);
  }

  private buildJourneyCard(journey: JourneyDefinition): DemoJourneyCard {
    return {
      journeyId: journey.id,
      title: journey.title,
      persona: journey.persona,
      moduleGroup: journey.moduleGroup,
      summary: journey.description,
      phase: journey.currentPhase,
      stepTitles: journey.steps.slice(0, 5).map((step) => step.title)
    };
  }

  private resolveCredentialJourneyId(credential: DemoCredential): JourneyId {
    if (credential.workspace === 'supplier' || credential.roleCodes.includes('EXTERNAL_SUPPLIER_USER') || credential.roleCodes.includes('SUPPLIER_ADMIN')) {
      return 'supplier';
    }

    if (credential.workspace === 'customer' || credential.roleCodes.includes('EXTERNAL_CUSTOMER_USER') || credential.roleCodes.includes('CUSTOMER_ADMIN')) {
      return 'customer';
    }

    if (credential.workspace === 'islamic' || credential.roleCodes.includes('IF_OPERATIONS_MAKER')) {
      return 'islamic-finance';
    }

    if (credential.roleCodes.some((roleCode) => roleCode.startsWith('FINANCE_'))) {
      return 'finance-approvals';
    }

    return 'operations-control';
  }

  private resolveSessionJourneyId(session: { roleCodes: string[]; workspace: string }): JourneyId {
    if (isSupplierSession(session as never)) {
      return 'supplier';
    }

    if (isCustomerSession(session as never)) {
      return 'customer';
    }

    if (isIslamicFinanceSession(session as never)) {
      return 'islamic-finance';
    }

    if (isFinanceSession(session as never)) {
      return 'finance-approvals';
    }

    if (isOperationsSession(session as never)) {
      return defaultJourneyId(session as never);
    }

    return 'operations-control';
  }

  private resolvePackageTone(journeyId: JourneyId): 'internal' | 'supplier' | 'customer' {
    if (journeyId === 'supplier') {
      return 'supplier';
    }

    if (journeyId === 'customer') {
      return 'customer';
    }

    return 'internal';
  }

  private setDemoMode(enabled: boolean): void {
    if (typeof window === 'undefined') {
      return;
    }

    if (enabled) {
      window.localStorage.setItem('cashline-kendo-demo-mode', '1');
      return;
    }

    window.localStorage.removeItem('cashline-kendo-demo-mode');
  }
}
