import * as i2$1 from '@acorex/components/button';
import { AXButtonModule } from '@acorex/components/button';
import * as i9 from '@acorex/components/check-box';
import { AXCheckBoxModule } from '@acorex/components/check-box';
import * as i1$2 from '@acorex/components/decorators';
import { AXDecoratorModule } from '@acorex/components/decorators';
import { AXDialogService } from '@acorex/components/dialog';
import * as i1$1 from '@acorex/components/form';
import { AXFormModule, AXFormComponent } from '@acorex/components/form';
import * as i7 from '@acorex/components/label';
import { AXLabelModule } from '@acorex/components/label';
import * as i2$2 from '@acorex/components/loading';
import { AXLoadingModule } from '@acorex/components/loading';
import * as i5 from '@acorex/components/password-box';
import { AXPasswordBoxModule } from '@acorex/components/password-box';
import * as i4 from '@acorex/components/text-box';
import { AXTextBoxModule } from '@acorex/components/text-box';
import * as i5$1 from '@acorex/core/translation';
import { AXTranslationModule } from '@acorex/core/translation';
import * as i1 from '@angular/common';
import { CommonModule } from '@angular/common';
import * as i0 from '@angular/core';
import { inject, ViewChild, Component } from '@angular/core';
import { RouterModule, ActivatedRoute, Router } from '@angular/router';
import { AXToastService } from '@acorex/components/toast';
import { AXValidationModule } from '@acorex/core/validation';
import { AXPSessionService } from '@acorex/platform/auth';
import { AXPHomePageService } from '@acorex/platform/common';
import * as i2 from '@angular/forms';
import { FormsModule } from '@angular/forms';
import { BehaviorSubject, firstValueFrom } from 'rxjs';
import { A as AXM_AUTH_CONFIG_TOKEN, a as AXMAuthenticationTypes } from './acorex-modules-auth-acorex-modules-auth-D1GLmcE-.mjs';

