import {
  Component,
  EventEmitter,
  Output,
  OnInit,
  OnChanges,
  SimpleChanges,
  Input,
  ChangeDetectorRef,
  OnDestroy,
  ViewChild,
  ElementRef,
  AfterViewInit
} from '@angular/core';

import {
  AbstractControl,
  AsyncValidatorFn,
  FormBuilder,
  FormGroup,
  ValidationErrors,
  ValidatorFn,
  Validators
} from '@angular/forms';

import { ActivatedRoute, Router } from '@angular/router';
import { HttpResponse, HttpStatusCode } from '@angular/common/http';
import {
  catchError,
  debounceTime,
  firstValueFrom,
  forkJoin,
  interval,
  lastValueFrom,
  map,
  Observable,
  of,
  Subject,
  Subscription,
  takeUntil,
  tap
} from 'rxjs';

import { ToastrService } from 'ngx-toastr';
import { DocumentUploadComponent } from '../document-upload/document-upload.component';
import { ContactDetailsFormService } from '../contact-details-form/service/contact-details-form.service';
import { ContactDocumentUploadService } from '../contact-document-upload/service/contact-document-upload.service';
import { NotificationService } from '../notification/service/notification.service';
import { AssetService } from '../asset.service';
import { UserService } from '../user/service/user.service';
import { DocumentUploadService } from '../document-upload/service/document-upload.service';
import { OrganisationDetailsService } from '../organisation-details/service/organisation-details.service';
import { RegistrationService } from '../registration/service/Registration.service';
import { PanService } from '../document-upload/service/pan.service';
import { SuperAdminDetailsService } from './services/super-admin-details.service';

@Component({
  standalone: false,
  selector: 'app-super-admin-details',
  templateUrl: './super-admin-details.component.html',
  styleUrls: ['./super-admin-details.component.css']
})

