import { CommonModule } from '@angular/common';
import { Component, Input, OnChanges, SimpleChanges, inject } from '@angular/core';
import { RouterLink, RouterLinkActive } from '@angular/router';

import { CutoverI18nService } from './core/cutover-i18n.service';

type SessionSummaryLike = {
  displayName: string;
  username: string;
  workspace: string;
};

type JourneyLink = {
  id: string;
  label: string;
  route: string;
  section: string;
  summary: string;
  packageId: string;
};

type FeatureLink = {
  id: string;
  label: string;
  subtitle: string;
  route: string;
  stepId: string;
};

type FrontendPackageDefinition = {
  id: string;
  label: string;
  title: string;
  summary: string;
  governance: string;
  featureLinks: readonly FeatureLink[];
};

interface NavNode {
  id: string;
  label: string;
  route: string;
  summary: string;
  children: readonly FeatureLink[];
  active: boolean;
  glyph: string;
  tone: string;
}

@Component({
  selector: 'app-workspace-side-nav',
  standalone: true,
  imports: [CommonModule, RouterLink, RouterLinkActive],
  styleUrl: './workspace-side-nav.component.scss',
  template: `
    <aside class="side-menu">
      <div class="side-menu__brand">
        <img class="cashline-logo cashline-logo--compact" src="assets/cashline-logo.png" alt="CashLine Logo">
        <div class="side-menu__brand-copy">
          <p class="eyebrow">{{ t('CashLine ERP') }}</p>
          <h2>{{ t(currentPackage?.title || 'Business Workspace') }}</h2>
          <p class="side-menu__copy">{{ t(currentPackage?.summary || 'Use the side menu to move across the modules and features assigned to your role.') }}</p>
        </div>
      </div>

      <div class="side-menu__snapshot">
        <article class="snapshot-card">
          <span class="meta-label">{{ t('Modules') }}</span>
          <strong>{{ navNodes.length }}</strong>
        </article>
        <article class="snapshot-card">
          <span class="meta-label">{{ t('Visible functions') }}</span>
          <strong>{{ childCount }}</strong>
        </article>
      </div>

      <div class="side-menu__section">
        <p class="eyebrow">{{ t(currentPackage?.label || 'Navigation') }}</p>
        <nav class="side-menu__tree" [attr.aria-label]="currentPackage?.title || 'Navigation'">
          <article class="nav-node" *ngFor="let node of navNodes" [attr.data-tone]="node.tone" [class.nav-node--open]="isExpanded(node.id)" [class.nav-node--active]="node.active">
            <div class="nav-node__row">
              <a
                [routerLink]="[node.route]"
                routerLinkActive="active"
                class="nav-node__link"
                [class.active]="node.active">
                <span class="nav-node__icon">{{ node.glyph }}</span>
                <span class="nav-node__copy">
                  <strong>{{ t(node.label) }}</strong>
                  <span>{{ t(node.summary) }}</span>
                </span>
              </a>
              <button
                type="button"
                class="nav-node__toggle"
                [attr.aria-expanded]="isExpanded(node.id)"
                (click)="toggleNode(node.id)">
                <span class="nav-node__chevron">⌄</span>
              </button>
            </div>

            <div class="nav-node__children" [class.nav-node__children--open]="isExpanded(node.id)">
              <div class="nav-node__children-inner">
                <a
                  *ngFor="let child of node.children"
                  [routerLink]="[child.route]"
                  [queryParams]="{ step: child.stepId }"
                  class="nav-child"
                  [class.active]="currentFeatureStepId === child.stepId">
                  <span class="nav-child__dot"></span>
                  <span class="nav-child__copy">
                    <strong>{{ t(child.label) }}</strong>
                    <span>{{ t(child.subtitle) }}</span>
                  </span>
                </a>
              </div>
            </div>
          </article>
        </nav>
      </div>

    </aside>
  `
})
export class WorkspaceSideNavComponent implements OnChanges {
  private readonly i18n = inject(CutoverI18nService);

  @Input() currentPackage: FrontendPackageDefinition | null = null;
  @Input() visibleJourneyLinks: readonly JourneyLink[] = [];
  @Input() currentJourney: JourneyLink | null = null;
  @Input() currentFeatureLinks: readonly FeatureLink[] = [];
  @Input() journeyFeatureLinks: Readonly<Record<string, readonly FeatureLink[]>> = {};
  @Input() currentFeatureStepId: string | null = null;

  protected navNodes: NavNode[] = [];
  private readonly expandedNodeIds = new Set<string>();

  protected get childCount(): number {
    return this.navNodes.reduce((sum, node) => sum + node.children.length, 0);
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['visibleJourneyLinks'] || changes['currentJourney'] || changes['journeyFeatureLinks']) {
      this.navNodes = this.visibleJourneyLinks.map((link) => ({
        id: link.id,
        label: link.label,
        route: link.route,
        summary: link.summary,
        children: this.journeyFeatureLinks[link.id] ?? [],
        active: this.currentJourney?.id === link.id,
        glyph: this.computeNodeGlyph(link.label),
        tone: this.computeNodeTone(link.id)
      }));

      if (this.currentJourney) {
        this.expandedNodeIds.add(this.currentJourney.id);
      } else if (this.navNodes[0]) {
        this.expandedNodeIds.add(this.navNodes[0].id);
      }
    }
  }

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

  protected isExpanded(nodeId: string): boolean {
    return this.expandedNodeIds.has(nodeId);
  }

  protected toggleNode(nodeId: string): void {
    if (this.expandedNodeIds.has(nodeId)) {
      this.expandedNodeIds.delete(nodeId);
      return;
    }

    this.expandedNodeIds.add(nodeId);
  }

  private computeNodeGlyph(label: string): string {
    const source = this.i18n.isArabic() ? this.t(label) : label;
    const words = source.trim().split(/\s+/).filter(Boolean);
    return words
      .slice(0, 2)
      .map((word) => word.replace(/^[^A-Za-z\u0600-\u06FF]*/, '').charAt(0))
      .join('') || '•';
  }

  private computeNodeTone(nodeId: string): string {
    switch (nodeId) {
      case 'supplier':
        return 'supplier';
      case 'customer':
        return 'customer';
      case 'accounting-office':
        return 'finance';
      case 'islamic-finance':
        return 'murabaha';
      case 'finance-approvals':
      case 'reporting-center':
        return 'finance';
      case 'workflow-monitoring':
        return 'monitoring';
      case 'operations-control':
      default:
        return 'operations';
    }
  }
}