const MODULES = [
    CommonModule,
    FormsModule,
    AXFormModule,
    AXTextBoxModule,
    AXPasswordBoxModule,
    AXButtonModule,
    AXLabelModule,
    AXDecoratorModule,
    AXCheckBoxModule,
    AXTranslationModule,
    AXTranslationModule,
    AXLoadingModule,
    RouterModule,
    AXValidationModule,
];
class AXPLoginPasswordComponent {
    constructor() {
        this.configs = inject(AXM_AUTH_CONFIG_TOKEN);
        this.v1 = '';
        this.v2 = '';
        this.isLoading$ = new BehaviorSubject(false);
        this.isExternalLoading$ = new BehaviorSubject(false);
        this.submitText = 'signin.submit';
        this.dialogService = inject(AXDialogService);
        this.sessionService = inject(AXPSessionService);
        this.activateRoute = inject(ActivatedRoute);
        this.homePageService = inject(AXPHomePageService);
        this.toastService = inject(AXToastService);
        this.router = inject(Router);
        this.isKeepLogin = false;
    }
    // Computed property to check if external providers exist
    get hasExternalProviders() {
        return !!(this.configs?.externalProviders && Object.keys(this.configs.externalProviders).length > 0);
    }
    ngOnInit() {
        this.l2 = 'password';
        switch (this.configs.type) {
            case AXMAuthenticationTypes.EmailPassword:
                this.l1 = 'email';
                break;
            case AXMAuthenticationTypes.MobilePassword:
                this.l1 = 'mobile';
                break;
            case AXMAuthenticationTypes.UsernameEmailPassword:
                this.l1 = 'username-email';
                break;
            case AXMAuthenticationTypes.UsernamePassword:
            default:
                this.l1 = 'username';
        }
    }
    handleForgotOnClick() {
        this.router.navigate(['/auth/forgot']);
    }
    handleRegisterOnClick() {
        this.router.navigate([this.configs.signup?.url || '/auth/register']);
    }
    handleLoginClick() {
        this.sessionService.setStrategy(this.configs.defaultStrategyName || 'user-pass');
        const redirectUrl = this.activateRoute.snapshot.queryParams['redirectUrl'];
        this.form.validate().then(async (form) => {
            console.log(this.configs.defaultStrategyName);
            if (form.result) {
                this.isLoading$.next(true);
                this.submitText = 'processing';
                this.submitText = 'redirecting';
                try {
                    const strategy = this.sessionService.getSessionData()?.strategy;
                    if (!strategy) {
                        throw new Error('Strategy not found');
                    }
                    await this.sessionService.signin({
                        strategy: strategy,
                        username: this.v1,
                        password: this.v2,
                    });
                    await this.sessionService.signInComplete();
                    // Check authentication status before navigation
                    const isAuthenticated = await firstValueFrom(this.sessionService.isAuthenticated$);
                    if (!isAuthenticated) {
                        throw new Error('Authentication failed after signin');
                    }
                    const currentApplication = await firstValueFrom(this.sessionService.application$);
                    if (!currentApplication) {
                        if (this.sessionService.tenant?.id == null) {
                            this.router.navigate(['/auth/account/tenant-chooser']);
                        }
                        else if (this.sessionService.application?.id == null) {
                            this.router.navigate(['/auth/account/app-chooser']);
                        }
                    }
                    else if (redirectUrl) {
                        this.router.navigate([redirectUrl]);
                    }
                    else {
                        await this.homePageService.navigateTo();
                    }
                }
                catch (error) {
                    let errorMsg = error?.error?.error_description ||
                        error?.error?.error ||
                        error?.message ||
                        'An error occurred during sign in.';
                    if (typeof errorMsg === 'object') {
                        // اگر شیء بود، سعی کن یک فیلد message یا description را نمایش بدهی
                        errorMsg = errorMsg.message || errorMsg.error_description || JSON.stringify(errorMsg);
                    }
                    this.toastService.show({
                        color: 'danger',
                        content: errorMsg,
                        timeOut: 5000,
                    });
                    console.log({ error });
                    this.submitText = 'signin.submit';
                    this.v2 = null;
                    this.isLoading$.next(false);
                }
            }
        });
    }
    async handleExternalSignIn(provider) {
        this.sessionService.setStrategy(provider);
        try {
            this.isExternalLoading$.next(true);
            // Get provider configuration (optional, for validation)
            const providerConfig = this.configs?.externalProviders?.[provider];
            if (!providerConfig) {
                throw new Error(`Provider '${provider}' is not configured`);
            }
            await this.sessionService.signin({ strategy: provider });
        }
        catch (error) {
            console.error(`${provider} sign-in error:`, error);
            // Optionally show an error message to the user here
        }
        finally {
            this.isExternalLoading$.next(false);
        }
    }
    /**
     * Generates a code challenge for PKCE (Proof Key for Code Exchange)
     */
    async generateCodeChallenge(codeVerifier) {
        // Create SHA256 hash of the code verifier
        const hash = await this.sha256(codeVerifier);
        // Base64url encode the hash
        return this.base64UrlEncode(hash);
    }
    /**
     * Generates a random string for code verifier
     */
    generateRandomString(length) {
        const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
        let text = '';
        for (let i = 0; i < length; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }
        return text;
    }
    /**
     * Creates SHA256 hash of the input string using Web Crypto API
     */
    async sha256(str) {
        const encoder = new TextEncoder();
        const data = encoder.encode(str);
        return await crypto.subtle.digest('SHA-256', data);
    }
    /**
     * Base64url encodes an ArrayBuffer
     */
    base64UrlEncode(buffer) {
        const bytes = new Uint8Array(buffer);
        let binary = '';
        for (let i = 0; i < bytes.byteLength; i++) {
            binary += String.fromCharCode(bytes[i]);
        }
        return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXPLoginPasswordComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "20.3.4", type: AXPLoginPasswordComponent, isStandalone: true, selector: "ng-component", viewQueries: [{ propertyName: "form", first: true, predicate: AXFormComponent, descendants: true }], ngImport: i0, template: "<ng-container *translate=\"let t\">\n  <div class=\"ax-text-center ax-mb-4\">\n    <h1 class=\"ax-font-bold ax-text-xl ax-mb-2\">\n      {{ '@auth:signin.title' | translate | async }}\n    </h1>\n    <p class=\"ax-text-base ax-text-neutral-600\">\n      {{ '@auth:signin.hint' | translate | async }}\n    </p>\n  </div>\n  <div class=\"ax-w-80 lg:ax-w-96\">\n    <ax-form>\n      <div class=\"ax-flex ax-flex-col ax-gap-6\">\n        <ax-form-field>\n          <ax-label>{{ '@auth:username-email' | translate | async }}</ax-label>\n          <ax-text-box [name]=\"'username'\" id=\"username\" [autoComplete]=\"'username'\" [(value)]=\"v1\">\n            <ax-validation-rule rule=\"required\"></ax-validation-rule>\n          </ax-text-box>\n        </ax-form-field>\n        <ax-form-field>\n          <ax-label>{{ '@auth:password' | translate | async }}</ax-label>\n          <ax-password-box [name]=\"'password'\" id=\"password\" [autoComplete]=\"'current-password'\" [(value)]=\"v2\">\n            <ax-validation-rule rule=\"required\"></ax-validation-rule>\n          </ax-password-box>\n        </ax-form-field>\n        <div class=\"ax-flex ax-justify-between ax-items-center\">\n          <ax-check-box [(ngModel)]=\"isKeepLogin\">\n            <ax-label class=\"ax-mb-0\">{{ '@auth:signin.remember' | translate | async }}</ax-label>\n          </ax-check-box>\n          <ax-button\n            color=\"primary\"\n            class=\"ax-sm\"\n            id=\"forgot-password\"\n            [text]=\"'@auth:forgot.password' | translate | async\"\n            look=\"blank\"\n            (onClick)=\"handleForgotOnClick()\"\n          >\n          </ax-button>\n        </div>\n      </div>\n      <ax-button\n        color=\"primary\"\n        class=\"ax-mt-6 ax-w-full\"\n        id=\"submit-login\"\n        [text]=\"'@auth:signin.submit' | translate | async\"\n        (onClick)=\"handleLoginClick()\"\n        [disabled]=\"isLoading$ | async\"\n        [type]=\"'submit'\"\n      >\n        @if (isLoading$ | async) {\n          <ax-loading></ax-loading>\n        }\n      </ax-button>\n      @if (hasExternalProviders || configs.signup?.enable) {\n        <div class=\"ax-heading ax-heading-center !ax-my-8\">\n          <span>{{ '@auth:signin.or' | translate | async }}</span>\n        </div>\n      }\n      <div class=\"ax-flex ax-flex-col ax-gap-2 lg:ax-flex-row ax-justify-between ax-mt-6\">\n        @if (configs.externalProviders?.['google']) {\n          <ax-button\n            class=\"ax-w-full ax-mt-2\"\n            text=\"{{ '@auth:authentication.with-google' | translate | async }}\"\n            [color]=\"'default'\"\n            id=\"google\"\n            (onClick)=\"handleExternalSignIn('google')\"\n            [disabled]=\"isExternalLoading$ | async\"\n          >\n            <ax-prefix>\n              <ax-icon>\n                <i class=\"fa-brands fa-google fa-lg ax-text-danger-500\"></i>\n              </ax-icon>\n            </ax-prefix>\n            <ax-loading *ngIf=\"isExternalLoading$ | async\"></ax-loading>\n          </ax-button>\n        }\n        @if (configs.externalProviders?.['apple']) {\n          <ax-button\n            text=\"{{ '@auth:authentication.with-apple' | translate | async }}\"\n            [color]=\"'default'\"\n            id=\"apple\"\n            (onClick)=\"handleExternalSignIn('apple')\"\n            [disabled]=\"isExternalLoading$ | async\"\n          >\n            <ax-prefix>\n              <ax-icon>\n                <i class=\"fa-brands fa-apple fa-xl\"></i>\n              </ax-icon>\n            </ax-prefix>\n            <ax-loading *ngIf=\"isExternalLoading$ | async\"></ax-loading>\n          </ax-button>\n        }\n        @if (configs.externalProviders?.['microsoft']) {\n          <ax-button\n            text=\"{{ '@auth:authentication.with-microsoft' | translate | async }}\"\n            [color]=\"'default'\"\n            id=\"microsoft\"\n            (onClick)=\"handleExternalSignIn('microsoft')\"\n            [disabled]=\"isExternalLoading$ | async\"\n          >\n            <ax-prefix>\n              <ax-icon>\n                <i class=\"fa-brands fa-microsoft fa-lg text-blue-500\"></i>\n              </ax-icon>\n            </ax-prefix>\n            <ax-loading *ngIf=\"isExternalLoading$ | async\"></ax-loading>\n          </ax-button>\n        }\n      </div>\n    </ax-form>\n    @if (configs.signup?.enable) {\n      <ax-button\n        class=\"ax-w-full ax-mt-2\"\n        id=\"register\"\n        (onClick)=\"handleRegisterOnClick()\"\n        text=\"{{ '@auth:register' | translate | async }}\"\n        [color]=\"'default'\"\n      >\n      </ax-button>\n    }\n  </div>\n</ng-container>\n", dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "directive", type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "ngmodule", type: FormsModule }, { kind: "directive", type: i2.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i2.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "ngmodule", type: AXFormModule }, { kind: "component", type: i1$1.AXFormFieldComponent, selector: "ax-form-field", inputs: ["labelMode"] }, { kind: "component", type: i1$1.AXFormComponent, selector: "ax-form", inputs: ["labelMode", "look", "messageStyle", "updateOn"], outputs: ["onValidate", "updateOnChange"] }, { kind: "directive", type: i1$1.AXValidationRuleDirective, selector: "ax-validation-rule", inputs: ["rule", "options", "message", "disabled"] }, { kind: "ngmodule", type: AXTextBoxModule }, { kind: "component", type: i4.AXTextBoxComponent, selector: "ax-text-box", inputs: ["disabled", "tabIndex", "readonly", "value", "state", "name", "id", "placeholder", "maxLength", "allowNull", "type", "autoComplete", "look", "mask-options", "class"], outputs: ["onBlur", "onFocus", "valueChange", "stateChange", "onValueChanged", "readonlyChange", "disabledChange", "onKeyDown", "onKeyUp", "onKeyPress"] }, { kind: "ngmodule", type: AXPasswordBoxModule }, { kind: "component", type: i5.AXPasswordBoxComponent, selector: "ax-password-box", inputs: ["readonly", "disabled", "tabIndex", "placeholder", "value", "state", "name", "id", "look", "autoComplete", "showToggleButton", "class"], outputs: ["valueChange", "stateChange", "onValueChanged", "onBlur", "onFocus", "readonlyChange", "disabledChange", "onKeyDown", "onKeyUp", "onKeyPress"] }, { kind: "ngmodule", type: AXButtonModule }, { kind: "component", type: i2$1.AXButtonComponent, selector: "ax-button", inputs: ["disabled", "size", "tabIndex", "color", "look", "text", "toggleable", "selected", "iconOnly", "type", "loadingText"], outputs: ["onBlur", "onFocus", "onClick", "selectedChange", "toggleableChange", "lookChange", "colorChange", "disabledChange", "loadingTextChange"] }, { kind: "ngmodule", type: AXLabelModule }, { kind: "component", type: i7.AXLabelComponent, selector: "ax-label", inputs: ["required", "for"], outputs: ["requiredChange"] }, { kind: "ngmodule", type: AXDecoratorModule }, { kind: "component", type: i1$2.AXDecoratorIconComponent, selector: "ax-icon", inputs: ["icon"] }, { kind: "component", type: i1$2.AXDecoratorGenericComponent, selector: "ax-footer, ax-header, ax-content, ax-divider, ax-form-hint, ax-prefix, ax-suffix, ax-text, ax-title, ax-subtitle, ax-placeholder, ax-overlay" }, { kind: "ngmodule", type: AXCheckBoxModule }, { kind: "component", type: i9.AXCheckBoxComponent, selector: "ax-check-box", inputs: ["disabled", "tabIndex", "readonly", "color", "value", "name", "id", "isLoading", "indeterminate"], outputs: ["onBlur", "onFocus", "valueChange", "onValueChanged"] }, { kind: "ngmodule", type: AXTranslationModule }, { kind: "directive", type: i5$1.AXTranslatorDirective, selector: "[translate]" }, { kind: "ngmodule", type: AXLoadingModule }, { kind: "component", type: i2$2.AXLoadingComponent, selector: "ax-loading", inputs: ["visible", "type", "context"], outputs: ["visibleChange"] }, { kind: "ngmodule", type: RouterModule }, { kind: "ngmodule", type: AXValidationModule }, { kind: "pipe", type: i1.AsyncPipe, name: "async" }, { kind: "pipe", type: i5$1.AXTranslatorPipe, name: "translate" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXPLoginPasswordComponent, decorators: [{
            type: Component,
            args: [{ imports: [...MODULES], template: "<ng-container *translate=\"let t\">\n  <div class=\"ax-text-center ax-mb-4\">\n    <h1 class=\"ax-font-bold ax-text-xl ax-mb-2\">\n      {{ '@auth:signin.title' | translate | async }}\n    </h1>\n    <p class=\"ax-text-base ax-text-neutral-600\">\n      {{ '@auth:signin.hint' | translate | async }}\n    </p>\n  </div>\n  <div class=\"ax-w-80 lg:ax-w-96\">\n    <ax-form>\n      <div class=\"ax-flex ax-flex-col ax-gap-6\">\n        <ax-form-field>\n          <ax-label>{{ '@auth:username-email' | translate | async }}</ax-label>\n          <ax-text-box [name]=\"'username'\" id=\"username\" [autoComplete]=\"'username'\" [(value)]=\"v1\">\n            <ax-validation-rule rule=\"required\"></ax-validation-rule>\n          </ax-text-box>\n        </ax-form-field>\n        <ax-form-field>\n          <ax-label>{{ '@auth:password' | translate | async }}</ax-label>\n          <ax-password-box [name]=\"'password'\" id=\"password\" [autoComplete]=\"'current-password'\" [(value)]=\"v2\">\n            <ax-validation-rule rule=\"required\"></ax-validation-rule>\n          </ax-password-box>\n        </ax-form-field>\n        <div class=\"ax-flex ax-justify-between ax-items-center\">\n          <ax-check-box [(ngModel)]=\"isKeepLogin\">\n            <ax-label class=\"ax-mb-0\">{{ '@auth:signin.remember' | translate | async }}</ax-label>\n          </ax-check-box>\n          <ax-button\n            color=\"primary\"\n            class=\"ax-sm\"\n            id=\"forgot-password\"\n            [text]=\"'@auth:forgot.password' | translate | async\"\n            look=\"blank\"\n            (onClick)=\"handleForgotOnClick()\"\n          >\n          </ax-button>\n        </div>\n      </div>\n      <ax-button\n        color=\"primary\"\n        class=\"ax-mt-6 ax-w-full\"\n        id=\"submit-login\"\n        [text]=\"'@auth:signin.submit' | translate | async\"\n        (onClick)=\"handleLoginClick()\"\n        [disabled]=\"isLoading$ | async\"\n        [type]=\"'submit'\"\n      >\n        @if (isLoading$ | async) {\n          <ax-loading></ax-loading>\n        }\n      </ax-button>\n      @if (hasExternalProviders || configs.signup?.enable) {\n        <div class=\"ax-heading ax-heading-center !ax-my-8\">\n          <span>{{ '@auth:signin.or' | translate | async }}</span>\n        </div>\n      }\n      <div class=\"ax-flex ax-flex-col ax-gap-2 lg:ax-flex-row ax-justify-between ax-mt-6\">\n        @if (configs.externalProviders?.['google']) {\n          <ax-button\n            class=\"ax-w-full ax-mt-2\"\n            text=\"{{ '@auth:authentication.with-google' | translate | async }}\"\n            [color]=\"'default'\"\n            id=\"google\"\n            (onClick)=\"handleExternalSignIn('google')\"\n            [disabled]=\"isExternalLoading$ | async\"\n          >\n            <ax-prefix>\n              <ax-icon>\n                <i class=\"fa-brands fa-google fa-lg ax-text-danger-500\"></i>\n              </ax-icon>\n            </ax-prefix>\n            <ax-loading *ngIf=\"isExternalLoading$ | async\"></ax-loading>\n          </ax-button>\n        }\n        @if (configs.externalProviders?.['apple']) {\n          <ax-button\n            text=\"{{ '@auth:authentication.with-apple' | translate | async }}\"\n            [color]=\"'default'\"\n            id=\"apple\"\n            (onClick)=\"handleExternalSignIn('apple')\"\n            [disabled]=\"isExternalLoading$ | async\"\n          >\n            <ax-prefix>\n              <ax-icon>\n                <i class=\"fa-brands fa-apple fa-xl\"></i>\n              </ax-icon>\n            </ax-prefix>\n            <ax-loading *ngIf=\"isExternalLoading$ | async\"></ax-loading>\n          </ax-button>\n        }\n        @if (configs.externalProviders?.['microsoft']) {\n          <ax-button\n            text=\"{{ '@auth:authentication.with-microsoft' | translate | async }}\"\n            [color]=\"'default'\"\n            id=\"microsoft\"\n            (onClick)=\"handleExternalSignIn('microsoft')\"\n            [disabled]=\"isExternalLoading$ | async\"\n          >\n            <ax-prefix>\n              <ax-icon>\n                <i class=\"fa-brands fa-microsoft fa-lg text-blue-500\"></i>\n              </ax-icon>\n            </ax-prefix>\n            <ax-loading *ngIf=\"isExternalLoading$ | async\"></ax-loading>\n          </ax-button>\n        }\n      </div>\n    </ax-form>\n    @if (configs.signup?.enable) {\n      <ax-button\n        class=\"ax-w-full ax-mt-2\"\n        id=\"register\"\n        (onClick)=\"handleRegisterOnClick()\"\n        text=\"{{ '@auth:register' | translate | async }}\"\n        [color]=\"'default'\"\n      >\n      </ax-button>\n    }\n  </div>\n</ng-container>\n" }]
        }], propDecorators: { form: [{
                type: ViewChild,
                args: [AXFormComponent]
            }] } });

export { AXPLoginPasswordComponent };
//# sourceMappingURL=acorex-modules-auth-password.component-DzWcZlfs.mjs.map