export class SuperAdminDetailsComponent
  implements OnInit, OnChanges, AfterViewInit, OnDestroy {

  @Output() formSubmitted: EventEmitter<void> = new EventEmitter<void>();
  @Output() back: EventEmitter<void> = new EventEmitter<void>(); // Emit event after form submission

  adminUploadedDocs: any[] = [];
  techUploadedDocs: any[] = [];
  billingUploadedDocs: any[] = [];

  contactSubmissionAttempted: boolean = false;
  @Output() adminDocDetails: EventEmitter<any> = new EventEmitter<any>();
  // @Output() techDocDetails: EventEmitter<any> = new EventEmitter<any>();
  // @Output() billDocDetails: EventEmitter<any> = new EventEmitter<any>();
  @Output() addUserContactDetailsSaved: EventEmitter<any> = new EventEmitter<any>();
  @Output() adminDocError: EventEmitter<any> = new EventEmitter<any>();
  // @Output() techDocError: EventEmitter<any> = new EventEmitter<any>();
  // @Output() finDocError: EventEmitter<any> = new EventEmitter<any>();
  @Input() organisationId: number = 0;
  @Input() applicationId: string | null = null;

  @Input() choosenContactType: string = '';

  @Input() choosenOrgId: number = 0;


  fullForm: FormGroup;
  // applicationId: string | null = null;
  user = ''; // Replace with appropriate value
  userMailId = localStorage.getItem('email');
  selectedDocType = '';
  imagUrl: any
  pdfUrl: any
  notificationList: any[] = [];
  notificationCount = 0;
  notificationError: string | null = null; // Holds error messages if any
  addressDetails: any;
  private notificationSubscription: Subscription;

  admAddress: string = '';
  //techAddress: string = '';
  //billAddress: string = '';
  fullAddress: string = '';
  constructor(private fb: FormBuilder, private superAdminContactService: SuperAdminDetailsService, private route: ActivatedRoute,
    private contactDoc: ContactDocumentUploadService,
    private assetService: AssetService, private notificationService: NotificationService,
    private cdr: ChangeDetectorRef,
    private userService: UserService,
    private panService: PanService,
    private router: Router,
    private contactDocumentsService: ContactDocumentUploadService,
    private organisationDocumentsService: DocumentUploadService,
    private organisationDetailsService: OrganisationDetailsService,
    private toastr: ToastrService, private registrationService: RegistrationService) {

    this.fullForm = this.fb.group({
      // Admin Form Controls
      superAdminId: 0,
      admPanNumber: ['', [Validators.required]],
      admDob: ['', [Validators.required]],
      admFullName: ['', [Validators.required, this.alphabetValidator]],
      admEmail: ['', [
        Validators.required,
        Validators.email,
        this.customEmailValidator()
      ]],
      // admEmail: ['', [Validators.required, Validators.email, this.customEmailValidator()], [this.emailNotExistsInDbValidator(this.contactDetailsFormService, (this.organisationId != 0 && this.organisationId != null) ? this.organisationId : localStorage.getItem('orgId'))]],
      admPhone: [{ value: '', disabled: true }, [
        Validators.required,
        Validators.pattern('^[0-9]*$'),
        Validators.minLength(5),
        Validators.maxLength(10)
      ]],
      admCountryCode: ['', [Validators.required]],
      admAltCountryCode: ['91', [Validators.required]],
      admAltPhone: [{ value: '', disabled: false }, [
        Validators.required,
        Validators.pattern('^[0-9]*$'),
        Validators.minLength(8),
        Validators.maxLength(15)
      ]],
      admDesignation: ['', [Validators.required]],
      admAddress: ['', [Validators.required, Validators.minLength(5), Validators.maxLength(300), this.noSpecialCharAtStart]],

      // Technical Form Controls
      // technicalContactId: 0,
      // techPanNumber: ['', [Validators.required]],
      // techDob: ['', [Validators.required]],
      // techFullName: ['', [Validators.required, this.alphabetValidator]],
      // techEmail: ['', [Validators.required, Validators.email, this.customEmailValidator()], this.emailNotExistsInDbValidator(this.contactDetailsFormService, (this.organisationId != 0 && this.organisationId != null) ? this.organisationId : localStorage.getItem('orgId'))],
      // techCountryCode: ['', [Validators.required]],
      // techAltCountryCode: ['91', [Validators.required]],
      // techPhone: [{ value: '', disabled: true }, [
      //   Validators.required,
      //   Validators.pattern('^[0-9]*$'),
      //   Validators.minLength(5),
      //   Validators.maxLength(10)
      // ]],
      // techAltPhone: [{ value: '', disabled: false }, [
      //   Validators.required,
      //   Validators.pattern('^[0-9]*$'),
      //   Validators.minLength(8),
      //   Validators.maxLength(15)
      // ]],
      // techDesignation: ['', [Validators.required]],
      // techAddress: ['', [Validators.required, Validators.minLength(5), Validators.maxLength(300), this.noSpecialCharAtStart]],

      // Billing Form Controls
      // organisationalContactId: 0,
      // billingPanNumber: ['', [Validators.required]],
      // billingDob: ['', [Validators.required]],
      // billFullName: ['', [Validators.required, this.alphabetValidator]],
      // billEmail: ['', [Validators.required, Validators.email, this.customEmailValidator()], [this.emailNotExistsInDbValidator(this.contactDetailsFormService, this.organisationId != 0 ? this.organisationId : localStorage.getItem('orgId'))]],
      // billCountryCode: ['', [Validators.required]],
      // billAltCountryCode: ['91', [Validators.required]],
      // billPhone: [{ value: '', disabled: true }, [
      //   Validators.required,
      //   Validators.pattern('^[0-9]*$'),
      //   Validators.minLength(5),
      //   Validators.maxLength(10)
      // ]],
      // billAltPhone: [{ value: '', disabled: false }, [
      //   Validators.required,
      //   Validators.pattern('^[0-9]*$'),
      //   Validators.minLength(8),
      //   Validators.maxLength(15)
      // ]],
      // billDesignation: ['', [Validators.required, Validators.maxLength(50)]],
      // billAddress: ['', [Validators.required, Validators.minLength(5), Validators.maxLength(300), this.noSpecialCharAtStart]],
    },
      {
        validators: this.uniqueEmailValidator()
      });

    //     this.fullForm = this.fb.group({

    //   /* =======================
    //      COMMON PAN DETAILS
    //      ======================= */
    //       panNumber: [
    //   '',
    //   [
    //     Validators.required,
    //     Validators.minLength(10),
    //     Validators.maxLength(10),
    //     Validators.pattern(/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/)
    //   ]
    // ],
    //   dob: ['', Validators.required],

    //   /* =======================
    //      ADMIN CONTROLS (UNCHANGED)
    //      ======================= */
    //   administrativeContactId: 0,
    //   admFullName: ['', [Validators.required, this.alphabetValidator]],
    //   admEmail: ['', [
    //     Validators.required,
    //     Validators.email,
    //     this.customEmailValidator()
    //   ], [
    //     this.emailNotExistsInDbValidator(
    //       this.contactDetailsFormService,
    //       (this.organisationId != 0 && this.organisationId != null)
    //         ? this.organisationId
    //         : localStorage.getItem('orgId')
    //     )
    //   ]],
    //   admPhone: [{ value: '', disabled: true }, [
    //     Validators.required,
    //     Validators.pattern('^[0-9]*$'),
    //     Validators.minLength(5),
    //     Validators.maxLength(10)
    //   ]],
    //   admCountryCode: ['', Validators.required],
    //   admAltCountryCode: ['', Validators.required],
    //   admAltPhone: [{ value: '', disabled: true }, [
    //     Validators.required,
    //     Validators.pattern('^[0-9]*$'),
    //     Validators.minLength(8),
    //     Validators.maxLength(15)
    //   ]],
    //   admDesignation: ['', Validators.required],
    //   admAddress: ['', [
    //     Validators.required,
    //     Validators.minLength(5),
    //     Validators.maxLength(300),
    //     this.noSpecialCharAtStart
    //   ]],

    //   /* =======================
    //      TECH CONTROLS (UNCHANGED)
    //      ======================= */
    //   technicalContactId: 0,
    //   techFullName: ['', [Validators.required, this.alphabetValidator]],
    //   techEmail: ['', [
    //     Validators.required,
    //     Validators.email,
    //     this.customEmailValidator()
    //   ], this.emailNotExistsInDbValidator(
    //     this.contactDetailsFormService,
    //     (this.organisationId != 0 && this.organisationId != null)
    //       ? this.organisationId
    //       : localStorage.getItem('orgId')
    //   )],
    //   techCountryCode: ['', Validators.required],
    //   techAltCountryCode: ['', Validators.required],
    //   techPhone: [{ value: '', disabled: true }, [
    //     Validators.required,
    //     Validators.pattern('^[0-9]*$'),
    //     Validators.minLength(5),
    //     Validators.maxLength(10)
    //   ]],
    //   techAltPhone: [{ value: '', disabled: true }, [
    //     Validators.required,
    //     Validators.pattern('^[0-9]*$'),
    //     Validators.minLength(8),
    //     Validators.maxLength(15)
    //   ]],
    //   techDesignation: ['', Validators.required],
    //   techAddress: ['', [
    //     Validators.required,
    //     Validators.minLength(5),
    //     Validators.maxLength(300),
    //     this.noSpecialCharAtStart
    //   ]],

    //   /* =======================
    //      BILLING CONTROLS (UNCHANGED)
    //      ======================= */
    //   organisationalContactId: 0,
    //   billFullName: ['', [Validators.required, this.alphabetValidator]],
    //   billEmail: ['', [
    //     Validators.required,
    //     Validators.email,
    //     this.customEmailValidator()
    //   ], [
    //     this.emailNotExistsInDbValidator(
    //       this.contactDetailsFormService,
    //       this.organisationId != 0
    //         ? this.organisationId
    //         : localStorage.getItem('orgId')
    //     )
    //   ]],
    //   billCountryCode: ['', Validators.required],
    //   billAltCountryCode: ['', Validators.required],
    //   billPhone: [{ value: '', disabled: true }, [
    //     Validators.required,
    //     Validators.pattern('^[0-9]*$'),
    //     Validators.minLength(5),
    //     Validators.maxLength(10)
    //   ]],
    //   billAltPhone: [{ value: '', disabled: true }, [
    //     Validators.required,
    //     Validators.pattern('^[0-9]*$'),
    //     Validators.minLength(8),
    //     Validators.maxLength(15)
    //   ]],
    //   billDesignation: ['', [Validators.required, Validators.maxLength(50)]],
    //   billAddress: ['', [
    //     Validators.required,
    //     Validators.minLength(5),
    //     Validators.maxLength(300),
    //     this.noSpecialCharAtStart
    //   ]]

    // }, {
    //   validators: this.uniqueEmailValidator()
    // });

  }
  ngAfterViewInit(): void {
    this.setInitialCountryCodeWidth();
    this.setInitialAdminAltCountyCodeWidth();
  }
  setInitialCountryCodeWidth() {
    const countryCodeInput = this.countryCodeInput?.nativeElement;
    if (countryCodeInput) {
      const placeholderLength = countryCodeInput.placeholder.length;
      countryCodeInput.style.width = `${placeholderLength * 12 + 0}px`; // Set initial width
    }
  }
  setInitialAdminAltCountyCodeWidth() {
    const countryCodeInput = this.adminAltCode?.nativeElement;
    if (countryCodeInput) {
      const placeholderLength = countryCodeInput.placeholder.length;
      countryCodeInput.style.width = `${placeholderLength * 12 + 0}px`; // Set initial width
    }
  }
  // setInitialBillCountryCodeWidth() {
  //   const countryCodeInput = this.billCountryCode?.nativeElement;
  //   if (countryCodeInput) {
  //     const placeholderLength = countryCodeInput.placeholder.length;
  //     countryCodeInput.style.width = `${placeholderLength * 12 + 0}px`; // Set initial width
  //   }
  // }
  // setInitialBillAltCountryCodeWidth() {
  //   const countryCodeInput = this.billAltCountryCode?.nativeElement;
  //   if (countryCodeInput) {
  //     const placeholderLength = countryCodeInput.placeholder.length;
  //     countryCodeInput.style.width = `${placeholderLength * 12 + 0}px`; // Set initial width
  //   }
  // }
  // setInitialTechCountyCodeWidth() {
  //   const countryCodeInput = this.techCountryCode?.nativeElement;
  //   if (countryCodeInput) {
  //     const placeholderLength = countryCodeInput.placeholder.length;
  //     countryCodeInput.style.width = `${placeholderLength * 12 + 0}px`; // Set initial width
  //   }
  // }
  // setInitialAltTechCountyCodeWidth() {
  //   const countryCodeInput = this.techAltContryCode?.nativeElement;
  //   if (countryCodeInput) {
  //     const placeholderLength = countryCodeInput.placeholder.length;
  //     countryCodeInput.style.width = `${placeholderLength * 12 + 0}px`; // Set initial width
  //   }
  // }

  goBack(): void {
    //console.log('goBack');
    this.back.emit();
  }

  resetForm() {
    // Reset form values and validation states
    this.fullForm.reset();
    Object.keys(this.fullForm.controls).forEach((field) => {
      const control = this.fullForm.get(field);
      if (control) {
        control.markAsUntouched();
        control.markAsPristine();
      }
      this.resetErrorMessages();
    });

  }
  @ViewChild(DocumentUploadComponent) documentUploadedForm: DocumentUploadComponent;

  // Method to reset the error messages in the DocumentUploadComponent
  resetErrorMessages() {
    if (this.documentUploadedForm) {
      this.documentUploadedForm.closedForm();
    }
  }

  async ngOnChanges(changes: SimpleChanges): Promise<void> {
    if (changes['organisationId']) {
      this.organisationId = changes['organisationId'].currentValue;
      //console.log('organisationId changed:', changes['organisationId'].currentValue);
      // Add custom logic here for handling the updated data
      this.getOrgDetails();
    }
    this.setAddress();
    // this.loadNotifications();
  }
  countryCodes;
  async getAllCountryCodes() {
    this.organisationDetailsService.getAllCountryCodes().subscribe({
      next: (response) => {
        this.countryCodes = response.body
        //console.log(this.countryCodes)
      }
    })
  }
  addAdditionalOficer: string = ''
  listOfEmailsAndRoleMap: Map<string, string[]>
  async ngOnInit(): Promise<void> {
    this.getOrgDetails();
    await this.getLoggedInUserDetails();
    //  this.fullForm.get('admAltCountryCode')?.disable();

    // AUTO FILL LOGGED IN USER EMAIL AND MOBILE NUMBER

    this.fullForm.patchValue({

      // Super Admin / Administrative
      admEmail: this.loggedInUser?.emailId || this.loggedInUser?.userId || '',
      admAltPhone: this.loggedInUser?.mobileNumber || '',

    });
    //console.log(this.organisationId)
    this.fullForm.get('admPhone')?.enable();
    this.getRegularExpressionForEmail();
    //console.log('Organisation ID:', this.organisationId);
    this.getAllCountryCodes();
    this.setAddress();

    // this.applicationId = sessionStorage.getItem('applicationId'); // Retrieve applicationId
    this.applicationId = localStorage.getItem('applicationId');
    //console.log('Retrieved Application ID from sessionStorage:', this.applicationId);
    // this.loadNotifications();
    // this.setupNotificationPolling();

    if (this.loggedInUser.organisationId > 0) {
      //console.log('org id > 0')
      //console.log("newAddUser value"+sessionStorage.getItem('newAddUser'))
      if (sessionStorage.getItem("newAddUser") == "null" || sessionStorage.getItem("newAddUser") == '' ||
        sessionStorage.getItem('newAddUser') == undefined) {
        this.getExistingDocsOfAOBOTOofficers();
      }

    }
    this.submitClickSubject.pipe(
      debounceTime(this.DEBOUNCE_TIME),
      takeUntil(this.destroy$) // Ensure subscription is cleaned up
    ).subscribe(() => {
      console.log('🔥 Debounce fired → calling onSubmit()');
      this.onSubmit(); // Call the actual submission logic after debounce
    });

    // this.assetService.addAdditionalOfficers$.subscribe(text => {
    //   this.addAdditionalOficer = text;
    //   // You can add logic here based on the received text
    //   if (this.addAdditionalOficer === 'AddOfficer') {
    //     forkJoin({
    //       users: this.getUsersList(),
    //       contacts: this.getContactOfficersDetails()
    //     }).pipe(
    //       // The 'map' operator is where the data transformation happens.
    //       map(results => {
    //         // Log the raw data to confirm it's coming through
    //         //console.log("Users from API:", results.users);
    //         //console.log("Contacts from API:", results.contacts);

    //         // Create the Map to store the combined data.
    //         // Key: email (string)
    //         // Value: array of roles (string[])
    //         const combinedMap = new Map<string, string[]>();

    //         // 1. Process the users list first
    //         results.users.forEach(user => {
    //           const email = user.userId;
    //           const userRolesArray = user.userRoles;

    //           // Get the existing roles for this email or start with an empty array
    //           const existingRoles = combinedMap.get(email) || [];

    //           if (!user.isDeleted) {
    //             // Loop through the nested 'userRoles' array
    //             userRolesArray.forEach(roleObject => {
    //               const roleName = roleObject.roleName;

    //               // Check for duplicate roles before adding
    //               if (!existingRoles.includes(roleName)) {
    //                 existingRoles.push(roleName);
    //               }
    //             });
    //           }

    //           // Always update the map with the email (even if no roles for deleted users)
    //           combinedMap.set(email, existingRoles);
    //         });

    //         // 2. Process the contacts list and merge with the user data
    //         results.contacts.forEach(contact => {
    //           const roles = combinedMap.get(contact.emailId);
    //           if (roles) {
    //             // If the contact's email already exists (from the users list)
    //             if (!roles.includes(contact.contactRole)) {
    //               roles.push(contact.contactRole);
    //             }
    //           } else {
    //             // If the email is new (not in the users list), add it
    //             combinedMap.set(contact.emailId, [contact.contactRole]);
    //           }
    //         });

    //         //console.log("Final Combined Map:", combinedMap);

    //         // You can return the map directly or convert it to an array if you
    //         // need to use it with *ngFor in the template.
    //         return combinedMap;
    //       })
    //     ).subscribe(finalMap => {
    //       // This is the final result. You can now use it in your component.
    //       // E.g., this.combinedUserRoles = finalMap;
    //       //console.log("Final Map is available in the subscription:", finalMap);
    //       this.listOfEmailsAndRoleMap = finalMap;
    //     });
    //   }

    // });
    //   this.selectedAdminAltCountryCode = '+91';
    //  this.fullForm.patchValue({
    // countryCode: '+91'
    // });
    //   this.fullForm.get('admAltPhone')?.enable();

    //   this.selectedTechAltCountryCode = '+91';
    //  this.fullForm.patchValue({
    // countryCode: '+91'
    // });
    //  this.fullForm.get('techAltPhone')?.enable();
    //   this.selectedBillAltCountryCode = '+91';
    //  this.fullForm.patchValue({
    // countryCode: '+91'
    // });
    //  this.fullForm.get('billAltPhone')?.enable();


    this.fullForm.patchValue({
      admAltCountryCode: '91',
    });

    this.selectedAdminAltCountryCode = '+91';


    // Enable all phone fields by default

    setTimeout(() => {
      this.fullForm.get('admAltPhone')?.enable();
    });

  }

  getExistingDocsOfAOBOTOofficers() {
    //console.log('enetered')
    this.contactDocumentsService.getContactOfficerDocumentsWithMail('Superadmin', this.organisationId,this.userMailId).subscribe({
      next: (response) => {
        //this.techUploadedDocs = response.body;
        if (response.body.length > 0) {
          //console.log(response.body)
          response.body.forEach(adminDoc => {
            var doc = { type: '', filename: '', file: new Blob(), value: '' };
            //console.log(adminDoc.fileName.endsWith('pdf'))
            if (adminDoc.fileName.endsWith('pdf')) {
              doc.type = 'application/pdf';
            } else if (adminDoc.fileName.endsWith('png')) {
              doc.type = 'image/png';
            } else if (adminDoc.fileName.endsWith('jpg')) {
              doc.type = 'image/jpg';
            } else if (adminDoc.fileName.endsWith('jpeg')) {
              doc.type = 'image/jpeg';
            }
            //doc.type = adminDoc.documentType;
            doc.filename = adminDoc.fileName;

            if (adminDoc.documentType === 'Aadhaar') {

              doc.file = this.base64ToBlob(adminDoc.aadharDocument, doc.type);
              doc.value = adminDoc.aadharNumber;
            } else if (adminDoc.documentType === 'PAN') {
              doc.file = this.base64ToBlob(adminDoc.panDocument, doc.type);
              doc.value = adminDoc.panNumber;
            } else if (adminDoc.documentType === 'Organization Identity Card') {
              doc.file = this.base64ToBlob(adminDoc.organisationIdDocument, doc.type);
              doc.value = '';
            }


            // console.log(doc); 
            const file = new File([doc.file], adminDoc.fileName, { type: doc.type })
            //console.log(file)

            //  const uploadedDoc = {
            //   type: this.adminSelectedDocType,
            //   fileName: file.name,
            //   fileSize: file.size, // Optional for extra checks
            //   value: this.adminInputValue ,
            //   organisationId: this.organisationId,
            //   contactType:'Administrative',
            //   file:file
            // };
            const uploadedDoc = {
              type: adminDoc.documentType,
              fileName: doc.filename,
              fileSize: file.size, // Optional for extra checks
              value: doc.value,
              organisationId: adminDoc.organisationId,
              contactType: 'Superadmin',
              file: file
            };
            this.adminUploadedDocs.push(uploadedDoc);
            //console.log(uploadedDoc);
            //console.log(this.adminUploadedDocs);
          })
          this.adminDocDetails.emit(this.adminUploadedDocs);
        }
      }
    });

    // this.contactDocumentsService.getContactOfficerDocuments('Billing', this.organisationId).subscribe({
    //   next: (response) => {
    //     if (response.body.length > 0) {
    //       //console.log(response.body);

    //       response.body.forEach(billDoc => {
    //         var doc = { type: '', filename: '', file: new Blob(), value: '' };

    //         // Set MIME type based on file extension
    //         if (billDoc.fileName.endsWith('pdf')) {
    //           doc.type = 'application/pdf';
    //         } else if (billDoc.fileName.endsWith('png')) {
    //           doc.type = 'image/png';
    //         } else if (billDoc.fileName.endsWith('jpg')) {
    //           doc.type = 'image/jpg';
    //         } else if (billDoc.fileName.endsWith('jpeg')) {
    //           doc.type = 'image/jpeg';
    //         }

    //         doc.filename = billDoc.fileName;

    //         // Assign corresponding file and value
    //         if (billDoc.documentType === 'Aadhaar') {

    //           doc.file = this.base64ToBlob(billDoc.aadharDocument, doc.type);
    //           doc.value = billDoc.aadharNumber;
    //         } else if (billDoc.documentType === 'PAN') {

    //           doc.file = this.base64ToBlob(billDoc.panDocument, doc.type);
    //           doc.value = billDoc.panNumber;
    //         } else if (billDoc.documentType === 'Organization Identity Card') {

    //           doc.file = this.base64ToBlob(billDoc.organisationIdDocument, doc.type);
    //           doc.value = '';
    //         }

    //         //console.log(doc);

    //         // Convert Blob to File
    //         const file = new File([doc.file], billDoc.fileName, { type: doc.type });

    //         const uploadedDoc = {
    //           type: billDoc.documentType,
    //           fileName: doc.filename,
    //           fileSize: file.size, // Optional for extra checks
    //           value: doc.value,
    //           organisationId: billDoc.organisationId,
    //           contactType: 'Billing',
    //           file: file
    //         };

    //         // this.billingUploadedDocs.push(uploadedDoc);
    //         //console.log(uploadedDoc);
    //         //console.log(this.billingUploadedDocs);
    //       });
    //       // this.billDocDetails.emit(this.billingUploadedDocs);
    //     }
    //   }
    // });


    // this.contactDocumentsService.getContactOfficerDocuments('Technical', this.organisationId).subscribe({
    //   next: (response) => {
    //     if (response.body.length > 0) {
    //       //console.log(response.body);

    //       response.body.forEach(techDoc => {
    //         var doc = { type: '', filename: '', file: new Blob(), value: '' };

    //         // Set MIME type based on file extension
    //         if (techDoc.fileName.endsWith('pdf')) {
    //           doc.type = 'application/pdf';
    //         } else if (techDoc.fileName.endsWith('png')) {
    //           doc.type = 'image/png';
    //         } else if (techDoc.fileName.endsWith('jpg')) {
    //           doc.type = 'image/jpg';
    //         } else if (techDoc.fileName.endsWith('jpeg')) {
    //           doc.type = 'image/jpeg';
    //         }

    //         doc.filename = techDoc.fileName;

    //         // Assign corresponding file and value
    //         if (techDoc.documentType === 'Aadhaar') {
    //           doc.file = this.base64ToBlob(techDoc.aadharDocument, doc.type);
    //           // doc.file = techDoc.aadharDocument;
    //           doc.value = techDoc.aadharNumber;
    //         } else if (techDoc.documentType === 'PAN') {
    //           doc.file = this.base64ToBlob(techDoc.panDocument, doc.type);
    //           // doc.file = techDoc.panDocument;
    //           doc.value = techDoc.panNumber;
    //         } else if (techDoc.documentType === 'Organization Identity Card') {
    //           doc.file = this.base64ToBlob(techDoc.organisationIdDocument, doc.type);
    //           // doc.file = techDoc.organisationIdDocument;
    //           doc.value = '';
    //         }

    //         //console.log(doc);

    //         // Convert Blob to File
    //         const file = new File([doc.file], techDoc.fileName, { type: doc.type });

    //         const uploadedDoc = {
    //           type: techDoc.documentType,
    //           fileName: doc.filename,
    //           fileSize: file.size, // Optional for extra checks
    //           value: doc.value,
    //           organisationId: techDoc.organisationId,
    //           contactType: 'Technical',
    //           file: file
    //         };

    //         // this.techUploadedDocs.push(uploadedDoc);
    //         //console.log(uploadedDoc);
    //         //console.log(this.techUploadedDocs);
    //       });
    //       // this.techDocDetails.emit(this.techUploadedDocs);
    //     }
    //   }
    // });

  }

  setAddress(): void {
    this.addressDetails = JSON.parse(sessionStorage.getItem('addressDetails') || '{}');

    if (this.addressDetails && this.addressDetails.address) {
      // Concatenate the full address into one string
      this.fullAddress = `${this.addressDetails.address}, ${this.addressDetails.city}, ${this.addressDetails.state} - ${this.addressDetails.pincode}`;
      this.fullForm.patchValue({
        admAddress: this.fullAddress,
        //techAddress: this.fullAddress,
        //billAddress: this.fullAddress,
      });

      this.cdr.detectChanges();

    }
  }
  onAdminStdChange() {

    const stdCode = this.fullForm.get('admCountryCode')?.value;

    if (stdCode && stdCode.toString().trim() !== '') {

      this.fullForm.get('admPhone')?.enable();

    } else {

      this.fullForm.get('admPhone')?.disable();
      this.fullForm.get('admPhone')?.reset();

    }

    this.fullForm.get('admPhone')?.updateValueAndValidity();
  }
  // onTechStdChange() {
  //   let std = this.fullForm.get('techCountryCode')?.value;

  //   std = std?.trim(); 

  //   if (std && std.trim() !== '') {
  //     this.fullForm.get('techPhone')?.enable();
  //   } else {
  //     this.fullForm.get('techPhone')?.disable();
  //   }
  // }
  // onBillStdChange() {
  //   let std = this.fullForm.get('billCountryCode')?.value;
  // std = std?.trim();
  //   if (std && std.trim() !== '') {
  //     this.fullForm.get('billPhone')?.enable();
  //   } else {
  //     this.fullForm.get('billPhone')?.disable();
  //   }
  // }
  ngOnDestroy(): void {
    if (this.notificationSubscription) {
      this.notificationSubscription.unsubscribe();
    }

    this.destroy$.next();
    this.destroy$.complete();

  }

  private setupNotificationPolling(): void {
    this.notificationSubscription = interval(30000).subscribe(() => {
      this.loadNotifications();
    });
  }

  base64ToBlob(base64: string, contentType: string = '') {
    const byteCharacters = atob(base64);
    const byteArrays = [];

    for (let offset = 0; offset < byteCharacters.length; offset += 512) {
      const slice = byteCharacters.slice(offset, offset + 512);

      const byteNumbers = new Array(slice.length);
      for (let i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i);
      }

      const byteArray = new Uint8Array(byteNumbers);
      byteArrays.push(byteArray);
    }

    return new Blob(byteArrays, { type: contentType });
  }

  loadNotifications(): void {
    //console.log(this.userMailId);
    if (this.userMailId) {
      this.notificationService.getNotifications(this.userMailId).subscribe(
        (notifications: any[]) => {
          this.notificationList = notifications; // Bind to the template
          this.notificationCount = notifications.filter(n => n.status === 'Unread').length; // Update count
          this.cdr.detectChanges(); // Ensure view updates
          //console.log('Notifications loaded:', this.notificationList);
        },
        error => {
          this.notificationError = 'Error fetching notifications: ' + error.message;
          //console.error('Error fetching notifications:', error);
        }
      );
    }
  }

  sanitizeInput(event: Event, controlName: string): void {
    const input = event.target as HTMLInputElement;

    input.value = input.value.replace(/[^0-9]/g, '');

    this.fullForm.get(controlName)?.setValue(input.value, { emitEvent: false });

    if (controlName == "admAltPhone") {
      this.validateAltAdminCountryCode();
    } else if (controlName == "admPhone") {
      this.validateAdminStdCode();
    }
  }

  // handleTechValidationChange(isValid: boolean): void {
  //   //console.log('Validation status:', isValid);
  // }

  // setTechUploadedDocuments(docs: any[]): void {
  //   this.techUploadedDocs = docs;
  //   //console.log('Uploaded documents updated:', this.techUploadedDocs);
  // }

  handleAdminValidationChange(isValid: boolean): void {
    //console.log('Validation status:', isValid);
  }

  setAdminUploadedDocuments(docs: any[]): void {
    console.log('ADMIN DOCS RECEIVED => ', docs);
    this.adminUploadedDocs = docs ? [...docs] : [];
    console.log('FINAL DOC COUNT => ', this.adminUploadedDocs.length);

  }

  // handleBillingValidationChange(isValid: boolean): void {
  //   //console.log('Validation status:', isValid);
  // }

  // setBillingUploadedDocuments(docs: any[]): void {
  //   this.billingUploadedDocs = docs;
  //   //console.log('Uploaded documents updated:', this.billingUploadedDocs);
  // }

  async onSubmitNewContact() {
    // this.isLoading=true;
    // if (choosenContactType !== '') {
    //   if (choosenContactType === 'Administrative Officer') {
        const adminDetails = {
          admFullName: this.fullForm.get('admFullName')?.value,
          admDob: this.fullForm.get('admDob')?.value,
          admPanNumber: this.fullForm.get('admPanNumber')?.value,
          admEmail: this.fullForm.get('admEmail')?.value,
          admPhone: this.fullForm.get('admPhone')?.value,
          admAltPhone: this.fullForm.get('admAltPhone')?.value,
          admCountryCode: this.fullForm.get('admCountryCode')?.value,
          // admAltCountryCode: this.fullForm.get('admAltCountryCode')?.value,
          admAltCountryCode: '+' + this.fullForm.get('admAltCountryCode')?.value,
          admDesignation: this.fullForm.get('admDesignation')?.value,
          admAddress: this.fullForm.value.admAddress,

          addressLine1: this.orgDetails.address,
          city: this.orgDetails.city,
          state: this.orgDetails.state,
          pincode: this.orgDetails.pincode,
          documents: this.fullForm.get('superAdminDocuments')?.value,

          applicationId: this.applicationId,
          organisationId: this.organisationId,
          isActive: null,
        };

        this.adminUploadedDocs.forEach(docs => {
          docs.email = adminDetails.admEmail;
        })
        //console.log(this.adminUploadedDocs)

        const adminUploadedDoc = [...this.adminUploadedDocs];

        // await lastValueFrom(
        //   this.contactDetailsFormService.saveAdminDetailsForm(
        //     this.contactDetailsFormData,
        //     adminUploadedDoc,
        //     this.applicationId,
        //     this.userMailId
        //   )
        // ).then(
        //   response => {
        //     let isContactDetailsSaved = false;

        //     if (response.status === HttpStatusCode.Ok) {
        //       isContactDetailsSaved = response.body?.success || false;

        //       this.contactDetailsFormData.adminContact = null;

        //       if (sessionStorage.getItem("newAddUser") == "active") {
        //         this.addUserContactDetailsSaved.emit("closeTheModal");
        //       }

        //       this.isLoading = false;
        //     }
        //   },
        //   error => {
        //     if (error.status === HttpStatusCode.Unauthorized) {
        //       this.isLoading = false;
        //       this.router.navigateByUrl("session-timeout");
        //       return;
        //     }
        //     else if (error.status === HttpStatusCode.ServiceUnavailable) {
        //       this.isLoading = false;
        //       this.toastr.error('Network error, please contact registrar');
        //       return;
        //     }
        //     else {
        //       this.isLoading = false;
        //       this.toastr.error('Error, please try after some time');
        //       return;
        //     }
        //   }
        // );
        // this.contactDetailsFormService.updateAdminDetails(adminDetails).subscribe(response => {
        //   //console.log('Admin details saved successfully', response);
        //   //console.log(adminDetails);
        //   // const applicationId = response.applicationId; // Ensure this is the correct field
        //   // sessionStorage.setItem('applicationId', applicationId);
        //   //console.log('Application ID saved to sessionStorage:', applicationId);
        //   //console.log(adminDetails);
        //   if(sessionStorage.getItem("newAddUser")=="active"){
        //   this.addUserContactDetailsSaved.emit("closeTheModal")
        //   }
        // }, error => {
        //   console.error('Error saving admin details', error);
        // });
      // }

      //     else if (choosenContactType === 'Technical Officer') {

      //   const techUploadedDocs = [...this.techUploadedDocs];

      //   await lastValueFrom(
      //     this.contactDetailsFormService.saveAdminDetailsForm(
      //       this.contactDetailsFormData,
      //       techUploadedDocs,
      //       this.applicationId,
      //       this.userMailId
      //     )
      //   ).then(
      //     response => {

      //       let isContactDetailsSaved = false;

      //       if (response.status === HttpStatusCode.Ok) {

      //         isContactDetailsSaved = response.body?.success || false;

      //         if (sessionStorage.getItem("newAddUser") == "active") {
      //           this.addUserContactDetailsSaved.emit("closeTheModal");
      //         }

      //         this.isLoading = false;
      //       }

      //     },
      //     error => {

      //       if (error.status === HttpStatusCode.Unauthorized) {

      //         this.isLoading = false;
      //         this.router.navigateByUrl("session-timeout");
      //         return;

      //       } else if (error.status === HttpStatusCode.ServiceUnavailable) {

      //         this.isLoading = false;
      //         this.toastr.error('Network error, please contact registrar');
      //         return;

      //       } else {

      //         this.isLoading = false;
      //         this.toastr.error('Error, please try after some time');
      //         return;
      //       }
      //     }
      //   );
      // }
      //     else if (choosenContactType === 'Billing Officer') {

      //   const billingUploadedDocs = [...this.billingUploadedDocs];

      //   await lastValueFrom(
      //     this.contactDetailsFormService.saveAdminDetailsForm(
      //       this.contactDetailsFormData,
      //       billingUploadedDocs,
      //       this.applicationId,
      //       this.userMailId
      //     )
      //   ).then(
      //     response => {

      //       let isContactDetailsSaved = false;

      //       if (response.status === HttpStatusCode.Ok) {

      //         isContactDetailsSaved = response.body?.success || false;

      //         if (sessionStorage.getItem("newAddUser") == "active") {
      //           this.addUserContactDetailsSaved.emit("closeTheModal");
      //         }

      //         this.isLoading = false;
      //       }

      //     },
      //     error => {

      //       if (error.status === HttpStatusCode.Unauthorized) {

      //         this.isLoading = false;
      //         this.router.navigateByUrl("session-timeout");
      //         return;

      //       } else if (error.status === HttpStatusCode.ServiceUnavailable) {

      //         this.isLoading = false;
      //         this.toastr.error('Network error, please contact registrar');
      //         return;

      //       } else {

      //         this.isLoading = false;
      //         this.toastr.error('Error, please try after some time');
      //         return;
      //       }
      //     }
      //   );
      // }
    // }
  }
  @ViewChild(DocumentUploadComponent, { static: false }) documentUploadComponent?: DocumentUploadComponent;
  documentValidationPassed = false;
  validationMessage = '';
  ContactdocumentValidationStatus(isValid: boolean) {
    //console.log('Validation status received from child:', isValid);
    this.documentValidationPassed = isValid;
  }


  contactDetailsFormData: any = {};
  isLoading: boolean = false;
  // --- Debouncing setup properties ---
  private submitClickSubject = new Subject<void>(); // Subject to emit on button click
  private destroy$ = new Subject<void>(); // For unsubscribing on component destruction
  private readonly DEBOUNCE_TIME = 1000; // Debounce time in milliseconds

  async onSubmit(): Promise<void> {
    console.log('🔥 onSubmit started');
    if (this.panStatus?.toLowerCase() !== 'valid') {
      this.toastr.error(
        'Please verify PAN before proceeding',
        'PAN Not Verified'
      );
      return;
    }
    this.isLoading = true; // Start loading state
    //console.log(this.fullForm)
    //console.log(this.fullForm.invalid ,this.adminUploadedDocs?.length<3,this.techUploadedDocs?.length<3,this.billingUploadedDocs?.length<3,this.techCountryCodeMobileCombinationError!='',this.adminCountryCodeMobileCombinationError!='',this.billCountryCodeMobileCombinationError!='' )
    // return
    await this.getLoggedInUserDetails();

    // this.documentUploadComponent.validateDocuments1();
    // console.log('Starting document validation...');
    // const isValid = await this.documentUploadComponent?.validateDocuments1();
    // console.log('Document Validation Result:', isValid);

    // if (!isValid) {
    //   this.validationMessage = 'One or more document file names are invalid!';
    //   console.error('One or more file names are invalid!');
    //   return;  // Prevent form submission if document validation fails
    // }

    // if (this.choosenContactType === 'Administrative Officer') {
    //   if (this.checkAdminSectionValidity()) {
    //     this.onSubmitNewContact(this.choosenContactType);
    //   }
    //   this.isLoading = false
    // } else if (this.choosenContactType === 'Technical Officer') {
    //   if (this.checkTechSectionValidity()) {
    //     this.onSubmitNewContact(this.choosenContactType);
    //   }
    //   this.isLoading = false
    // } else if (this.choosenContactType === 'Billing Officer') {
    //   if (this.checkBillSectionValidity()) {
    //     this.onSubmitNewContact(this.choosenContactType);
    //   }
    //   this.isLoading = false
    // }
    if (this.checkAdminSectionValidity()) {
        this.onSubmitNewContact();
      }
      // this.isLoading = false

    // Now, the unified submission logic:


    //if(this.adminUploadedDocs.length < )
    //  this.formSubmitted.emit();
    //console.log(this.fullForm.get('admAltPhone')?.value,this.fullForm.get('admCountryCode')?.value,
    //this.fullForm.get('techCountryCode')?.value,this.fullForm.get('techAltCountryCode')?.value,this.fullForm.get('billCountryCode')?.value,
    //this.fullForm.get('billAltCountryCode')?.value)
    if (this.fullForm.valid && this.adminUploadedDocs.length >= 1) {

      const adminDetails = {
        superAdminPanNumber: this.fullForm.get('admPanNumber')?.value,
        superAdminDob: this.fullForm.get('admDob')?.value,
        superAdminFullName: this.fullForm.get('admFullName')?.value,
        superAdminEmail: this.fullForm.get('admEmail')?.value,
        superAdminPhone: this.fullForm.get('admPhone')?.value,
        superAdminAltPhone: this.fullForm.get('admAltPhone')?.value,
        superAdminCountryCode: this.fullForm.get('admCountryCode')?.value,

        // admAltCountryCode: this.fullForm.get('admAltCountryCode')?.value,
        superAdminAltCountryCode: '+' + this.fullForm.get('admAltCountryCode')?.value,
        superAdminDesignation: this.fullForm.get('admDesignation')?.value,
        documents: this.fullForm.get('superAdminDocuments')?.value,
        superAdminAddress: this.fullForm.value.admAddress,

        addressLine1: this.addressDetails.address,
        city: this.addressDetails.city,
        state: this.addressDetails.state,
        pincode: this.addressDetails.pincode,
        applicationId: this.applicationId,
        organisationId: this.organisationId,
        isActive: null,
        // createdDateTime:'',
        createdByEmailId: this.userMailId

      };

      // const technicalDetails = {
      //   techPanNumber: this.fullForm.get('techPanNumber')?.value,
      //   techDob: this.fullForm.get('techDob')?.value,
      //   techFullName: this.fullForm.get('techFullName')?.value,
      //   techEmail: this.fullForm.get('techEmail')?.value,
      //   techPhone: this.fullForm.get('techPhone')?.value,
      //   techAltPhone: this.fullForm.get('techAltPhone')?.value,
      //   techCountryCode: this.fullForm.get('techCountryCode')?.value,
      //   // techAltCountryCode: this.fullForm.get('techAltCountryCode')?.value,
      //   techAltCountryCode: '+' + this.fullForm.get('techAltCountryCode')?.value,
      //   techDesignation: this.fullForm.get('techDesignation')?.value,
      //   techAddress: this.fullForm.value.techAddress,
      //   addressLine1: this.addressDetails.address,
      //   city: this.addressDetails.city,
      //   state: this.addressDetails.state,
      //   pincode: this.addressDetails.pincode,
      //   // documents: this.fullForm.get('techDocuments')?.value,
      //   applicationId: this.applicationId,
      //   organisationId: this.organisationId,
      //   isActive: null,
      //   //  createdDateTime:'',
      //   createdByEmailId: this.userMailId

      // };

      // const billingDetails = {
      //   billingPanNumber: this.fullForm.get('billingPanNumber')?.value,
      //   billingDob: this.fullForm.get('billingDob')?.value,
      //   billFullName: this.fullForm.get('billFullName')?.value,
      //   billEmail: this.fullForm.get('billEmail')?.value,
      //   billPhone: this.fullForm.get('billPhone')?.value,
      //   billAltPhone: this.fullForm.get('billAltPhone')?.value,
      //   billCountryCode: this.fullForm.get('billCountryCode')?.value,
      //   // billAltCountryCode: this.fullForm.get('billAltCountryCode')?.value,
      //   billAltCountryCode: '+' + this.fullForm.get('billAltCountryCode')?.value,
      //   billDesignation: this.fullForm.get('billDesignation')?.value,
      //   billAddress: this.fullForm.value.billAddress,
      //   addressLine1: this.addressDetails.address,
      //   city: this.addressDetails.city,
      //   state: this.addressDetails.state,
      //   pincode: this.addressDetails.pincode,
      //   // documents: this.fullForm.get('billDocuments')?.value,
      //   applicationId: this.applicationId,
      //   organisationId: this.organisationId,
      //   isActive: null,
      //   // createdDateTime:'',
      //   createdByEmailId: this.userMailId


      // };

      this.adminUploadedDocs.forEach(docs => {
        docs.email = adminDetails.superAdminEmail;
      })

      // this.techUploadedDocs.forEach(docs => {
      //   docs.email = technicalDetails.techEmail;
      // })

      // this.billingUploadedDocs.forEach(docs => {
      //   docs.email = billingDetails.billEmail;
      // })
      // await this.updateUserOnboardingStep();
      try {
        // 1. Emit document details (these are synchronous events, fine as is)
        // Move these further down if they should only happen after backend success.
        this.adminDocDetails.emit(this.adminUploadedDocs);
        // setTimeout(() => {
        //   this.techDocDetails.emit(this.techUploadedDocs);
        // }, 0);
        // setTimeout(() => {
        //   this.billDocDetails.emit(this.billingUploadedDocs);
        // }, 0);



        // 2. Save Admin details
        // If this fails, subsequent saves and document uploads won't happen.

        //const adminResponse = await lastValueFrom(this.contactDetailsFormService.updateAdminDetails(adminDetails));
        // console.log('Admin details saved successfully', adminResponse);

        // 3. Save Technical details
        // If this fails, billing and document uploads won't happen.
        //const techResponse = await lastValueFrom(this.contactDetailsFormService.updateTechDetails(technicalDetails));
        // console.log('Technical details saved successfully', techResponse);

        // 4. Save Billing details
        // If this fails, document uploads won't happen.
        //const billResponse = await lastValueFrom(this.contactDetailsFormService.updateBillDetails(billingDetails));
        // console.log('Billing details saved successfully', billResponse);

        // 5. Prepare and upload documents
        const uploadedDoc = [
          ...this.adminUploadedDocs,
          // ...this.techUploadedDocs,
          // ...this.billingUploadedDocs
        ];

        //this.contactDetailsFormData.adminContact = adminDetails;
        //this.contactDetailsFormData.techContact = technicalDetails;
        //this.contactDetailsFormData.billContact = billingDetails;
        //this.contactDetailsFormData.contactDocuments.applicationId = this.applicationId;
        //  this.contactDetailsFormData.contactDocuments.user = this.user;
        //this.contactDetailsFormData.contactDocuments.userMailId = this.userMailId;
        //
        // this.contactDetailsFormData.contactDocuments = {
        //   files: uploadedDoc.map(doc => doc.file),
        //   types: uploadedDoc.map(doc => doc.type),
        //   values: uploadedDoc.map(doc => doc.value),
        //   contactType: uploadedDoc.map(doc => doc.contactType),
        //   emailId: uploadedDoc.map(doc => doc.email),
        //   organisationId: uploadedDoc[0]?.organisationId, // Assuming all docs have same org ID
        //   applicationId: '', // Set appropriately from your component
        //   user: this.user,                   // Set appropriately
        //   userMailId: this.userMailId        // Set appropriately
        // };

        this.contactDetailsFormData = {
          spradmContact: adminDetails
        };
        //console.log('Contact Details Form Data:', this.contactDetailsFormData);
        if (this.fullForm.pending) {
          this.toastr.error('Please wait, validation in progress');
          return;
        }
        // this.fullForm.updateValueAndValidity();

        await lastValueFrom(this.superAdminContactService.saveSuperAdminContactDetailsForm(this.contactDetailsFormData, uploadedDoc, this.applicationId, this.user, this.userMailId)).then(
          response => {
            console.log('✅ API response:', response);
            let isContactDetailsSaved = false;
            if (response.status === HttpStatusCode.Ok) {
              isContactDetailsSaved = response.body?.success || false;
              this.toastr.success('Contact details saved successfully');
              this.updateUserOnboardingStep();
              // console.log('User onboarding step updated successfully.');
              setTimeout(() => {
                console.log('➡️ Emitting formSubmitted');
                this.formSubmitted.emit();
                this.router.navigateByUrl('/rgnt-dshd');
                // Emit form submitted event
              }, 0);
              this.isLoading = false; // Stop loading state
            }
            // this.isLoading = false;
          }, error => {
            if (error.status === HttpStatusCode.Unauthorized) {
              this.isLoading = false; // Stop loading state
              this.router.navigateByUrl("session-timeout");
              return;
            } else if (error.status === HttpStatusCode.ServiceUnavailable) {
              this.isLoading = false; // Stop loading state
              this.toastr.error('Network error, please contact registrar');
              return;
            } else {
              this.isLoading = false; // Stop loading state
              this.toastr.error("We couldn't process your request at this moment, please try after some time.");
              return;
            }
          });


        // If document upload fails, the entire process is stopped.
        // const uploadResponse = await lastValueFrom(
        //     this.contactDoc.uploadDocuments(
        //         uploadedDoc,
        //         this.applicationId, // Ensure applicationId is set correctly
        //         this.user,
        //         this.userMailId
        //     )
        // );


        // console.log('Documents uploaded successfully', uploadResponse);

        // 6. Update User Onboarding Step
        // THIS WILL ONLY RUN IF ALL THE ABOVE CONTACT AND DOCUMENT SAVES WERE SUCCESSFUL.

        // 7. Create Notification
        // THIS WILL ONLY RUN IF ALL PREVIOUS STEPS (including onboarding step) WERE SUCCESSFUL.
        const notification = {
          message: "Login details sent to billing and technical persons.",
          moduleType: "DocumentUpload",
          moduleRecordId: 102, // Ensure this ID is correct/dynamic if needed
          notificationTo: this.fullForm.get('admEmail')?.value,
          emailId: this.fullForm.get('admEmail')?.value,
          status: "Unread",
          createdDateTime: '',
          createdByEmailId: this.userMailId,
          profilepic: null
        };

        if (!notification.notificationTo || !notification.emailId) {
          //console.error('Error: Notification creation failed because the email is missing or invalid.');
          // Crucially, if the email is missing, we need to stop here too.
          // Throwing an error will jump to the catch block.
          throw new Error('Admin email for notification is missing or invalid.');
        }

        const notificationResponse = await lastValueFrom(
          this.notificationService.createNotification(notification)
        );
        // console.log('Notification created successfully:', notificationResponse);
        this.loadNotifications(); // Assuming this is a local method to refresh notifications


        // If execution reaches here, all steps completed successfully.
        // You can add final success messages, navigation, etc., here.

      } catch (error) {
        this.isLoading = false; // Stop loading state
        // This block will catch the FIRST error from ANY 'await' call above,
        // including the notification creation.

        if (error.status === HttpStatusCode.Unauthorized) {
          this.isLoading = false; // Stop loading state
          this.router.navigateByUrl("session-timeout");
        }
        else if (error.status === HttpStatusCode.ServiceUnavailable) {
          this.isLoading = false; // Stop loading state
          this.toastr.error("Network error please contact registrar");
        } else {
          this.isLoading = false;
          this.toastr.error("We couldn't process your request at this moment, please try after some time 1")
          //console.error('An error occurred during the submission process. Aborting subsequent steps:', error);
        }
        // You might want to display a user-friendly error message, e.g.:
        // this.toast.error('Failed to complete setup. Please try again.');

        // Importantly, no code after this 'catch' block (within submitAllDetails)
        // will execute if an error was caught. The function effectively stops here.
      }

    }

    else {
      this.contactSubmissionAttempted = true;
      //console.log('Form is invalid');
      this.fullForm.markAllAsTouched();
    }
  }

  onImageViewClick(imageUrl) {
    //console.log(imageUrl)
    this.pdfUrl = null
    this.imagUrl = imageUrl
  }
  onPdfViewClick(pdfUrl) {
    this.imagUrl = null
    this.pdfUrl = pdfUrl
  }
  alphabetValidator(control: any) {
    const value = control.value?.trim();
    if (!value || !/[a-zA-Z]/.test(value)) {
      return { alphabetRequired: true };
    }
    return null; // Valid input
  }

  allowAlphabetsOnly(event: any): void {
    let inputValue = event.target.value;

    // Remove characters that are not alphabets or spaces
    let validValue = inputValue.replace(/[^a-zA-Z\s]/g, '');

    // If the first character is a space, remove it (no leading spaces allowed)
    if (validValue.charAt(0) === ' ') {
      validValue = validValue.slice(1);
    }

    // If a space is entered at the end without any alphabet after it, remove it
    if (validValue.charAt(validValue.length - 1) === ' ' && validValue.length > 1 && !/[a-zA-Z]/.test(validValue.charAt(validValue.length - 2))) {
      validValue = validValue.slice(0, -1);
    }

    // Replace multiple spaces with a single space
    validValue = validValue.replace(/\s+/g, ' ');

    // Update the input field with the valid value
    event.target.value = validValue;
  }
  isSuperAdminFormValid(): boolean {

    const isValid =
      this.fullForm.get('admPanNumber')?.valid &&
      this.fullForm.get('admDob')?.valid &&
      this.fullForm.get('admFullName')?.valid &&
      this.fullForm.get('admEmail')?.valid &&
      this.fullForm.get('admDesignation')?.valid &&
      this.fullForm.get('admCountryCode')?.valid &&
      this.fullForm.get('admPhone')?.valid &&
      this.fullForm.get('admAltCountryCode')?.valid &&
      this.fullForm.get('admAltPhone')?.valid &&
      this.fullForm.get('admAddress')?.valid &&
      this.adminUploadedDocs?.length >= 2
    // this.panStatus &&
    // this.panStatus.toLowerCase() === 'valid';

    console.log('FINAL VALIDATION => ', isValid);

    console.log({
      pan: this.fullForm.get('admPanNumber')?.status,
      dob: this.fullForm.get('admDob')?.status,
      fullName: this.fullForm.get('admFullName')?.status,
      email: this.fullForm.get('admEmail')?.status,
      designation: this.fullForm.get('admDesignation')?.status,
      countryCode: this.fullForm.get('admCountryCode')?.status,
      phone: this.fullForm.get('admPhone')?.status,
      altCountryCode: this.fullForm.get('admAltCountryCode')?.status,
      altPhone: this.fullForm.get('admAltPhone')?.status,
      address: this.fullForm.get('admAddress')?.status,
      docs: this.adminUploadedDocs?.length,
      panStatus: this.panStatus
    });

    return !!isValid;
  }

  adminPanVerified = false;
  // techPanVerified = false;
  // billPanVerified = false;

  panStatus: 'valid' | 'invalid' | 'mismatch' | 'error' | '' = '';
  PANDetails: any = null;


  verifyPANForAdmin() {
    this.isLoading = true;   // ✅ START loader

    const panCtrl = this.fullForm.get('admPanNumber');
    const nameCtrl = this.fullForm.get('admFullName');
    const dobCtrl = this.fullForm.get('admDob');

    panCtrl?.markAsTouched();
    nameCtrl?.markAsTouched();
    dobCtrl?.markAsTouched();

    if (panCtrl?.invalid || nameCtrl?.invalid || dobCtrl?.invalid) {
      this.toastr.error(
        'Please enter PAN, Name and Date of Birth',
        'PAN Verification Failed'
      );

      this.isLoading = false;   // ✅ STOP loader
      return;
    }

    const pan = panCtrl?.value?.trim();
    const name = nameCtrl?.value?.trim();
    const dob = dobCtrl?.value;

    // const formattedDob = dob
    //   ? new Date(dob).toLocaleDateString('en-GB')
    //   : '';

    const formattedDob = dob
      ? dob.split('-').reverse().join('/')
      : '';

    this.panStatus = '';
    this.PANDetails = null;

    this.panService.verifyPAN(pan, name, formattedDob).subscribe({
      next: (response) => {
        console.log('PAN API RESPONSE:', response);

        this.PANDetails = response;

        if (response.valid === true) {
          this.panStatus = 'valid';
          this.adminPanVerified = true;
          this.cdr.detectChanges();

          this.toastr.success(
            response.validationMessage || 'PAN verified successfully'
          );

          this.panService.setPanData(response);
        }
        else if (response.nameMatch === 'NO') {
          this.panStatus = 'mismatch';
          this.toastr.error('Name does not match PAN records');
          this.panService.setPanData(null);
        }
        else if (response.dobMatch === 'NO') {
          this.panStatus = 'mismatch';
          this.toastr.error('Date of Birth does not match PAN records');
          this.panService.setPanData(null);
        }
        else {
          this.panStatus = 'invalid';
          this.toastr.error(
            response.validationMessage || 'PAN is invalid or inactive'
          );
          this.panService.setPanData(null);
        }

        this.cdr.detectChanges();
        this.isLoading = false;   // ✅ STOP loader
      },

      error: (err) => {
        console.error('PAN API ERROR:', err);
        this.panStatus = 'error';

        this.toastr.error(
          'PAN verification service is unavailable',
          'Network Error'
        );

        this.panService.setPanData(null);
        this.cdr.detectChanges();

        this.isLoading = false;   // ✅ STOP loader
      }
    });
  }

  //   verifyPANForTech() {
  //   this.isLoading = true;   // ✅ START loader

  //   const panCtrl = this.fullForm.get('techPanNumber');
  //   const dobCtrl = this.fullForm.get('techDob');
  //   const nameCtrl = this.fullForm.get('techFullName');

  //   panCtrl?.markAsTouched();
  //   nameCtrl?.markAsTouched();
  //   dobCtrl?.markAsTouched();

  //   if (panCtrl?.invalid || nameCtrl?.invalid || dobCtrl?.invalid) {
  //     this.toastr.error(
  //       'Please enter PAN, Name and Date of Birth',
  //       'PAN Verification Failed'
  //     );

  //     this.isLoading = false;   // ✅ STOP loader
  //     return;
  //   }

  //   const pan = panCtrl?.value?.trim();
  //   const name = nameCtrl?.value?.trim();
  //   const dob = dobCtrl?.value;

  //  const formattedDob = dob
  //   ? dob.split('-').reverse().join('/')
  //   : '';

  //   this.panStatus = '';
  //   this.PANDetails = null;

  //   this.panService.verifyPAN(pan, name, formattedDob).subscribe({
  //     next: (response) => {
  //       console.log('PAN API RESPONSE:', response);

  //       this.PANDetails = response;

  //       if (response.valid === true) {
  //         this.panStatus = 'valid';
  //         this.techPanVerified = true;

  //         this.toastr.success(
  //           response.validationMessage || 'PAN verified successfully'
  //         );

  //         this.panService.setPanData(response);
  //       }
  //       else if (response.nameMatch === 'NO') {
  //         this.panStatus = 'mismatch';
  //         this.toastr.error('Name does not match PAN records');
  //         this.panService.setPanData(null);
  //       }
  //       else if (response.dobMatch === 'NO') {
  //         this.panStatus = 'mismatch';
  //         this.toastr.error('Date of Birth does not match PAN records');
  //         this.panService.setPanData(null);
  //       }
  //       else {
  //         this.panStatus = 'invalid';
  //         this.toastr.error(
  //           response.validationMessage || 'PAN is invalid or inactive'
  //         );
  //         this.panService.setPanData(null);
  //       }

  //       this.cdr.detectChanges();
  //       this.isLoading = false;   // ✅ STOP loader
  //     },

  //     error: (err) => {
  //       console.error('PAN API ERROR:', err);
  //       this.panStatus = 'error';

  //       this.toastr.error(
  //         'PAN verification service is unavailable',
  //         'Network Error'
  //       );

  //       this.panService.setPanData(null);
  //       this.cdr.detectChanges();

  //       this.isLoading = false;   // ✅ STOP loader
  //     }
  //   });
  // }

  //   verifyPANForBill() {
  //   this.isLoading = true;   // ✅ START loader

  //   const panCtrl = this.fullForm.get('billingPanNumber');
  //   const dobCtrl = this.fullForm.get('billingDob');
  //   const nameCtrl = this.fullForm.get('billFullName');

  //   panCtrl?.markAsTouched();
  //   nameCtrl?.markAsTouched();
  //   dobCtrl?.markAsTouched();

  //   if (panCtrl?.invalid || nameCtrl?.invalid || dobCtrl?.invalid) {
  //     this.toastr.error(
  //       'Please enter PAN, Name and Date of Birth',
  //       'PAN Verification Failed'
  //     );

  //     this.isLoading = false;   // ✅ STOP loader
  //     return;
  //   }

  //   const pan = panCtrl?.value?.trim();
  //   const name = nameCtrl?.value?.trim();
  //   const dob = dobCtrl?.value;

  // const formattedDob = dob
  //   ? dob.split('-').reverse().join('/')
  //   : '';

  //   this.panStatus = '';
  //   this.PANDetails = null;

  //   this.panService.verifyPAN(pan, name, formattedDob).subscribe({
  //     next: (response) => {
  //       console.log('PAN API RESPONSE:', response);

  //       this.PANDetails = response;

  //       if (response.valid === true) {
  //         this.panStatus = 'valid';
  //         this.billPanVerified = true;

  //         this.toastr.success(
  //           response.validationMessage || 'PAN verified successfully'
  //         );

  //         this.panService.setPanData(response);
  //       }
  //       else if (response.nameMatch === 'NO') {
  //         this.panStatus = 'mismatch';
  //         this.toastr.error('Name does not match PAN records');
  //         this.panService.setPanData(null);
  //       }
  //       else if (response.dobMatch === 'NO') {
  //         this.panStatus = 'mismatch';
  //         this.toastr.error('Date of Birth does not match PAN records');
  //         this.panService.setPanData(null);
  //       }
  //       else {
  //         this.panStatus = 'invalid';
  //         this.toastr.error(
  //           response.validationMessage || 'PAN is invalid or inactive'
  //         );
  //         this.panService.setPanData(null);
  //       }

  //       this.cdr.detectChanges();
  //       this.isLoading = false;   // ✅ STOP loader
  //     },

  //     error: (err) => {
  //       console.error('PAN API ERROR:', err);
  //       this.panStatus = 'error';

  //       this.toastr.error(
  //         'PAN verification service is unavailable',
  //         'Network Error'
  //       );

  //       this.panService.setPanData(null);
  //       this.cdr.detectChanges();

  //       this.isLoading = false;   // ✅ STOP loader
  //     }
  //   });
  // }


  uniqueEmailValidator(): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      const superAdminEmail = localStorage.getItem('email');
      const admEmail = control.get('admEmail')?.value?.toLowerCase();
      const techEmail = control.get('techEmail')?.value?.toLowerCase();
      const billEmail = control.get('billEmail')?.value?.toLowerCase();

      const emailCounts: Record<string, number> = {};
      const emails = [superAdminEmail, admEmail];

      // Count occurrences of each email
      emails.forEach(email => {
        if (email) {
          emailCounts[email] = (emailCounts[email] || 0) + 1;
        }
      });

      const errors: ValidationErrors = {};

      // Validate each email field (except empty values)
      if (admEmail && emailCounts[admEmail] > 2) {
        errors['emailNotUniqueAdmin'] = 'An email can only be used twice.';
      }
      if (techEmail && emailCounts[techEmail] > 2) {
        errors['emailNotUniqueTech'] = 'An email can only be used twice.';
      }
      if (billEmail && emailCounts[billEmail] > 2) {
        errors['emailNotUniqueBill'] = 'An email can only be used twice.';
      }
      if (superAdminEmail && emailCounts[superAdminEmail] > 2) {
        errors['emailNotUniqueSuperAdmin'] = 'An email can only be used twice.';
      }

      return Object.keys(errors).length ? errors : null;
    };
  }
  emailNotExistsInDbValidator(emailService: ContactDetailsFormService, orgId): AsyncValidatorFn {
    return (control: AbstractControl): Observable<ValidationErrors | null> => {
      const email = control.value.toLowerCase();

      if (!email) {
        return of(null); // Skip validation for empty field
      }
      // console.log(this.choosenContactType,this.listOfEmailsAndRoleMap)
      // console.log(this.organisationId)
      if (this.listOfEmailsAndRoleMap?.get(email)) {
        //console.log(this.listOfEmailsAndRoleMap.get(email).length)
        if (this.listOfEmailsAndRoleMap.get(email).length == 1) {
          //console.log("entered")
          if (this.listOfEmailsAndRoleMap.get(email).includes(this.choosenContactType)) {

          } else {
            return of(null);
          }

        }
      }
      return emailService.isEmailAvailableToUse(email, this.organisationId).pipe(
        map((res: HttpResponse<boolean>) => {
          const isAvailable = res.body;
          //console.log(`Email availability for "${email}":`, isAvailable);
          return isAvailable ? null : { emailAlreadyExists: true };
        }),
        catchError((error) => {
          //console.error(`Error checking email "${email}":`, error);
          return of({ emailCheckFailed: true });
        })
      );
    };
  }



  customEmailValidator(): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      const value = control.value;
      if (!value) return null;  // Don't validate empty fields

      // Regular expression to check email format
      const emailRegex = new RegExp(this.regExp.trim());

      // If the value does not match the pattern, return an error
      if (!emailRegex.test(value)) {
        return { invalidEmail: 'Please enter a valid email address (e.g., example@gmail.com).' };
      }
      return null;  // Valid email format
    };
  }

  regExp: string = '';
  getRegularExpressionForEmail() {
    // Assuming 'this.assetService' is where getEmailReqExp is defined
    this.registrationService.getEmailReqExp('email').subscribe({
      next: (response: string) => { // 👈 Make sure to expect a string here
        // 'response' is ALREADY the extracted 'value' string from the map operator.
        const respo = response[0] as any;
        this.regExp = respo.value.trim(); // Trim any whitespace
        //console.log('Email regex fetched and assigned:', this.regExp);
      },
      error: (error) => {
        //console.error('Error fetching email regex:', error);
        // Handle the error, e.g., set a default value or clear regExp
        this.regExp = ''; // Or null, depending on your default state
      }
    });
  }

  // countryCodes = [
  //   { name: 'India', code: '91' },
  //   { name: 'United States', code: '1' },
  //   { name: 'United Kingdom', code: '44' },
  //   { name: 'Canada', code: '1' },
  //   { name: 'Australia', code: '61' },
  //   // Add more countries as needed
  // ];
  selectedCountryCode: string = '+91'; // Default country code
  countryCode: string = '+91'; // Default value for the country code to show in the input
  phoneNumber: string = ''; // Store the phone number without the country code

  selectedAdminCountryCode: string = '';  // For billPhone
  selectedAdminAltCountryCode: string = '';
  // updateAdminCountryCode(event) {
  //   // this.selectedAdminCountryCode = `${event.target.value}`;
  //   // if (this.selectedAdminCountryCode) {
  //   //   this.fullForm.patchValue({ admCountryCode: this.selectedAdminCountryCode });
  //   //   this.fullForm.controls['admPhone'].enable();
  //   // }
  //   // else {
  //   //   this.fullForm.controls['admPhone'].disable();
  //   // }

  //  this.selectedAdminCountryCode = `${event.target.value}`;

  // if (this.selectedAdminCountryCode) {
  //   this.fullForm.patchValue({ admCountryCode: this.selectedAdminCountryCode });
  //   this.fullForm.controls['admPhone'].enable();

  //   // Disable Individual Mobile
  //   this.fullForm.get('admAltPhone')?.disable();
  // } else {
  //   this.fullForm.controls['admPhone'].disable();

  //   // Enable Individual Mobile
  //   this.fullForm.get('admAltPhone')?.enable();
  // }
  // }
  updateAdminCountryCode(event) {
    this.selectedAdminCountryCode = `${event.target.value}`;

    this.fullForm.patchValue({
      admCountryCode: this.selectedAdminCountryCode
    });

    if (this.selectedAdminCountryCode) {
      this.fullForm.get('admPhone')?.enable({ emitEvent: false });
    }
  }

  // Update country code for billAltPhone
  updateAdminAltCountryCode(event) {
    this.selectedAdminAltCountryCode = `${event.target.value}`;
    if (this.selectedAdminAltCountryCode) {
      this.fullForm.patchValue({ admAltCountryCode: this.selectedAdminAltCountryCode });
      this.fullForm.controls['admAltPhone'].enable();
    }
    else {
      this.fullForm.controls['admAltPhone'].disable();
    }
    this.validateAltAdminCountryCode();
  }
  adminCountryCodeMobileCombinationError = ""
  // async validateAltAdminCountryCode() {
  //   const admAltPhone = this.fullForm.get('admAltPhone')?.value;
  //   const admAltCountryCode = this.fullForm.get('admAltCountryCode')?.value;

  //   // If mobile number is empty, clear any existing errors
  //   if (!admAltPhone) {
  //     this.adminCountryCodeMobileCombinationError = "";
  //     return;
  //   }

  //   // Check if the mobile number starts with 0-5 for India
  //   if (admAltCountryCode === '+91' && /^[0-5]/.test(admAltPhone)) {
  //     this.adminCountryCodeMobileCombinationError = "India phone numbers cannot start with 0-5.";
  //     return;
  //   }

  //   // Check length of the mobile number and validate
  //   if (admAltPhone.length > 7) {
  //     if (admAltCountryCode && admAltPhone) {
  //       try {
  //         const validMobileFormat = await lastValueFrom(
  //           this.organisationDetailsService.validateCodeAndNumber(
  //             admAltCountryCode,
  //             admAltPhone
  //           )
  //         );
  //         //console.log(validMobileFormat);

  //         if (!validMobileFormat) {
  //           this.adminCountryCodeMobileCombinationError = "Please enter a valid Country code or mobile number.";
  //         } else {
  //           this.adminCountryCodeMobileCombinationError = ""; // Clear the error if valid
  //         }
  //       } catch (error) {
  //         //console.error("Validation error:", error);
  //         this.adminCountryCodeMobileCombinationError = "Please enter a valid country code (1-4 digits) or mobile number (10 digits for India, 8-15 digits for other countries).";
  //       }
  //     }
  //   }
  // }
  validateAltAdminCountryCode() {
    const countryCode = this.fullForm.get('admAltCountryCode')?.value;
    const phone = this.fullForm.get('admAltPhone')?.value;

    // remove '+' if exists
    const cc = countryCode ? countryCode.toString().replace('+', '') : '';

    if (cc === '91') {
      if (phone && phone.length !== 10) {
        this.adminCountryCodeMobileCombinationError =
          'For India, mobile number must be exactly 10 digits';
      } else {
        this.adminCountryCodeMobileCombinationError = '';
      }
    } else {
      if (phone && (phone.length < 8 || phone.length > 15)) {
        this.adminCountryCodeMobileCombinationError =
          'Mobile number must be between 8 to 15 digits';
      } else {
        this.adminCountryCodeMobileCombinationError = '';
      }
    }
  }
  adminStdCodeMobileCombinationError = ''
  async validateAdminStdCode() {
    if (this.fullForm.get('admPhone')?.value == null || this.fullForm.get('admPhone')?.value == '') {
      this.adminStdCodeMobileCombinationError = ""
      return
    }
    if (this.fullForm.get('admPhone')?.value.length > 4) {
      if (this.fullForm.get('admCountryCode')?.value && this.fullForm.get('admPhone')?.value) {
        try {
          const validMobileFormat = await lastValueFrom(
            this.organisationDetailsService.validatestdCodeAndNumber(
              this.fullForm.get('admCountryCode')?.value,
              this.fullForm.get('admPhone')?.value
            )
          );
          //console.log(validMobileFormat)
          if (!validMobileFormat) { // Check for false, not truthy
            this.adminStdCodeMobileCombinationError = "Please enter a valid STD code or number.";
          } else {
            this.adminStdCodeMobileCombinationError = ""; // Clear the error if valid
          }
        } catch (error) {
          //console.error("Validation error:", error);
          this.adminStdCodeMobileCombinationError = "Validation failed. Please try again.";
        }
      }
    }
  }
  techCountryCodeMobileCombinationError = ""
  // validateAltTechCountryCode() {
  //   const countryCode = this.fullForm.get('techAltCountryCode')?.value;
  //   const phone = this.fullForm.get('techAltPhone')?.value;

  //   const cc = countryCode ? countryCode.toString().replace('+', '') : '';

  //   if (cc === '91') {
  //     if (phone && phone.length !== 10) {
  //       this.techCountryCodeMobileCombinationError =
  //         'For India, mobile number must be exactly 10 digits';
  //     } else {
  //       this.techCountryCodeMobileCombinationError = '';
  //     }
  //   } else {
  //     if (phone && (phone.length < 8 || phone.length > 15)) {
  //       this.techCountryCodeMobileCombinationError =
  //         'Mobile number must be between 8 to 15 digits';
  //     } else {
  //       this.techCountryCodeMobileCombinationError = '';
  //     }
  //   }
  // }
  techStdCodeMobileCombinationError = ''
  // async validateTechStdCode() {
  //   if (this.fullForm.get('techPhone')?.value == null || this.fullForm.get('techPhone')?.value == '') {
  //     this.techStdCodeMobileCombinationError = ""
  //     return
  //   }
  //   if (this.fullForm.get('techPhone')?.value.length > 4) {
  //     if (this.fullForm.get('techCountryCode')?.value && this.fullForm.get('techPhone')?.value) {
  //       try {
  //         const validMobileFormat = await lastValueFrom(
  //           this.organisationDetailsService.validatestdCodeAndNumber(
  //             this.fullForm.get('techCountryCode')?.value,
  //             this.fullForm.get('techPhone')?.value
  //           )
  //         );
  //         //console.log(validMobileFormat)
  //         if (!validMobileFormat) { // Check for false, not truthy
  //           this.techStdCodeMobileCombinationError = "Please enter a valid STD code or number.";
  //         } else {
  //           this.techStdCodeMobileCombinationError = ""; // Clear the error if valid
  //         }
  //       } catch (error) {
  //         //console.error("Validation error:", error);
  //         this.techStdCodeMobileCombinationError = "Validation failed. Please try again.";
  //       }
  //     }
  //   }
  // }
  billCountryCodeMobileCombinationError = ""
  // validateAltBillCountryCode() {
  //   const countryCode = this.fullForm.get('billAltCountryCode')?.value;
  //   const phone = this.fullForm.get('billAltPhone')?.value;

  //   const cc = countryCode ? countryCode.toString().replace('+', '') : '';

  //   if (cc === '91') {
  //     if (phone && phone.length !== 10) {
  //       this.billCountryCodeMobileCombinationError =
  //         'For India, mobile number must be exactly 10 digits';
  //     } else {
  //       this.billCountryCodeMobileCombinationError = '';
  //     }
  //   } else {
  //     if (phone && (phone.length < 8 || phone.length > 15)) {
  //       this.billCountryCodeMobileCombinationError =
  //         'Mobile number must be between 8 to 15 digits';
  //     } else {
  //       this.billCountryCodeMobileCombinationError = '';
  //     }
  //   }
  // }
  billStdCodeMobileCombinationError = ''
  // async validateBillStdCode() {
  //   if (this.fullForm.get('billPhone')?.value == null || this.fullForm.get('billPhone')?.value == '') {
  //     this.billStdCodeMobileCombinationError = ""
  //     return
  //   }
  //   if (this.fullForm.get('billPhone')?.value.length > 4) {
  //     if (this.fullForm.get('billCountryCode')?.value && this.fullForm.get('billPhone')?.value) {
  //       try {
  //         const validMobileFormat = await lastValueFrom(
  //           this.organisationDetailsService.validatestdCodeAndNumber(
  //             this.fullForm.get('billCountryCode')?.value,
  //             this.fullForm.get('billPhone')?.value
  //           )
  //         );
  //         //console.log(validMobileFormat)
  //         if (!validMobileFormat) { // Check for false, not truthy
  //           this.billStdCodeMobileCombinationError = "Please enter a valid STD code or number.";
  //         } else {
  //           this.billStdCodeMobileCombinationError = ""; // Clear the error if valid
  //         }
  //       } catch (error) {
  //         //console.error("Validation error:", error);
  //         this.billStdCodeMobileCombinationError = "Validation failed. Please try again.";
  //       }
  //     }
  //   }
  // }

  @ViewChild('countryCodeInput') countryCodeInput!: ElementRef;

  @ViewChild('adminAltCode') adminAltCode!: ElementRef;
  @ViewChild('techCountryCode') techCountryCode!: ElementRef;
  @ViewChild('techAltContryCode') techAltContryCode!: ElementRef;
  @ViewChild('billCountryCode') billCountryCode!: ElementRef;
  @ViewChild('billAltCountryCode') billAltCountryCode!: ElementRef;

  adminCC: string = "adminCC"
  adminAltCC: string = "adminAltCC"
  techCC: string = "techCC"
  techAltCC: string = "techAltCC"
  billCC: string = "billCC"
  billAltCC: string = "billAltCC"
  adjustCountryCodeWidth(element) {
    // const handleMobileNumberField = (countryCodeControlName: string, mobileNumberControlName: string) => {
    //   const countryCode = this.fullForm.get(countryCodeControlName)?.value;

    //   // If country code has a value, enable the mobile number input
    //   const mobileNumberControl = this.fullForm.get(mobileNumberControlName);
    //   if (countryCode && countryCode.trim().length > 0) {
    //     mobileNumberControl?.enable();  // Enable the mobile number field
    //     mobileNumberControl?.updateValueAndValidity(); // Trigger validation
    //   } else {
    //     mobileNumberControl?.disable(); // Disable the mobile number field if country code is not entered
    //     //  mobileNumberControl?.setValue(''); // Clear mobile number value when disabled
    //   }
    //   if (element == this.techCC) {
    //     this.validateTechStdCode();
    //   } else if (element == this.adminCC) {
    //     this.validateAdminStdCode();
    //   } else if (element == this.billCC) {
    //     this.validateBillStdCode();
    //   }
    // };

    const handleMobileNumberField = (countryCodeControlName: string, mobileNumberControlName: string) => {
      const countryCode = this.fullForm.get(countryCodeControlName)?.value;

      const mobileNumberControl = this.fullForm.get(mobileNumberControlName);

      if (countryCode && countryCode.trim().length > 0) {
        mobileNumberControl?.enable();
        mobileNumberControl?.updateValueAndValidity();

        // 🔴 NEW LOGIC: Disable Individual Mobile when STD code entered
        if (countryCodeControlName === 'admCountryCode') {
          this.fullForm.get('admAltPhone')?.disable();
        }

        if (countryCodeControlName === 'techCountryCode') {
          this.fullForm.get('techAltPhone')?.disable();
        }

        if (countryCodeControlName === 'billCountryCode') {
          this.fullForm.get('billAltPhone')?.disable();
        }

      } else {
        mobileNumberControl?.disable();

        // 🔴 NEW LOGIC: Enable Individual Mobile when STD code removed
        if (countryCodeControlName === 'admCountryCode') {
          this.fullForm.get('admAltPhone')?.enable();
        }

        if (countryCodeControlName === 'techCountryCode') {
          this.fullForm.get('techAltPhone')?.enable();
        }

        if (countryCodeControlName === 'billCountryCode') {
          this.fullForm.get('billAltPhone')?.enable();
        }
      }
    };

    // Handle the main admin phone number
    // handleMobileNumberField('admCountryCode', 'admPhone');

    // // Handle the alternate admin phone number
    // handleMobileNumberField('admAltCountryCode', 'admAltPhone');
    // handleMobileNumberField('techCountryCode', 'techPhone');
    // handleMobileNumberField('techAltCountryCode', 'techAltPhone');
    // handleMobileNumberField('billCountryCode', 'billPhone');
    // handleMobileNumberField('billAltCountryCode', 'billAltPhone');


    if (this.fullForm.get('admCountryCode')?.value) {
      this.fullForm.get('admAltPhone')?.disable();
    } else {
      this.fullForm.get('admAltPhone')?.enable();
    }

    if (this.fullForm.get('techCountryCode')?.value) {
      this.fullForm.get('techAltPhone')?.disable();
    } else {
      this.fullForm.get('techAltPhone')?.enable();
    }

    if (this.fullForm.get('billCountryCode')?.value) {
      this.fullForm.get('billAltPhone')?.disable();
    } else {
      this.fullForm.get('billAltPhone')?.enable();
    }
    let countryCodeInput;
    if (element == this.adminCC) {
      countryCodeInput = this.countryCodeInput.nativeElement;
    } else if (element == this.adminAltCC) {
      countryCodeInput = this.adminAltCode.nativeElement;
    } else if (element == this.techCC) {
      countryCodeInput = this.techCountryCode.nativeElement;
    } else if (element == this.techAltCC) {
      countryCodeInput = this.techAltContryCode.nativeElement;
    } else if (element == this.billCC) {
      countryCodeInput = this.billCountryCode.nativeElement;
    } else if (element == this.billAltCC) {
      countryCodeInput = this.billAltCountryCode.nativeElement;
    }

    if (countryCodeInput) {
      let inputValue = countryCodeInput.value;

      // Allow only numbers, + (only at the start), and -
      inputValue = inputValue.replace(/[^0-9]/g, '');



      // Limit total length to 5 characters
      inputValue = inputValue.substring(0, 5);


      countryCodeInput.value = inputValue; // Update input field

      const inputLength = inputValue.length > 0
        ? inputValue.length
        : countryCodeInput.placeholder.length;

      countryCodeInput.style.width = `${(inputLength * 12) + (inputValue.length ? 20 : 0)}px`; // Adjust width dynamically
    }
  }


  selectedTechCountryCode: string = '';  // For billPhone
  selectedTechAltCountryCode: string = '';
  updateTechCountryCode(event) {
    // this.selectedTechCountryCode = `${event.target.value}`;
    // if (this.selectedTechCountryCode) {
    //   this.fullForm.patchValue({ techCountryCode: this.selectedTechCountryCode });
    //   this.fullForm.controls['techPhone'].enable();
    // } else {
    //   this.fullForm.controls['techPhone'].disable();
    // }
    if (this.selectedTechCountryCode) {
      this.fullForm.patchValue({ techCountryCode: this.selectedTechCountryCode });
      this.fullForm.controls['techPhone'].enable();

      this.fullForm.get('techAltPhone')?.disable();
    } else {
      this.fullForm.controls['techPhone'].disable();

      this.fullForm.get('techAltPhone')?.enable();
    }
  }

  // Update country code for billAltPhone
  updateTechAltCountryCode(event) {
    this.selectedTechAltCountryCode = `${event.target.value}`;
    if (this.selectedTechAltCountryCode) {
      this.fullForm.patchValue({ techAltCountryCode: this.selectedTechAltCountryCode });
      this.fullForm.controls['techAltPhone'].enable();
    } else {
      this.fullForm.controls['techAltPhone'].disable();
    }
    // this.validateAltTechCountryCode();
  }

  selectedBillCountryCode: string = '';  // For billPhone
  selectedBillAltCountryCode: string = '';
  updateBillCountryCode(event) {
    // this.selectedBillCountryCode = `${event.target.value}`;
    // if (this.selectedBillCountryCode) {
    //   this.fullForm.patchValue({ billCountryCode: this.selectedBillCountryCode });
    //   this.fullForm.controls['billPhone'].enable();
    // }
    // else {
    //   this.fullForm.controls['billPhone'].disable();
    // }

    if (this.selectedBillCountryCode) {
      this.fullForm.patchValue({ billCountryCode: this.selectedBillCountryCode });
      this.fullForm.controls['billPhone'].enable();

      this.fullForm.get('billAltPhone')?.disable();
    }
    else {
      this.fullForm.controls['billPhone'].disable();

      this.fullForm.get('billAltPhone')?.enable();
    }
  }

  // Update country code for billAltPhone
  updateBillAltCountryCode(event) {
    this.selectedBillAltCountryCode = `${event.target.value}`;
    if (this.selectedBillAltCountryCode) {
      this.fullForm.patchValue({ billAltCountryCode: this.selectedBillAltCountryCode });
      this.fullForm.controls['billAltPhone'].enable();
    } else {
      this.fullForm.controls['billAltPhone'].disable();
    }
    // this.validateAltBillCountryCode();
  }

  loggedInUser: any = null;
  onBoardingStatus: boolean = false;
  async getLoggedInUserDetails() {
    await lastValueFrom(this.userService.getUserByEmailId(this.userMailId)).then(
      response => {
        if (response.status === HttpStatusCode.Ok) {
          this.loggedInUser = response.body
          this.onBoardingStatus = this.loggedInUser.isOnboardingCompleted;
          this.organisationId = this.loggedInUser.organisationId;
        }
      }, error => {
        if (error.status === HttpStatusCode.Unauthorized) {
          this.router.navigate(['/session-timeout']);
        }
      }
    )
  }

  async updateUserOnboardingStep() {
    //console.log('user: '+this.loggedInUser)
    this.loggedInUser.onboardingStepIndex = 2;
    //console.log(this.loggedInUser.onboardingStepIndex);
    await lastValueFrom(this.userService.updateUser(this.loggedInUser)).then(
      response => {
        if (response.status === HttpStatusCode.Ok) {
          //console.log('User updated successfully'+response.body);
        }
      }, error => {
        //console.error('Error occurred while updating user', error);
      });
  }
  preventConsecutiveSpaces(event: KeyboardEvent): void {
    const inputElement = event.target as HTMLInputElement;

    // Prevent leading spaces
    if (event.key === ' ' && inputElement.value === '') {
      event.preventDefault(); // Block the space if it's the first character
    }

    // Prevent consecutive spaces
    if (event.key === ' ' && inputElement.value[inputElement.value.length - 1] === ' ') {
      event.preventDefault(); // Block the space if the last character is already a space
    }
  }
  restrictNonDigits(event: KeyboardEvent): void {
    const key = event.key;

    // Check if the key is not a digit or backspace, and prevent it
    if (!/[\d]/.test(key) && key !== "Backspace" && key !== "Tab") {
      event.preventDefault(); // Prevent non-digit characters
    }
  }
  noSpecialCharAtStart(control: any) {
    const value = control.value || '';
    // If the value starts with a special character, return an error
    if (/^[^a-zA-Z0-9]/.test(value)) {
      return { startWithSpecialChar: true };
    }
    return null; // No error
  }
  // sendErrorOfFinDocUploadToOnBoardingStepper(finDocError) {
  //   this.finDocError.emit(finDocError)
  // }
  // sendErrorOfTechDocUploadToOnBoardingStepper(techDocError) {
  //   this.techDocError.emit(techDocError)
  // }
  sendErrorOfAdminDocUploadToOnBoardingStepper(adminDocError) {
    this.adminDocError.emit(adminDocError)
  }
  docNameForContact: string = '';
  setDocNameToVieDocumentModal(docName) {
    this.docNameForContact = docName
  }

  // Inside your component class
  checkAdminSectionValidity(): boolean {
    const adminControls = [
      this.fullForm.get('admFullName'),
      this.fullForm.get('admDob'),
      this.fullForm.get('admPanNumber'),
      this.fullForm.get('admEmail'),
      this.fullForm.get('admPhone'),
      this.fullForm.get('admCountryCode'),
      this.fullForm.get('admAltCountryCode'),
      this.fullForm.get('admAltPhone'),
      this.fullForm.get('admDesignation'),
      this.fullForm.get('admAddress'),
    ];
    let adminSectionValid = true
    //console.log(this.fullForm.get('admEmail')?.errors?.['emailAlreadyExists'] )
    if (this.fullForm.get('admEmail')?.errors?.['emailAlreadyExists'] == true) {
      adminSectionValid = false;
    }
    if (adminSectionValid == true) {
      adminControls.forEach(control => {
        // We explicitly mark as touched/dirty and update validity to ensure errors are shown
        if (control) {
          control.markAsTouched();
          control.markAsDirty();
          control.updateValueAndValidity(); // Recalculate validation status
          if (control.invalid) {
            adminSectionValid = false;
          }
        }
      });
    }

    if (this.adminUploadedDocs.length <= 2 || this.fullForm.get('admEmail')?.errors?.['emailAlreadyExists'] && this.fullForm.get('admEmail')?.touched) {
      adminSectionValid = false;
    }

    return adminSectionValid;
  }

  // Method to check Technical section validity
  checkTechSectionValidity(): boolean {
    const techControls = [
      this.fullForm.get('techPanNumber'),
      this.fullForm.get('techDob'),
      this.fullForm.get('techFullName'),
      this.fullForm.get('techEmail'),
      this.fullForm.get('techCountryCode'),
      this.fullForm.get('techAltCountryCode'),
      this.fullForm.get('techPhone'),
      this.fullForm.get('techAltPhone'),
      this.fullForm.get('techDesignation'),
      this.fullForm.get('techAddress'),
    ];

    let techSectionValid = true;
    if (this.fullForm.get('techEmail')?.errors?.['emailAlreadyExists'] == true) {
      techSectionValid = false;
    }
    if (techSectionValid == true) {
      techControls.forEach(control => {
        if (control) {
          control.markAsTouched();
          control.markAsDirty();
          control.updateValueAndValidity();
          if (control.invalid) {
            techSectionValid = false;
          }
        }
      });
    }

    // if (this.techUploadedDocs.length <= 2) {
    //   techSectionValid = false;
    // }
    return techSectionValid;
  }

  // Method to check Billing section validity
  checkBillSectionValidity(): boolean {
    const billControls = [
      this.fullForm.get('billingPanNumber'),
      this.fullForm.get('billingDob'),
      this.fullForm.get('billFullName'),
      this.fullForm.get('billEmail'),
      this.fullForm.get('billCountryCode'),
      this.fullForm.get('billAltCountryCode'),
      this.fullForm.get('billPhone'),
      this.fullForm.get('billAltPhone'),
      this.fullForm.get('billDesignation'),
      this.fullForm.get('billAddress'),
    ];

    let billSectionValid = true;

    if (this.fullForm.get('billEmail')?.errors?.['emailAlreadyExists'] == true) {
      billSectionValid = false;
    }
    if (billSectionValid == true) {
      billControls.forEach(control => {
        if (control) {
          control.markAsTouched();
          control.markAsDirty();
          control.updateValueAndValidity();
          if (control.invalid) {
            billSectionValid = false;
          }
        }
      });
    }

    // if (this.billingUploadedDocs.length <= 2) {
    //   billSectionValid = false;
    // }

    return billSectionValid;
  }

  //   onButtonClickOfSubmit(): void {
  //     // These conditions mirror the button's [disabled] attribute.
  //     // We only trigger the debounce if the button is conceptually "enabled".
  //     // if (!this.adminPanVerified || !this.techPanVerified || !this.billPanVerified) {
  //     //   this.toastr.error(
  //     //     'Please verify PAN before proceeding',
  //     //     'PAN Not Verified'
  //     //   );
  //     //   return;
  //     // }
  //     if (false && (!this.adminPanVerified || !this.techPanVerified || !this.billPanVerified)) {
  //   this.toastr.error(
  //     'Please verify PAN before proceeding',
  //     'PAN Not Verified'
  //   );
  //   return;
  // }
  //     const isButtonCurrentlyDisabled =
  //       this.fullForm.invalid ||
  //       this.adminUploadedDocs?.length < 2 ||
  //       this.techUploadedDocs?.length < 2 ||
  //       this.billingUploadedDocs?.length < 2 ||
  //       this.techCountryCodeMobileCombinationError !== '' ||
  //       this.adminCountryCodeMobileCombinationError !== '' ||
  //       this.billCountryCodeMobileCombinationError !== '' ||
  //       this.isLoading; // Prevent triggering if already in a loading state

  //     if (!isButtonCurrentlyDisabled) {
  //       console.log("pppppppppppppppppppppppp", this.submitClickSubject.next())
  //       this.submitClickSubject.next(); // Push a value to the subject to start the debounce timer
  //     } else {
  //       // If the button is disabled, immediately mark form as touched to show errors
  //       this.contactSubmissionAttempted = true;
  //       console.log("ooooooooooooooooooooooooo", this.submitClickSubject.next())
  //       this.fullForm.markAllAsTouched();
  //       // this.toastr.warning("Please fill all required fields and upload all necessary documents.");
  //       // console.log('Button disabled, not debouncing:', {
  //       //   formInvalid: this.fullForm.invalid,
  //       //   adminDocs: this.adminUploadedDocs?.length,
  //       //   techDocs: this.techUploadedDocs?.length,
  //       //   billingDocs: this.billingUploadedDocs?.length,
  //       //   techError: this.techCountryCodeMobileCombinationError,
  //       //   adminError: this.adminCountryCodeMobileCombinationError,
  //       //   billError: this.billCountryCodeMobileCombinationError,
  //       //   isLoading: this.isLoading
  //       // });
  //     }
  //   }


  onButtonClickOfSubmit(): void {
    // These conditions mirror the button's [disabled] attribute.
    // We only trigger the debounce if the button is conceptually "enabled".
    if (false && (!this.adminPanVerified)) {
      this.toastr.error(
        'Please verify PAN before proceeding',
        'PAN Not Verified'
      );
      return;
    }

    const isButtonCurrentlyDisabled =
      this.fullForm.invalid ||
      this.adminUploadedDocs?.length < 2 ||
      // this.techUploadedDocs?.length < 2 ||
      //  this.billingUploadedDocs?.length < 2 ||
      // this.techCountryCodeMobileCombinationError !== '' ||
      this.adminCountryCodeMobileCombinationError !== '' ||
      this.billCountryCodeMobileCombinationError !== '' ||
      this.isLoading; // Prevent triggering if already in a loading state

    if (!isButtonCurrentlyDisabled) {
      console.log("pppppppppppppppppppppppp clicked");
      this.submitClickSubject.next(); // Push a value to the subject to start the debounce timer
    } else {
      // If the button is disabled, immediately mark form as touched to show errors
      this.contactSubmissionAttempted = true;
      console.log("ooooooooooooooooooooooooo button disabled");
      this.fullForm.markAllAsTouched();
    }
  }

  orgDetails: any
  async getOrgDetails(): Promise<void> { // Specify return type as Promise<void> for async functions
    try {
      // 1. Subscribe to the Observable and assign the result
      // This is the traditional way with Observables
      // this.organisationDetailsService.getOrganisationDetailsByOrganisationId(this.organisationId)
      //   .subscribe(
      //     (data: OrganisationDetails) => {
      //       this.orgDetails = data;
      //       console.log('Organisation Details:', this.orgDetails);
      //     },
      //     (error: any) => {
      //       console.error('Error fetching organisation details:', error);
      //       // Handle error, e.g., show a message to the user
      //     }
      //   );

      // 2. Using async/await with firstValueFrom (more modern, looks like your current async attempt)
      // This requires importing 'firstValueFrom' from 'rxjs'
      const orgDetails = await firstValueFrom(
        this.organisationDetailsService.getOrganisationDetailsByOrganisationId(this.organisationId)
      );
      this.orgDetails = orgDetails.body
      //console.log('Organisation Details:', this.orgDetails);

    } catch (error) {
      //console.error('Error fetching organisation details:', error);
      // Handle error, e.g., show a message to the user
      this.orgDetails = null; // Clear details on error if desired
    }
  }



  usersList

  getUsersList(): Observable<any> { // Change return type to Observable
    const organisationId = this.organisationId;
    if (isNaN(organisationId) || organisationId <= 1) {
      // You can handle invalid ID here, e.g., throw an error or return an empty observable
      return of(null);
    }

    // Return the Observable directly
    return this.userService.getAllUsers(organisationId).pipe(
      // Optional: Add error handling using the catchError operator
      catchError((error) => {
        if (error.status === HttpStatusCode.Unauthorized) {
          this.navigateToSessionTimeout();
        }
        // Re-throw the error or return an empty observable to prevent the stream from breaking
        return of(null);
      }),
      // Optional: Use tap to log the response without affecting the stream
      tap((response) => {
        if (response.status === HttpStatusCode.Ok) {
          //console.log('usersList:', response.body);
          this.usersList = response.body; // You can still assign it here
        }
      }),
      // Map to just the body, so the consumer gets the data directly
      map(response => response.body)
    );
  }
  navigateToSessionTimeout() {
    this.router.navigateByUrl("/session-timeout");
  }
  // contactDetailsList
  // getContactOfficersDetails(): Observable<any> { // Change return type to Observable
  //   let selectedOrganisationId = this.organisationId;
  //   if (selectedOrganisationId === 0) {
  //     return of(null);
  //   }

  //   // Return the Observable directly
  //   return this.contactDetailsFormService.getContactOfficersDetails(selectedOrganisationId).pipe(
  //     catchError((error) => {
  //       if (error.status === HttpStatusCode.Unauthorized) {
  //         this.navigateToSessionTimeout();
  //       }
  //       return of(null);
  //     }),
  //     tap((response) => {
  //       if (response.status === HttpStatusCode.Ok) {
  //         //console.log("cntactDetails", response.body);
  //         this.contactDetailsList = response.body; // You can still assign it here
  //       }
  //     }),
  //     map(response => response.body)
  //   );
  // }

}

