import { Overlay, OverlayConfig } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';
import * as i5 from '@angular/common';
import { CommonModule } from '@angular/common';
import * as i0 from '@angular/core';
import { model, input, booleanAttribute, ChangeDetectionStrategy, Component, EventEmitter, signal, Output, viewChild, contentChild, inject, ChangeDetectorRef, ElementRef, Injector, computed, output, effect, untracked } from '@angular/core';
import * as i1$1 from '@angular/forms';
import { NgForm, FormGroup, Validators, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { provideDateFnsAdapter } from '@angular/material-date-fns-adapter';
import { MAT_DATE_LOCALE } from '@angular/material/core';
import { MatFormFieldModule } from '@angular/material/form-field';
import * as i3 from '@angular/material/icon';
import { MatIconModule } from '@angular/material/icon';
import * as i2 from '@angular/material/input';
import { MatInputModule } from '@angular/material/input';
import * as i4 from '@angular/material/tooltip';
import { MatTooltipModule } from '@angular/material/tooltip';
import { SdView } from '@sdcorejs/angular/components/view';
import { SdViewDefDirective } from '@sdcorejs/angular/forms/directives';
import { SdLabel } from '@sdcorejs/angular/forms/label';
import { SD_FORM_CONFIGURATION, sdFormControlState, sdViewedTransform, sdViewedInline, SdFormControl, SdInlineErrorValidator } from '@sdcorejs/angular/forms/models';
import { sdIsEmpty, sdSerializeDataValue } from '@sdcorejs/angular/utilities/data-state';
import { TranslatePipe, I18nService } from '@sdcorejs/angular/i18n';
import { DateUtilities } from '@sdcorejs/angular/utilities/extensions';
import { BrowserUtilities } from '@sdcorejs/utils/fns';
import { isValid, parse } from 'date-fns';
import { enUS } from 'date-fns/locale';
import { Subscription } from 'rxjs';
import * as uuid from 'uuid';
import { MatButtonModule } from '@angular/material/button';
import * as i1 from '@angular/material/datepicker';
import { MatDatepickerModule } from '@angular/material/datepicker';

/**
 * Time spinner — UI chọn giờ/phút/(giây) compact, modern.
 *
 *  - Format 24h
 *  - Mặc định hiển thị HH:MM, bật `showSeconds` để hiện thêm cột giây
 *  - Hỗ trợ: click ▲▼, gõ trực tiếp, lăn chuột, mũi tên bàn phím
 *  - Wrap vòng (23 → ▲ → 00)
 */
class SdTimeSpinner {
    // Hai-chiều: cha có thể đọc/ghi từng đơn vị qua signal model.
    hours = model(0, ...(ngDevMode ? [{ debugName: "hours" }] : []));
    minutes = model(0, ...(ngDevMode ? [{ debugName: "minutes" }] : []));
    seconds = model(0, ...(ngDevMode ? [{ debugName: "seconds" }] : []));
    showSeconds = input(false, ...(ngDevMode ? [{ debugName: "showSeconds", transform: booleanAttribute }] : [{ transform: booleanAttribute }]));
    disabled = input(false, ...(ngDevMode ? [{ debugName: "disabled", transform: booleanAttribute }] : [{ transform: booleanAttribute }]));
    // Cache hiển thị 2 chữ số — pad-left "0".
    pad(n) {
        return n < 10 ? `0${n}` : `${n}`;
    }
    // Bước nhảy ±1, wrap vòng quanh max.
    step(unit, delta) {
        if (this.disabled())
            return;
        if (unit === 'h') {
            const next = (this.hours() + delta + 24) % 24;
            this.hours.set(next);
        }
        else if (unit === 'm') {
            const next = (this.minutes() + delta + 60) % 60;
            this.minutes.set(next);
        }
        else {
            const next = (this.seconds() + delta + 60) % 60;
            this.seconds.set(next);
        }
    }
    /**
     * Buffer tích lũy chữ số đang gõ cho từng đơn vị.
     * Được reset khi: focus, commit (2 chữ số / auto-commit), blur.
     */
    _buf = { h: '', m: '', s: '' };
    _commitUnit(unit, num) {
        if (unit === 'h')
            this.hours.set(num);
        else if (unit === 'm')
            this.minutes.set(num);
        else
            this.seconds.set(num);
    }
    /**
     * onInput chỉ xử lý các trường hợp không qua keydown:
     * paste, drag-drop, mobile soft-keyboard (không fire keydown).
     */
    onInput(unit, event) {
        if (this.disabled())
            return;
        const raw = event.target.value.replace(/[^0-9]/g, '');
        if (!raw) {
            this._buf[unit] = '';
            return;
        }
        const max = unit === 'h' ? 23 : 59;
        const num = Math.min(parseInt(raw.slice(-2), 10), max);
        this._commitUnit(unit, num);
        this._buf[unit] = '';
    }
    // Lăn chuột trên input — cuộn lên = tăng.
    onWheel(unit, event) {
        if (this.disabled())
            return;
        event.preventDefault();
        this._buf[unit] = '';
        this.step(unit, event.deltaY < 0 ? 1 : -1);
    }
    /**
     * Xử lý gõ phím:
     * - Chữ số: buffer 2 ký tự, auto-commit khi đủ hoặc chữ số đầu vượt ngưỡng
     * - Arrow: ±1, reset buffer
     * - Tab/Enter: commit buffer dở (nếu có)
     */
    onKeyDown(unit, event) {
        if (this.disabled())
            return;
        if (event.key === 'ArrowUp') {
            event.preventDefault();
            this._buf[unit] = '';
            this.step(unit, 1);
            return;
        }
        if (event.key === 'ArrowDown') {
            event.preventDefault();
            this._buf[unit] = '';
            this.step(unit, -1);
            return;
        }
        if (/^\d$/.test(event.key)) {
            event.preventDefault(); // Ta tự kiểm soát hiển thị
            const max = unit === 'h' ? 23 : 59;
            // Chữ số đầu tối đa để còn có thể nhập chữ số 2 hợp lệ:
            // giờ  → max first digit = 2  (vd '3x' không hợp lệ vì max 23)
            // phút/giây → max first digit = 5
            const maxFirstDigit = unit === 'h' ? 2 : 5;
            const buf = this._buf[unit] + event.key;
            const el = event.target;
            if (buf.length === 1) {
                const d = parseInt(event.key, 10);
                if (d > maxFirstDigit) {
                    // Chữ số đầu không thể là hàng chục hợp lệ → commit ngay dạng 0X
                    const num = Math.min(d, max);
                    this._commitUnit(unit, num);
                    el.value = this.pad(num);
                    this._buf[unit] = '';
                }
                else {
                    // Chờ chữ số thứ 2 — hiển thị ký tự đơn tạm thời
                    this._buf[unit] = event.key;
                    el.value = event.key;
                }
            }
            else {
                // Đã có 2 chữ số → commit
                const num = Math.min(parseInt(buf, 10), max);
                this._commitUnit(unit, num);
                el.value = this.pad(num);
                this._buf[unit] = '';
            }
            return;
        }
        if (event.key === 'Backspace' || event.key === 'Delete') {
            this._buf[unit] = '';
            return; // browser tự xử lý xóa ký tự
        }
        if (event.key === 'Tab' || event.key === 'Enter') {
            // Commit nếu còn buffer chữ số đơn
            if (this._buf[unit]) {
                const max = unit === 'h' ? 23 : 59;
                const num = Math.min(parseInt(this._buf[unit], 10), max);
                this._commitUnit(unit, num);
                this._buf[unit] = '';
            }
        }
    }
    // Khi blur: commit buffer dở (nếu có) + chuẩn hóa hiển thị.
    onBlur(unit, event) {
        if (this._buf[unit]) {
            const max = unit === 'h' ? 23 : 59;
            const num = Math.min(parseInt(this._buf[unit], 10), max);
            this._commitUnit(unit, num);
            this._buf[unit] = '';
        }
        const el = event.target;
        if (unit === 'h')
            el.value = this.pad(this.hours());
        else if (unit === 'm')
            el.value = this.pad(this.minutes());
        else
            el.value = this.pad(this.seconds());
    }
    // Chọn toàn bộ text khi focus + reset buffer.
    onFocus(unit, event) {
        this._buf[unit] = '';
        event.target.select();
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.24", ngImport: i0, type: SdTimeSpinner, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "20.3.24", type: SdTimeSpinner, isStandalone: true, selector: "sd-time-spinner", inputs: { hours: { classPropertyName: "hours", publicName: "hours", isSignal: true, isRequired: false, transformFunction: null }, minutes: { classPropertyName: "minutes", publicName: "minutes", isSignal: true, isRequired: false, transformFunction: null }, seconds: { classPropertyName: "seconds", publicName: "seconds", isSignal: true, isRequired: false, transformFunction: null }, showSeconds: { classPropertyName: "showSeconds", publicName: "showSeconds", isSignal: true, isRequired: false, transformFunction: null }, disabled: { classPropertyName: "disabled", publicName: "disabled", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { hours: "hoursChange", minutes: "minutesChange", seconds: "secondsChange" }, ngImport: i0, template: "<div class=\"sd-time-spinner\" [class.disabled]=\"disabled()\">\n  <!-- HOURS -->\n  <div class=\"unit\">\n    <button type=\"button\" class=\"step\" (click)=\"step('h', 1)\" tabindex=\"-1\" [attr.aria-label]=\"'core.form.time-spinner.increase-hour' | translate\">\n      <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n        <polyline points=\"18 15 12 9 6 15\"></polyline>\n      </svg>\n    </button>\n    <input\n      class=\"value\"\n      type=\"text\"\n      inputmode=\"numeric\"\n      maxlength=\"2\"\n      [value]=\"pad(hours())\"\n      [disabled]=\"disabled()\"\n      (input)=\"onInput('h', $event)\"\n      (wheel)=\"onWheel('h', $event)\"\n      (keydown)=\"onKeyDown('h', $event)\"\n      (focus)=\"onFocus('h', $event)\"\n      (blur)=\"onBlur('h', $event)\"\n      [attr.aria-label]=\"'core.form.time-spinner.hour' | translate\" />\n    <button type=\"button\" class=\"step\" (click)=\"step('h', -1)\" tabindex=\"-1\" [attr.aria-label]=\"'core.form.time-spinner.decrease-hour' | translate\">\n      <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n        <polyline points=\"6 9 12 15 18 9\"></polyline>\n      </svg>\n    </button>\n  </div>\n\n  <span class=\"sep\">:</span>\n\n  <!-- MINUTES -->\n  <div class=\"unit\">\n    <button type=\"button\" class=\"step\" (click)=\"step('m', 1)\" tabindex=\"-1\" [attr.aria-label]=\"'core.form.time-spinner.increase-minute' | translate\">\n      <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n        <polyline points=\"18 15 12 9 6 15\"></polyline>\n      </svg>\n    </button>\n    <input\n      class=\"value\"\n      type=\"text\"\n      inputmode=\"numeric\"\n      maxlength=\"2\"\n      [value]=\"pad(minutes())\"\n      [disabled]=\"disabled()\"\n      (input)=\"onInput('m', $event)\"\n      (wheel)=\"onWheel('m', $event)\"\n      (keydown)=\"onKeyDown('m', $event)\"\n      (focus)=\"onFocus('m', $event)\"\n      (blur)=\"onBlur('m', $event)\"\n      [attr.aria-label]=\"'core.form.time-spinner.minute' | translate\" />\n    <button type=\"button\" class=\"step\" (click)=\"step('m', -1)\" tabindex=\"-1\" [attr.aria-label]=\"'core.form.time-spinner.decrease-minute' | translate\">\n      <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n        <polyline points=\"6 9 12 15 18 9\"></polyline>\n      </svg>\n    </button>\n  </div>\n\n  @if (showSeconds()) {\n    <span class=\"sep\">:</span>\n    <!-- SECONDS -->\n    <div class=\"unit\">\n      <button type=\"button\" class=\"step\" (click)=\"step('s', 1)\" tabindex=\"-1\" [attr.aria-label]=\"'core.form.time-spinner.increase-second' | translate\">\n        <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n          <polyline points=\"18 15 12 9 6 15\"></polyline>\n        </svg>\n      </button>\n      <input\n        class=\"value\"\n        type=\"text\"\n        inputmode=\"numeric\"\n        maxlength=\"2\"\n        [value]=\"pad(seconds())\"\n        [disabled]=\"disabled()\"\n        (input)=\"onInput('s', $event)\"\n        (wheel)=\"onWheel('s', $event)\"\n        (keydown)=\"onKeyDown('s', $event)\"\n        (focus)=\"onFocus('s', $event)\"\n        (blur)=\"onBlur('s', $event)\"\n        [attr.aria-label]=\"'core.form.time-spinner.second' | translate\" />\n      <button type=\"button\" class=\"step\" (click)=\"step('s', -1)\" tabindex=\"-1\" [attr.aria-label]=\"'core.form.time-spinner.decrease-second' | translate\">\n        <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n          <polyline points=\"6 9 12 15 18 9\"></polyline>\n        </svg>\n      </button>\n    </div>\n  }\n</div>\n", styles: [":host{display:block}.sd-time-spinner{display:flex;align-items:center;justify-content:center;gap:4px;padding:6px 12px}.sd-time-spinner.disabled{opacity:.5;pointer-events:none}.sd-time-spinner .unit{display:flex;flex-direction:column;align-items:center;gap:2px}.sd-time-spinner .unit .step{width:32px;height:20px;padding:0;border:0;background:transparent;color:var(--sd-black300);border-radius:6px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:background-color .15s ease,color .15s ease,transform .1s ease}.sd-time-spinner .unit .step svg{width:14px;height:14px;display:block}.sd-time-spinner .unit .step:hover{background:var(--sd-primary-light);color:var(--sd-primary)}.sd-time-spinner .unit .step:active{transform:scale(.92)}.sd-time-spinner .unit .value{width:44px;height:36px;padding:0;text-align:center;font-size:20px;font-weight:600;line-height:1;color:var(--sd-black500);font-variant-numeric:tabular-nums;background:transparent;border:1.5px solid transparent;border-radius:6px;outline:none;cursor:text;transition:border-color .15s ease,background-color .15s ease}.sd-time-spinner .unit .value:hover:not(:focus){background:var(--sd-black100)}.sd-time-spinner .unit .value:focus{border-color:var(--sd-primary);background:#fff}.sd-time-spinner .unit .value:disabled{color:var(--sd-black400);cursor:not-allowed}.sd-time-spinner .unit:hover .step{color:var(--sd-black400)}.sd-time-spinner .sep{font-size:20px;font-weight:600;color:var(--sd-black400);padding-bottom:2px;-webkit-user-select:none;user-select:none}\n"], dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "pipe", type: TranslatePipe, name: "translate" }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.24", ngImport: i0, type: SdTimeSpinner, decorators: [{
            type: Component,
            args: [{ selector: 'sd-time-spinner', standalone: true, imports: [CommonModule, TranslatePipe], changeDetection: ChangeDetectionStrategy.OnPush, template: "<div class=\"sd-time-spinner\" [class.disabled]=\"disabled()\">\n  <!-- HOURS -->\n  <div class=\"unit\">\n    <button type=\"button\" class=\"step\" (click)=\"step('h', 1)\" tabindex=\"-1\" [attr.aria-label]=\"'core.form.time-spinner.increase-hour' | translate\">\n      <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n        <polyline points=\"18 15 12 9 6 15\"></polyline>\n      </svg>\n    </button>\n    <input\n      class=\"value\"\n      type=\"text\"\n      inputmode=\"numeric\"\n      maxlength=\"2\"\n      [value]=\"pad(hours())\"\n      [disabled]=\"disabled()\"\n      (input)=\"onInput('h', $event)\"\n      (wheel)=\"onWheel('h', $event)\"\n      (keydown)=\"onKeyDown('h', $event)\"\n      (focus)=\"onFocus('h', $event)\"\n      (blur)=\"onBlur('h', $event)\"\n      [attr.aria-label]=\"'core.form.time-spinner.hour' | translate\" />\n    <button type=\"button\" class=\"step\" (click)=\"step('h', -1)\" tabindex=\"-1\" [attr.aria-label]=\"'core.form.time-spinner.decrease-hour' | translate\">\n      <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n        <polyline points=\"6 9 12 15 18 9\"></polyline>\n      </svg>\n    </button>\n  </div>\n\n  <span class=\"sep\">:</span>\n\n  <!-- MINUTES -->\n  <div class=\"unit\">\n    <button type=\"button\" class=\"step\" (click)=\"step('m', 1)\" tabindex=\"-1\" [attr.aria-label]=\"'core.form.time-spinner.increase-minute' | translate\">\n      <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n        <polyline points=\"18 15 12 9 6 15\"></polyline>\n      </svg>\n    </button>\n    <input\n      class=\"value\"\n      type=\"text\"\n      inputmode=\"numeric\"\n      maxlength=\"2\"\n      [value]=\"pad(minutes())\"\n      [disabled]=\"disabled()\"\n      (input)=\"onInput('m', $event)\"\n      (wheel)=\"onWheel('m', $event)\"\n      (keydown)=\"onKeyDown('m', $event)\"\n      (focus)=\"onFocus('m', $event)\"\n      (blur)=\"onBlur('m', $event)\"\n      [attr.aria-label]=\"'core.form.time-spinner.minute' | translate\" />\n    <button type=\"button\" class=\"step\" (click)=\"step('m', -1)\" tabindex=\"-1\" [attr.aria-label]=\"'core.form.time-spinner.decrease-minute' | translate\">\n      <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n        <polyline points=\"6 9 12 15 18 9\"></polyline>\n      </svg>\n    </button>\n  </div>\n\n  @if (showSeconds()) {\n    <span class=\"sep\">:</span>\n    <!-- SECONDS -->\n    <div class=\"unit\">\n      <button type=\"button\" class=\"step\" (click)=\"step('s', 1)\" tabindex=\"-1\" [attr.aria-label]=\"'core.form.time-spinner.increase-second' | translate\">\n        <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n          <polyline points=\"18 15 12 9 6 15\"></polyline>\n        </svg>\n      </button>\n      <input\n        class=\"value\"\n        type=\"text\"\n        inputmode=\"numeric\"\n        maxlength=\"2\"\n        [value]=\"pad(seconds())\"\n        [disabled]=\"disabled()\"\n        (input)=\"onInput('s', $event)\"\n        (wheel)=\"onWheel('s', $event)\"\n        (keydown)=\"onKeyDown('s', $event)\"\n        (focus)=\"onFocus('s', $event)\"\n        (blur)=\"onBlur('s', $event)\"\n        [attr.aria-label]=\"'core.form.time-spinner.second' | translate\" />\n      <button type=\"button\" class=\"step\" (click)=\"step('s', -1)\" tabindex=\"-1\" [attr.aria-label]=\"'core.form.time-spinner.decrease-second' | translate\">\n        <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n          <polyline points=\"6 9 12 15 18 9\"></polyline>\n        </svg>\n      </button>\n    </div>\n  }\n</div>\n", styles: [":host{display:block}.sd-time-spinner{display:flex;align-items:center;justify-content:center;gap:4px;padding:6px 12px}.sd-time-spinner.disabled{opacity:.5;pointer-events:none}.sd-time-spinner .unit{display:flex;flex-direction:column;align-items:center;gap:2px}.sd-time-spinner .unit .step{width:32px;height:20px;padding:0;border:0;background:transparent;color:var(--sd-black300);border-radius:6px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:background-color .15s ease,color .15s ease,transform .1s ease}.sd-time-spinner .unit .step svg{width:14px;height:14px;display:block}.sd-time-spinner .unit .step:hover{background:var(--sd-primary-light);color:var(--sd-primary)}.sd-time-spinner .unit .step:active{transform:scale(.92)}.sd-time-spinner .unit .value{width:44px;height:36px;padding:0;text-align:center;font-size:20px;font-weight:600;line-height:1;color:var(--sd-black500);font-variant-numeric:tabular-nums;background:transparent;border:1.5px solid transparent;border-radius:6px;outline:none;cursor:text;transition:border-color .15s ease,background-color .15s ease}.sd-time-spinner .unit .value:hover:not(:focus){background:var(--sd-black100)}.sd-time-spinner .unit .value:focus{border-color:var(--sd-primary);background:#fff}.sd-time-spinner .unit .value:disabled{color:var(--sd-black400);cursor:not-allowed}.sd-time-spinner .unit:hover .step{color:var(--sd-black400)}.sd-time-spinner .sep{font-size:20px;font-weight:600;color:var(--sd-black400);padding-bottom:2px;-webkit-user-select:none;user-select:none}\n"] }]
        }], propDecorators: { hours: [{ type: i0.Input, args: [{ isSignal: true, alias: "hours", required: false }] }, { type: i0.Output, args: ["hoursChange"] }], minutes: [{ type: i0.Input, args: [{ isSignal: true, alias: "minutes", required: false }] }, { type: i0.Output, args: ["minutesChange"] }], seconds: [{ type: i0.Input, args: [{ isSignal: true, alias: "seconds", required: false }] }, { type: i0.Output, args: ["secondsChange"] }], showSeconds: [{ type: i0.Input, args: [{ isSignal: true, alias: "showSeconds", required: false }] }], disabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "disabled", required: false }] }] } });

/**
 * Datetime picker popup — Calendar (Angular Material) + Time Spinner + Footer.
 *
 * Component này được render trong CDK Overlay từ `sd-datetime`.
 * Phát event `confirmed`/`cancelled` khi user thao tác trên footer.
 */
class SdDatetimePicker {
    // ==========================================
    // INPUTS
    // ==========================================
    /** Giá trị khởi tạo của picker (native Date, có thể null). */
    initialValue = input(null, ...(ngDevMode ? [{ debugName: "initialValue" }] : []));
    /** Min/max boundary (Date hoặc bất kỳ giá trị nào hợp lệ cho `new Date(...)`). */
    minDate = input(null, ...(ngDevMode ? [{ debugName: "minDate" }] : []));
    maxDate = input(null, ...(ngDevMode ? [{ debugName: "maxDate" }] : []));
    /** Hiển thị thêm cột giây (mặc định ẩn — chỉ HH:MM). */
    showSeconds = input(false, ...(ngDevMode ? [{ debugName: "showSeconds", transform: booleanAttribute }] : [{ transform: booleanAttribute }]));
    /** Disabled state. */
    disabled = input(false, ...(ngDevMode ? [{ debugName: "disabled", transform: booleanAttribute }] : [{ transform: booleanAttribute }]));
    // ==========================================
    // OUTPUTS (legacy EventEmitter để tương thích Overlay subscription)
    // ==========================================
    confirmed = new EventEmitter();
    cancelled = new EventEmitter();
    // ==========================================
    // STATE — signals nội bộ
    // ==========================================
    // date-fns là immutable — luôn cấp Date mới, không mutate.
    selectedDate = signal(new Date(), ...(ngDevMode ? [{ debugName: "selectedDate" }] : []));
    hours = signal(0, ...(ngDevMode ? [{ debugName: "hours" }] : []));
    minutes = signal(0, ...(ngDevMode ? [{ debugName: "minutes" }] : []));
    seconds = signal(0, ...(ngDevMode ? [{ debugName: "seconds" }] : []));
    constructor() {
        // Khởi tạo từ initialValue khi component được tạo.
        // Effect không cần thiết vì input chỉ set một lần lúc mở popup.
        queueMicrotask(() => this.#hydrateFromInput());
    }
    #hydrateFromInput() {
        const init = this.initialValue();
        // Clone bằng new Date(getTime()) để không chia sẻ reference với caller.
        const d = init instanceof Date && isValid(init) ? new Date(init.getTime()) : new Date();
        this.selectedDate.set(d);
        this.hours.set(d.getHours());
        this.minutes.set(d.getMinutes());
        this.seconds.set(d.getSeconds());
    }
    // ==========================================
    // EVENT HANDLERS
    // ==========================================
    /** Khi user chọn ngày trên MatCalendar. */
    onDateSelected(date) {
        if (!date)
            return;
        // Giữ nguyên giờ/phút/giây hiện tại, chỉ thay đổi ngày.
        const next = new Date(date.getTime());
        next.setHours(this.hours(), this.minutes(), this.seconds(), 0);
        this.selectedDate.set(next);
    }
    onConfirm() {
        if (this.disabled())
            return;
        // Tạo Date mới từ selectedDate + hours/minutes/seconds hiện tại.
        const base = this.selectedDate();
        const result = new Date(base.getTime());
        result.setHours(this.hours(), this.minutes(), this.showSeconds() ? this.seconds() : 0, 0);
        this.confirmed.emit(result);
    }
    onCancel() {
        this.cancelled.emit();
    }
    /** Đặt nhanh thời gian "Bây giờ". */
    onNow() {
        if (this.disabled())
            return;
        const now = new Date();
        this.selectedDate.set(now);
        this.hours.set(now.getHours());
        this.minutes.set(now.getMinutes());
        this.seconds.set(now.getSeconds());
    }
    // Min/Max — chuyển về Date cho MatCalendar (date-fns adapter dùng native Date).
    get _minDate() {
        const v = this.minDate();
        if (v === null || v === undefined)
            return null;
        if (v instanceof Date)
            return isValid(v) ? v : null;
        const d = new Date(v);
        return isValid(d) ? d : null;
    }
    get _maxDate() {
        const v = this.maxDate();
        if (v === null || v === undefined)
            return null;
        if (v instanceof Date)
            return isValid(v) ? v : null;
        const d = new Date(v);
        return isValid(d) ? d : null;
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.24", ngImport: i0, type: SdDatetimePicker, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.1.0", version: "20.3.24", type: SdDatetimePicker, isStandalone: true, selector: "sd-datetime-picker", inputs: { initialValue: { classPropertyName: "initialValue", publicName: "initialValue", isSignal: true, isRequired: false, transformFunction: null }, minDate: { classPropertyName: "minDate", publicName: "minDate", isSignal: true, isRequired: false, transformFunction: null }, maxDate: { classPropertyName: "maxDate", publicName: "maxDate", isSignal: true, isRequired: false, transformFunction: null }, showSeconds: { classPropertyName: "showSeconds", publicName: "showSeconds", isSignal: true, isRequired: false, transformFunction: null }, disabled: { classPropertyName: "disabled", publicName: "disabled", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { confirmed: "confirmed", cancelled: "cancelled" }, ngImport: i0, template: "<div class=\"sd-datetime-picker\">\n  <!-- Calendar -->\n  <div class=\"picker-calendar\">\n    <mat-calendar\n      [selected]=\"selectedDate()\"\n      [minDate]=\"_minDate\"\n      [maxDate]=\"_maxDate\"\n      (selectedChange)=\"onDateSelected($event)\">\n    </mat-calendar>\n  </div>\n\n  <!-- Divider m\u1EA3nh -->\n  <div class=\"picker-divider\"></div>\n\n  <!-- Time Spinner -->\n  <div class=\"picker-time\">\n    <sd-time-spinner\n      [(hours)]=\"hours\"\n      [(minutes)]=\"minutes\"\n      [(seconds)]=\"seconds\"\n      [showSeconds]=\"showSeconds()\"\n      [disabled]=\"disabled()\">\n    </sd-time-spinner>\n  </div>\n\n  <!-- Footer: B\u00E2y gi\u1EDD | H\u1EE7y | X\u00E1c nh\u1EADn -->\n  <div class=\"picker-footer\">\n    <button type=\"button\" class=\"btn btn-ghost\" (click)=\"onNow()\" [disabled]=\"disabled()\">\n      <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n        <circle cx=\"12\" cy=\"12\" r=\"9\"></circle>\n        <polyline points=\"12 7 12 12 15 14\"></polyline>\n      </svg>\n      <span>{{ 'core.form.datetime.now' | translate }}</span>\n    </button>\n\n    <div class=\"footer-actions\">\n      <button type=\"button\" class=\"btn btn-text\" (click)=\"onCancel()\">{{ 'core.common.cancel' | translate }}</button>\n      <button type=\"button\" class=\"btn btn-primary\" (click)=\"onConfirm()\" [disabled]=\"disabled()\">\n        <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n          <polyline points=\"20 6 9 17 4 12\"></polyline>\n        </svg>\n        <span>{{ 'core.form.datetime.confirm' | translate }}</span>\n      </button>\n    </div>\n  </div>\n</div>\n", styles: [":host{display:block;background:#fff;border-radius:12px;box-shadow:0 10px 24px #0000001f,0 2px 6px #0000000f;overflow:hidden;font-family:inherit}.sd-datetime-picker{display:flex;flex-direction:column;width:320px;animation:sd-picker-enter .18s ease-out}@keyframes sd-picker-enter{0%{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:translateY(0)}}.picker-calendar{padding:4px 8px 0}.picker-calendar ::ng-deep .mat-calendar{height:auto;width:100%}.picker-calendar ::ng-deep .mat-calendar-header{padding:4px 4px 0}.picker-calendar ::ng-deep .mat-calendar-content{padding:0 8px 8px}.picker-divider{height:1px;background:var(--sd-black200);margin:0 16px}.picker-time{padding:8px 0}.picker-footer{display:flex;align-items:center;justify-content:space-between;padding:8px 12px 12px;gap:8px;border-top:1px solid var(--sd-black100)}.picker-footer .footer-actions{display:flex;align-items:center;gap:6px}.btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;height:32px;padding:0 12px;border:0;border-radius:6px;font-size:13px;font-weight:500;line-height:1;cursor:pointer;transition:background-color .15s ease,color .15s ease,transform .1s ease;white-space:nowrap}.btn svg{width:14px;height:14px;flex-shrink:0}.btn:active:not(:disabled){transform:scale(.97)}.btn:disabled{opacity:.5;cursor:not-allowed}.btn.btn-ghost{background:transparent;color:var(--sd-black400)}.btn.btn-ghost:hover:not(:disabled){background:var(--sd-black100);color:var(--sd-primary)}.btn.btn-text{background:transparent;color:var(--sd-black500)}.btn.btn-text:hover:not(:disabled){background:var(--sd-black100)}.btn.btn-primary{background:var(--sd-primary);color:#fff;box-shadow:0 1px 2px #0000000d}.btn.btn-primary:hover:not(:disabled){background:var(--sd-primary-dark)}\n"], dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "ngmodule", type: MatDatepickerModule }, { kind: "component", type: i1.MatCalendar, selector: "mat-calendar", inputs: ["headerComponent", "startAt", "startView", "selected", "minDate", "maxDate", "dateFilter", "dateClass", "comparisonStart", "comparisonEnd", "startDateAccessibleName", "endDateAccessibleName"], outputs: ["selectedChange", "yearSelected", "monthSelected", "viewChanged", "_userSelection", "_userDragDrop"], exportAs: ["matCalendar"] }, { kind: "ngmodule", type: MatButtonModule }, { kind: "component", type: SdTimeSpinner, selector: "sd-time-spinner", inputs: ["hours", "minutes", "seconds", "showSeconds", "disabled"], outputs: ["hoursChange", "minutesChange", "secondsChange"] }, { kind: "pipe", type: TranslatePipe, name: "translate" }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.24", ngImport: i0, type: SdDatetimePicker, decorators: [{
            type: Component,
            args: [{ selector: 'sd-datetime-picker', standalone: true, imports: [CommonModule, MatDatepickerModule, MatButtonModule, SdTimeSpinner, TranslatePipe], changeDetection: ChangeDetectionStrategy.OnPush, template: "<div class=\"sd-datetime-picker\">\n  <!-- Calendar -->\n  <div class=\"picker-calendar\">\n    <mat-calendar\n      [selected]=\"selectedDate()\"\n      [minDate]=\"_minDate\"\n      [maxDate]=\"_maxDate\"\n      (selectedChange)=\"onDateSelected($event)\">\n    </mat-calendar>\n  </div>\n\n  <!-- Divider m\u1EA3nh -->\n  <div class=\"picker-divider\"></div>\n\n  <!-- Time Spinner -->\n  <div class=\"picker-time\">\n    <sd-time-spinner\n      [(hours)]=\"hours\"\n      [(minutes)]=\"minutes\"\n      [(seconds)]=\"seconds\"\n      [showSeconds]=\"showSeconds()\"\n      [disabled]=\"disabled()\">\n    </sd-time-spinner>\n  </div>\n\n  <!-- Footer: B\u00E2y gi\u1EDD | H\u1EE7y | X\u00E1c nh\u1EADn -->\n  <div class=\"picker-footer\">\n    <button type=\"button\" class=\"btn btn-ghost\" (click)=\"onNow()\" [disabled]=\"disabled()\">\n      <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n        <circle cx=\"12\" cy=\"12\" r=\"9\"></circle>\n        <polyline points=\"12 7 12 12 15 14\"></polyline>\n      </svg>\n      <span>{{ 'core.form.datetime.now' | translate }}</span>\n    </button>\n\n    <div class=\"footer-actions\">\n      <button type=\"button\" class=\"btn btn-text\" (click)=\"onCancel()\">{{ 'core.common.cancel' | translate }}</button>\n      <button type=\"button\" class=\"btn btn-primary\" (click)=\"onConfirm()\" [disabled]=\"disabled()\">\n        <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n          <polyline points=\"20 6 9 17 4 12\"></polyline>\n        </svg>\n        <span>{{ 'core.form.datetime.confirm' | translate }}</span>\n      </button>\n    </div>\n  </div>\n</div>\n", styles: [":host{display:block;background:#fff;border-radius:12px;box-shadow:0 10px 24px #0000001f,0 2px 6px #0000000f;overflow:hidden;font-family:inherit}.sd-datetime-picker{display:flex;flex-direction:column;width:320px;animation:sd-picker-enter .18s ease-out}@keyframes sd-picker-enter{0%{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:translateY(0)}}.picker-calendar{padding:4px 8px 0}.picker-calendar ::ng-deep .mat-calendar{height:auto;width:100%}.picker-calendar ::ng-deep .mat-calendar-header{padding:4px 4px 0}.picker-calendar ::ng-deep .mat-calendar-content{padding:0 8px 8px}.picker-divider{height:1px;background:var(--sd-black200);margin:0 16px}.picker-time{padding:8px 0}.picker-footer{display:flex;align-items:center;justify-content:space-between;padding:8px 12px 12px;gap:8px;border-top:1px solid var(--sd-black100)}.picker-footer .footer-actions{display:flex;align-items:center;gap:6px}.btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;height:32px;padding:0 12px;border:0;border-radius:6px;font-size:13px;font-weight:500;line-height:1;cursor:pointer;transition:background-color .15s ease,color .15s ease,transform .1s ease;white-space:nowrap}.btn svg{width:14px;height:14px;flex-shrink:0}.btn:active:not(:disabled){transform:scale(.97)}.btn:disabled{opacity:.5;cursor:not-allowed}.btn.btn-ghost{background:transparent;color:var(--sd-black400)}.btn.btn-ghost:hover:not(:disabled){background:var(--sd-black100);color:var(--sd-primary)}.btn.btn-text{background:transparent;color:var(--sd-black500)}.btn.btn-text:hover:not(:disabled){background:var(--sd-black100)}.btn.btn-primary{background:var(--sd-primary);color:#fff;box-shadow:0 1px 2px #0000000d}.btn.btn-primary:hover:not(:disabled){background:var(--sd-primary-dark)}\n"] }]
        }], ctorParameters: () => [], propDecorators: { initialValue: [{ type: i0.Input, args: [{ isSignal: true, alias: "initialValue", required: false }] }], minDate: [{ type: i0.Input, args: [{ isSignal: true, alias: "minDate", required: false }] }], maxDate: [{ type: i0.Input, args: [{ isSignal: true, alias: "maxDate", required: false }] }], showSeconds: [{ type: i0.Input, args: [{ isSignal: true, alias: "showSeconds", required: false }] }], disabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "disabled", required: false }] }], confirmed: [{
                type: Output
            }], cancelled: [{
                type: Output
            }] } });

/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @angular-eslint/no-input-rename */
/**
 * Format parse/display dùng cho MatDateAdapter (date-fns).
 * Note: format input là `dd/MM/yyyy HH:mm` (không có giây mặc định) —
 *       giây chỉ được render khi `showSeconds` = true.
 * Token date-fns dùng chữ thường: `yyyy` (năm), `dd` (ngày), `HH` (giờ 24h).
 */
const SD_DATETIME_FORMATS = {
    parse: { dateInput: 'dd/MM/yyyy HH:mm' },
    display: {
        dateInput: 'dd/MM/yyyy HH:mm',
        monthYearLabel: 'MMM yyyy',
        dateA11yLabel: 'PP',
        monthYearA11yLabel: 'MMMM yyyy',
    },
};
/**
 * Thử parse `value` theo lần lượt nhiều format; trả về Date đầu tiên hợp lệ.
 * date-fns không hỗ trợ multi-format parse như moment(value, [fmt1, fmt2], true).
 */
function parseFirstValid(value, formats) {
    for (const fmt of formats) {
        const d = parse(value, fmt, new Date());
        if (isValid(d))
            return d;
    }
    return null;
}
class SdDatetime {
    id = `I${uuid.v4()}`;
    // ==========================================
    // 1. SIGNAL QUERIES
    // ==========================================
    inputRef = viewChild('input', ...(ngDevMode ? [{ debugName: "inputRef" }] : []));
    sdLabelTemplate = contentChild('sdLabel', ...(ngDevMode ? [{ debugName: "sdLabelTemplate" }] : []));
    sdValueTemplate = contentChild('sdValue', ...(ngDevMode ? [{ debugName: "sdValueTemplate" }] : []));
    sdViewDef = contentChild(SdViewDefDirective, ...(ngDevMode ? [{ debugName: "sdViewDef" }] : []));
    // ==========================================
    // 2. INJECTS
    // ==========================================
    ref = inject(ChangeDetectorRef);
    overlay = inject(Overlay);
    elementRef = inject(ElementRef);
    injector = inject(Injector);
    formConfig = inject(SD_FORM_CONFIGURATION, { optional: true });
    #i18n = inject(I18nService);
    // ==========================================
    // 3. SIGNAL INPUTS & MODEL
    // ==========================================
    autoIdInput = input(undefined, ...(ngDevMode ? [{ debugName: "autoIdInput", alias: 'autoId' }] : [{ alias: 'autoId' }]));
    autoId = computed(() => this.autoIdInput() ? `forms-datetime-${this.autoIdInput()}` : undefined, ...(ngDevMode ? [{ debugName: "autoId" }] : []));
    #state = sdFormControlState(computed(() => this.formControl));
    dataDisabled = computed(() => (this.#state().disabled ? 'true' : 'false'), ...(ngDevMode ? [{ debugName: "dataDisabled" }] : []));
    dataInvalid = computed(() => (this.#state().invalid ? 'true' : 'false'), ...(ngDevMode ? [{ debugName: "dataInvalid" }] : []));
    dataEmpty = computed(() => (sdIsEmpty(this.#state().value) ? 'true' : 'false'), ...(ngDevMode ? [{ debugName: "dataEmpty" }] : []));
    dataValue = computed(() => sdSerializeDataValue(this.#state().value), ...(ngDevMode ? [{ debugName: "dataValue" }] : []));
    dataRequired = computed(() => (this.required() ? 'true' : 'false'), ...(ngDevMode ? [{ debugName: "dataRequired" }] : []));
    dataErrorMessage = computed(() => {
        void this.#state();
        const msg = this.errorMessage();
        return msg && msg.length > 0 ? msg : null;
    }, ...(ngDevMode ? [{ debugName: "dataErrorMessage" }] : []));
    name = input(uuid.v4(), ...(ngDevMode ? [{ debugName: "name" }] : []));
    size = input('md', ...(ngDevMode ? [{ debugName: "size" }] : []));
    // Ghi (TransformT): any (để không bị lỗi typing khi cha truyền vào)
    form = input(undefined, ...(ngDevMode ? [{ debugName: "form", transform: (val) => {
                if (!val)
                    return undefined;
                // Nếu cha truyền vào NgForm (template-driven) -> Bóc lấy FormGroup bên trong
                if (val instanceof NgForm)
                    return val.form;
                // Nếu cha truyền sẵn FormGroup (reactive) -> Lấy luôn
                if (val instanceof FormGroup)
                    return val;
                // Fallback an toàn phòng trường hợp cha truyền 1 object chứa form
                if (val?.form instanceof FormGroup)
                    return val.form;
                return undefined;
            } }] : [{
            transform: (val) => {
                if (!val)
                    return undefined;
                // Nếu cha truyền vào NgForm (template-driven) -> Bóc lấy FormGroup bên trong
                if (val instanceof NgForm)
                    return val.form;
                // Nếu cha truyền sẵn FormGroup (reactive) -> Lấy luôn
                if (val instanceof FormGroup)
                    return val;
                // Fallback an toàn phòng trường hợp cha truyền 1 object chứa form
                if (val?.form instanceof FormGroup)
                    return val.form;
                return undefined;
            },
        }]));
    label = input(...(ngDevMode ? [undefined, { debugName: "label" }] : []));
    helperText = input(...(ngDevMode ? [undefined, { debugName: "helperText" }] : []));
    placeholder = input(...(ngDevMode ? [undefined, { debugName: "placeholder" }] : []));
    hideInlineError = input(false, ...(ngDevMode ? [{ debugName: "hideInlineError", transform: booleanAttribute }] : [{ transform: booleanAttribute }]));
    required = input(false, ...(ngDevMode ? [{ debugName: "required", transform: booleanAttribute }] : [{ transform: booleanAttribute }]));
    disabled = input(false, ...(ngDevMode ? [{ debugName: "disabled", transform: booleanAttribute }] : [{ transform: booleanAttribute }]));
    /** Display mode: `false` edit · `true` static view · `'inline'` view + click-to-edit (datetime overlay). */
    viewed = input(false, ...(ngDevMode ? [{ debugName: "viewed", transform: sdViewedTransform }] : [{ transform: sdViewedTransform }]));
    /** Hiển thị thêm cột giây trong picker. Mặc định: chỉ HH:MM. */
    showSeconds = input(false, ...(ngDevMode ? [{ debugName: "showSeconds", transform: booleanAttribute }] : [{ transform: booleanAttribute }]));
    /** In `viewed='inline'`, show a hover clear-× on the text face. Set `false` when the host owns removal (chips). */
    clearable = input(true, ...(ngDevMode ? [{ debugName: "clearable", transform: booleanAttribute }] : [{ transform: booleanAttribute }]));
    // Tri-state `viewed` — shared primitive. In `'inline'` the datetime editor is always mounted
    // (chrome hidden via CSS); the sd-view text face opens the overlay on click.
    #viewedState = sdViewedInline(this.viewed, () => this.open(), this.disabled);
    /** `true` when `viewed === 'inline'`. */
    isInline = this.#viewedState.isInline;
    /** `true` when `viewed === true` (static view, no editor). */
    isViewed = this.#viewedState.isViewed;
    /** Open the datetime overlay from the inline text face. No-op unless `viewed='inline'`. */
    enterInlineEdit = () => this.#viewedState.enterInlineEdit();
    /** View display template: `sdViewDef` overrides the projected `#sdValue` (unified). */
    viewTemplate = computed(() => this.sdViewDef()?.templateRef ?? this.sdValueTemplate(), ...(ngDevMode ? [{ debugName: "viewTemplate" }] : []));
    inlineError = input(...(ngDevMode ? [undefined, { debugName: "inlineError" }] : []));
    /**
     * Tổng hợp error message để hiển thị trong tooltip khi hideInlineError = true.
     */
    errorMessage = computed(() => {
        void this.#state();
        const errors = this.formControl.errors;
        if (!errors)
            return undefined;
        if (errors['required'])
            return this.#i18n.t('core.form.datetime.required');
        if (errors['matDatepickerMin']) {
            const d = this.resolvedMin();
            return this.#i18n.t('core.form.datetime.min-date', { date: d ? new Date(d).toLocaleDateString('vi-VN') : '' });
        }
        if (errors['matDatepickerMax']) {
            const d = this.resolvedMax();
            return this.#i18n.t('core.form.datetime.max-date', { date: d ? new Date(d).toLocaleDateString('vi-VN') : '' });
        }
        if (errors['date'])
            return errors['date'];
        if (errors['customValidator'])
            return errors['customValidator'];
        if (errors['inlineError'])
            return this.inlineError();
        return undefined;
    }, ...(ngDevMode ? [{ debugName: "errorMessage" }] : []));
    hyperlink = input(...(ngDevMode ? [undefined, { debugName: "hyperlink" }] : []));
    appearanceInput = input(undefined, ...(ngDevMode ? [{ debugName: "appearanceInput", alias: 'appearance' }] : [{ alias: 'appearance' }]));
    appearance = computed(() => this.appearanceInput() ?? this.formConfig?.appearance ?? 'outline', ...(ngDevMode ? [{ debugName: "appearance" }] : []));
    floatLabel = input('auto', ...(ngDevMode ? [{ debugName: "floatLabel" }] : []));
    // Min/max — chấp nhận 'TODAY', Date, hoặc string ISO
    minInput = input(undefined, ...(ngDevMode ? [{ debugName: "minInput", alias: 'min' }] : [{ alias: 'min' }]));
    minDateInput = input(undefined, ...(ngDevMode ? [{ debugName: "minDateInput", alias: 'minDate' }] : [{ alias: 'minDate' }]));
    resolvedMin = computed(() => this.#parseDateBoundary(this.minInput() ?? this.minDateInput()), ...(ngDevMode ? [{ debugName: "resolvedMin" }] : []));
    maxInput = input(undefined, ...(ngDevMode ? [{ debugName: "maxInput", alias: 'max' }] : [{ alias: 'max' }]));
    maxDateInput = input(undefined, ...(ngDevMode ? [{ debugName: "maxDateInput", alias: 'maxDate' }] : [{ alias: 'maxDate' }]));
    resolvedMax = computed(() => this.#parseDateBoundary(this.maxInput() ?? this.maxDateInput()), ...(ngDevMode ? [{ debugName: "resolvedMax" }] : []));
    valueModel = model(undefined, ...(ngDevMode ? [{ debugName: "valueModel", alias: 'model' }] : [{ alias: 'model' }]));
    // viewed-mode: formControl.value là chuỗi display (dd/MM/yyyy HH:mm) nên DatePipe không parse được.
    // Lấy thẳng từ valueModel (nguồn dữ liệu thật) rồi convert sang Date cho DatePipe.
    viewedDate = computed(() => {
        const v = this.valueModel();
        if (v == null || !DateUtilities.isDate(v))
            return null;
        const iso = DateUtilities.toFormat(v, 'yyyy/MM/dd HH:mm:ss');
        if (!iso)
            return null;
        const d = parse(iso, 'yyyy/MM/dd HH:mm:ss', new Date());
        return isValid(d) ? d : null;
    }, ...(ngDevMode ? [{ debugName: "viewedDate" }] : []));
    // ==========================================
    // 4. SIGNAL OUTPUTS
    // ==========================================
    sdChange = output();
    sdFocus = output();
    // ==========================================
    // 5. INTERNAL STATE
    // ==========================================
    isMobileOrTablet = BrowserUtilities.isMobile();
    formControl = new SdFormControl();
    isFocused = false;
    isValid;
    /** State popup — true khi đang mở. */
    pickerOpened = signal(false, ...(ngDevMode ? [{ debugName: "pickerOpened" }] : []));
    #date;
    #subscription = new Subscription();
    #overlayRef = null;
    constructor() {
        // EFFECT 1: Sync model thay đổi từ bên ngoài → cập nhật hiển thị
        effect(() => {
            let val = this.valueModel();
            untracked(() => {
                if (!DateUtilities.isDate(val)) {
                    val = null;
                }
                val = DateUtilities.toFormat(val, 'yyyy/MM/dd HH:mm');
                if (this.#date !== val) {
                    this.#date = val;
                    // Cập nhật formControl với chuỗi hiển thị dd/MM/yyyy HH:mm
                    const fmt = this.showSeconds() ? 'dd/MM/yyyy HH:mm:ss' : 'dd/MM/yyyy HH:mm';
                    const displayStr = DateUtilities.isDate(this.#date)
                        ? DateUtilities.toFormat(this.#date, fmt)
                        : null;
                    this.formControl.setValue(displayStr, { emitEvent: false });
                }
            });
        });
        // EFFECT 2: Sync Disable
        effect(() => {
            if (this.disabled())
                this.formControl.disable({ emitEvent: false });
            else
                this.formControl.enable({ emitEvent: false });
        });
        // EFFECT 3: Update Validators
        effect(() => {
            const req = this.required();
            const inl = this.inlineError();
            untracked(() => {
                const validators = [];
                if (req)
                    validators.push(Validators.required);
                if (inl)
                    validators.push(SdInlineErrorValidator);
                this.formControl.setValidators(validators.length ? validators : null);
                this.formControl.updateValueAndValidity({ emitEvent: false });
            });
        });
    }
    ngOnInit() {
        this.#subscription.add(this.formControl.sdChanges.subscribe(() => {
            this.ref.markForCheck();
        }));
        const formGroup = this.form();
        formGroup?.addControl(this.name(), this.formControl);
    }
    ngOnDestroy() {
        const formGroup = this.form();
        formGroup?.removeControl(this.name());
        this.#subscription.unsubscribe();
        this.#closeOverlay();
    }
    // ==========================================
    // 6. POPUP MANAGEMENT — CDK Overlay
    // ==========================================
    /** Mở popup chọn datetime, neo vào input. */
    open() {
        if (this.formControl.disabled || this.pickerOpened())
            return;
        const origin = this.elementRef.nativeElement;
        const positionStrategy = this.overlay
            .position()
            .flexibleConnectedTo(origin)
            .withPositions([
            { originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'top', offsetY: 4 },
            { originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'bottom', offsetY: -4 },
            { originX: 'end', originY: 'bottom', overlayX: 'end', overlayY: 'top', offsetY: 4 },
            { originX: 'end', originY: 'top', overlayX: 'end', overlayY: 'bottom', offsetY: -4 },
        ])
            .withFlexibleDimensions(false)
            .withPush(true);
        const overlayConfig = new OverlayConfig({
            positionStrategy,
            scrollStrategy: this.overlay.scrollStrategies.reposition(),
            hasBackdrop: true,
            backdropClass: 'sd-datetime-backdrop',
            panelClass: 'sd-datetime-overlay-panel',
        });
        this.#overlayRef = this.overlay.create(overlayConfig);
        const portal = new ComponentPortal(SdDatetimePicker, null, this.injector);
        const ref = this.#overlayRef.attach(portal);
        // Đẩy state hiện tại vào popup
        ref.setInput('initialValue', this.#currentValueAsDate());
        ref.setInput('minDate', this.resolvedMin());
        ref.setInput('maxDate', this.resolvedMax());
        ref.setInput('showSeconds', this.showSeconds());
        // Subscribe events từ popup
        ref.instance.confirmed.subscribe((value) => this.#onPickerConfirm(value));
        ref.instance.cancelled.subscribe(() => this.#onPickerCancel());
        // Đóng khi click backdrop
        this.#overlayRef.backdropClick().subscribe(() => this.#onPickerCancel());
        this.pickerOpened.set(true);
        this.ref.markForCheck();
    }
    /** Đóng popup (public — gọi từ template nếu cần). */
    close() {
        this.#closeOverlay();
    }
    #closeOverlay() {
        if (this.#overlayRef) {
            this.#overlayRef.dispose();
            this.#overlayRef = null;
        }
        if (this.pickerOpened()) {
            this.pickerOpened.set(false);
            this.ref.markForCheck();
        }
    }
    #onPickerConfirm(value) {
        const fmt = this.showSeconds() ? 'yyyy/MM/dd HH:mm:ss' : 'yyyy/MM/dd HH:mm:00';
        // value giờ là native Date (date-fns), không cần .toDate() như Moment.
        const stored = DateUtilities.toFormat(value, fmt);
        if (this.#date !== stored) {
            this.valueModel.set(stored);
            this.sdChange.emit(stored);
        }
        this.#closeOverlay();
    }
    #onPickerCancel() {
        this.#closeOverlay();
    }
    /** Lấy giá trị hiện tại dưới dạng native Date để truyền vào popup. */
    #currentValueAsDate() {
        const v = this.valueModel();
        if (!v || !DateUtilities.isDate(v))
            return null;
        const fmtted = DateUtilities.toFormat(v, 'yyyy/MM/dd HH:mm:ss');
        if (!fmtted)
            return null;
        const parsed = parse(fmtted, 'yyyy/MM/dd HH:mm:ss', new Date());
        return isValid(parsed) ? parsed : null;
    }
    // ==========================================
    // 7. PARSE/VALIDATE HELPERS
    // ==========================================
    #parseDateBoundary(val) {
        if (val === 'TODAY')
            return new Date();
        if (val && DateUtilities.isDate(val))
            return new Date(val);
        return null;
    }
    // ==========================================
    // 8. INPUT EVENT HANDLERS
    // ==========================================
    onFocus = () => {
        this.isFocused = true;
        this.sdFocus.emit();
    };
    onBlur = () => {
        this.isFocused = false;
    };
    onClick = () => {
        if (this.sdViewDef()?.templateRef) {
            if (!this.formControl.disabled && !this.isFocused) {
                this.focus();
            }
        }
    };
    blur = () => {
        this.inputRef()?.nativeElement?.blur();
    };
    focus = () => {
        this.isFocused = true;
        setTimeout(() => {
            this.inputRef()?.nativeElement?.focus();
            this.open();
        }, 100);
    };
    focusInputElement() {
        this.inputRef()?.nativeElement?.focus();
    }
    onKeyDown = (event) => {
        const key = event.keyCode || event.charCode;
        const isShift = key === 16;
        if (event.ctrlKey && (key === 67 || key === 86))
            return true;
        if (((key >= 48 && key <= 57) ||
            key === 8 ||
            key <= 37 ||
            key <= 39 ||
            (key >= 96 && key <= 105) ||
            key === 191 ||
            key === 186 ||
            key === 59) &&
            !isShift) {
            return true;
        }
        return false;
    };
    /**
     * Khi user gõ trực tiếp vào input và rời focus → validate format dd/MM/yyyy HH:mm
     * Hỗ trợ cả format có giây.
     */
    onConfirmInput = (event) => {
        const currentVal = event.target.value;
        const formControl = this.formControl;
        const regexToMinutes = /^([1-9]|([012][0-9])|(3[01]))\/([0]{0,1}[1-9]|1[012])\/\d\d\d\d [012]{0,1}[0-9]:[0-6][0-9]$/g;
        const regexToSecond = /^([1-9]|([012][0-9])|(3[01]))\/([0]{0,1}[1-9]|1[012])\/\d\d\d\d [012]{0,1}[0-9]:[0-6][0-9]:[0-6][0-9]$/g;
        if (currentVal && !(regexToMinutes.test(currentVal) || regexToSecond.test(currentVal))) {
            setTimeout(() => {
                formControl.markAsDirty();
                formControl.markAsTouched();
                formControl.setErrors({ ...formControl.errors, date: this.#i18n.t('core.form.datetime.invalid-format') });
            }, 0);
            return;
        }
        setTimeout(() => {
            formControl.setErrors({ ...formControl.errors, date: null });
            this.formControl.updateValueAndValidity();
        }, 0);
        // Đồng bộ ngược về model nếu hợp lệ.
        // date-fns không có multi-format strict parse như moment, dùng helper parseFirstValid.
        if (currentVal) {
            const parsed = parseFirstValid(currentVal, ['dd/MM/yyyy HH:mm:ss', 'dd/MM/yyyy HH:mm']);
            if (parsed) {
                const fmt = this.showSeconds() ? 'yyyy/MM/dd HH:mm:ss' : 'yyyy/MM/dd HH:mm:00';
                const stored = DateUtilities.toFormat(parsed, fmt);
                if (this.#date !== stored) {
                    this.valueModel.set(stored);
                    this.sdChange.emit(stored);
                }
            }
        }
        else if (this.valueModel()) {
            this.valueModel.set(null);
            this.sdChange.emit(null);
        }
    };
    clear = ($event) => {
        $event?.stopPropagation();
        if (this.formControl.value) {
            this.formControl.setValue(null);
            this.valueModel.set(null);
            this.sdChange.emit(null);
        }
    };
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.24", ngImport: i0, type: SdDatetime, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "20.3.24", type: SdDatetime, isStandalone: true, selector: "sd-datetime", inputs: { autoIdInput: { classPropertyName: "autoIdInput", publicName: "autoId", isSignal: true, isRequired: false, transformFunction: null }, name: { classPropertyName: "name", publicName: "name", isSignal: true, isRequired: false, transformFunction: null }, size: { classPropertyName: "size", publicName: "size", isSignal: true, isRequired: false, transformFunction: null }, form: { classPropertyName: "form", publicName: "form", isSignal: true, isRequired: false, transformFunction: null }, label: { classPropertyName: "label", publicName: "label", isSignal: true, isRequired: false, transformFunction: null }, helperText: { classPropertyName: "helperText", publicName: "helperText", isSignal: true, isRequired: false, transformFunction: null }, placeholder: { classPropertyName: "placeholder", publicName: "placeholder", isSignal: true, isRequired: false, transformFunction: null }, hideInlineError: { classPropertyName: "hideInlineError", publicName: "hideInlineError", isSignal: true, isRequired: false, transformFunction: null }, required: { classPropertyName: "required", publicName: "required", isSignal: true, isRequired: false, transformFunction: null }, disabled: { classPropertyName: "disabled", publicName: "disabled", isSignal: true, isRequired: false, transformFunction: null }, viewed: { classPropertyName: "viewed", publicName: "viewed", isSignal: true, isRequired: false, transformFunction: null }, showSeconds: { classPropertyName: "showSeconds", publicName: "showSeconds", isSignal: true, isRequired: false, transformFunction: null }, clearable: { classPropertyName: "clearable", publicName: "clearable", isSignal: true, isRequired: false, transformFunction: null }, inlineError: { classPropertyName: "inlineError", publicName: "inlineError", isSignal: true, isRequired: false, transformFunction: null }, hyperlink: { classPropertyName: "hyperlink", publicName: "hyperlink", isSignal: true, isRequired: false, transformFunction: null }, appearanceInput: { classPropertyName: "appearanceInput", publicName: "appearance", isSignal: true, isRequired: false, transformFunction: null }, floatLabel: { classPropertyName: "floatLabel", publicName: "floatLabel", isSignal: true, isRequired: false, transformFunction: null }, minInput: { classPropertyName: "minInput", publicName: "min", isSignal: true, isRequired: false, transformFunction: null }, minDateInput: { classPropertyName: "minDateInput", publicName: "minDate", isSignal: true, isRequired: false, transformFunction: null }, maxInput: { classPropertyName: "maxInput", publicName: "max", isSignal: true, isRequired: false, transformFunction: null }, maxDateInput: { classPropertyName: "maxDateInput", publicName: "maxDate", isSignal: true, isRequired: false, transformFunction: null }, valueModel: { classPropertyName: "valueModel", publicName: "model", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { valueModel: "modelChange", sdChange: "sdChange", sdFocus: "sdFocus" }, host: { properties: { "class.sd-bare": "isInline()", "class.sd-viewed": "isViewed() || isInline()", "class.sd-has-label": "!!label()" } }, providers: [
            // DateFnsAdapter inject MAT_DATE_LOCALE; cấp default en-US để parse/format hoạt động.
            { provide: MAT_DATE_LOCALE, useValue: enUS },
            provideDateFnsAdapter(SD_DATETIME_FORMATS),
        ], queries: [{ propertyName: "sdLabelTemplate", first: true, predicate: ["sdLabel"], descendants: true, isSignal: true }, { propertyName: "sdValueTemplate", first: true, predicate: ["sdValue"], descendants: true, isSignal: true }, { propertyName: "sdViewDef", first: true, predicate: SdViewDefDirective, descendants: true, isSignal: true }], viewQueries: [{ propertyName: "inputRef", first: true, predicate: ["input"], descendants: true, isSignal: true }], ngImport: i0, template: "@let lbl = label();\n@let app = appearance();\n@let hideErr = hideInlineError();\n@let errMsg = errorMessage();\n@let hText = helperText();\n@let req = required();\n@let _isInline = isInline();\n@let _bare = _isInline;\n@let _hasValue = !!formControl.value;\n\n@let minD = resolvedMin();\n@let maxD = resolvedMax();\n\n@let vDate = viewedDate();\n@if (isViewed()) {\n  <sd-view\n    [label]=\"lbl\"\n    [labelTemplate]=\"sdLabelTemplate()\"\n    [value]=\"vDate\"\n    [display]=\"vDate | date: (showSeconds() ? 'dd/MM/yyyy HH:mm:ss' : 'dd/MM/yyyy HH:mm')\"\n    [hyperlink]=\"hyperlink()\"\n    [valueTemplate]=\"viewTemplate()\">\n  </sd-view>\n} @else {\n  @if (_isInline) {\n    <!-- why: inline \u2014 sd-view l\u00E0 \"m\u1EB7t\" + trigger; datetime editor render \u1EA9n (.sd-inline-editor) ch\u1EC9 \u0111\u1EC3 m\u1EDF overlay. -->\n    <span class=\"sd-inline-view\" role=\"button\" tabindex=\"0\" (click)=\"enterInlineEdit()\" (keydown.enter)=\"enterInlineEdit()\">\n      <sd-view\n        [label]=\"lbl\"\n        [labelTemplate]=\"sdLabelTemplate()\"\n        [value]=\"vDate\"\n        [display]=\"vDate | date: (showSeconds() ? 'dd/MM/yyyy HH:mm:ss' : 'dd/MM/yyyy HH:mm')\"\n        [hyperlink]=\"hyperlink()\"\n        [valueTemplate]=\"viewTemplate()\">\n      </sd-view>\n      @if (clearable() && _hasValue && !req && !formControl.disabled) {\n        <button type=\"button\" class=\"sd-inline-clear\" (click)=\"clear($event)\" title=\"X\u00F3a\" aria-label=\"X\u00F3a\">\n          <mat-icon>close</mat-icon>\n        </button>\n      }\n    </span>\n  }\n  @if (!app) {\n    <ng-content select=\"[sdLabel]\">\n      @if (lbl) {\n        <sd-label [label]=\"lbl\" [required]=\"req\"></sd-label>\n      }\n    </ng-content>\n  }\n\n  <div\n    class=\"d-flex align-items-center\"\n    [class.sd-inline-editor]=\"_isInline\"\n    [class.c-focused]=\"isFocused\"\n    [class.c-disabled]=\"formControl.disabled\"\n    (click)=\"onClick()\"\n    aria-hidden=\"true\">\n      <mat-form-field\n        class=\"c-form-field-datetime-input\"\n        [class.sd-md]=\"size() === 'md'\"\n        [class.sd-sm]=\"size() === 'sm'\"\n        [class.hide-inline-error]=\"hideErr\"\n        [appearance]=\"app || 'outline'\"\n        [floatLabel]=\"floatLabel()\">\n        @if (app && lbl) {\n          <mat-label style=\"display: inline-block\">\n            <div class=\"d-flex align-items-center gap-4\">\n              <span>{{ lbl }}</span>\n              @if (hText) {\n                <mat-icon [matTooltip]=\"hText\" matTooltipPosition=\"below\">info_outline</mat-icon>\n              }\n            </div>\n          </mat-label>\n        }\n\n        <input\n          aria-hidden=\"true\"\n          [attr.data-autoId]=\"autoId()\"\n          [attr.data-disabled]=\"dataDisabled()\"\n          [attr.data-invalid]=\"dataInvalid()\"\n          [attr.data-empty]=\"dataEmpty()\"\n          [attr.data-value]=\"dataValue()\"\n          [attr.data-required]=\"dataRequired()\"\n          [attr.data-error-message]=\"dataErrorMessage()\"\n          [id]=\"id\"\n          (blur)=\"onConfirmInput($event)\"\n          (keyup.enter)=\"onConfirmInput($event)\"\n          (keydown)=\"onKeyDown($event)\"\n          [autocomplete]=\"id\"\n          autocorrect=\"off\"\n          [formControl]=\"formControl\"\n          [required]=\"req\"\n          [placeholder]=\"placeholder() || lbl || ''\"\n          [min]=\"minD\"\n          [max]=\"maxD\"\n          (focus)=\"onFocus()\"\n          (blur)=\"onBlur()\"\n          #input\n          matInput />\n\n        @if (hideErr && errMsg && formControl.touched) {\n          <mat-icon matSuffix class=\"sd-error-icon\" [matTooltip]=\"errMsg\" matTooltipPosition=\"above\"> error </mat-icon>\n        }\n\n        @if (!hideErr && errMsg && formControl.touched) {\n          <mat-error>{{ errMsg }}</mat-error>\n        }\n\n        @if (formControl.value && !req && !formControl.disabled && !_bare) {\n          <button\n            type=\"button\"\n            class=\"sd-clear-btn sd-hover\"\n            matSuffix\n            (click)=\"clear($event)\"\n            title=\"X\u00F3a\"\n            aria-label=\"X\u00F3a\">\n            <mat-icon>close</mat-icon>\n          </button>\n        }\n\n        <span class=\"cursor-pointer sd-suffix-icon\" (click)=\"!formControl.disabled && open()\" matSuffix\n          ><svg fill=\"currentColor\" viewBox=\"0 0 24 24\" fill=\"currentColor\" focusable=\"false\">\n            <path\n              d=\"M15,13H16.5V15.82L18.94,17.23L18.19,18.53L15,16.69V13M19,8H5V19H9.67C9.24,18.09 9,17.07 9,16A7,7 0 0,1 16,9C17.07,9 18.09,9.24 19,9.67V8M5,21C3.89,21 3,20.1 3,19V5C3,3.89 3.89,3 5,3H6V1H8V3H16V1H18V3H19A2,2 0 0,1 21,5V11.1C22.24,12.36 23,14.09 23,16A7,7 0 0,1 16,23C14.09,23 12.36,22.24 11.1,21H5M16,11.15A4.85,4.85 0 0,0 11.15,16C11.15,18.68 13.32,20.85 16,20.85A4.85,4.85 0 0,0 20.85,16C20.85,13.32 18.68,11.15 16,11.15Z\"></path></svg\n        ></span>\n      </mat-form-field>\n  </div>\n}\n", styles: [".text-primary{color:var(--sd-primary)!important}.bg-primary{background:var(--sd-primary)!important}.border-primary{border-color:var(--sd-primary)!important}.text-primary-light{color:var(--sd-primary-light)!important}.bg-primary-light{background:var(--sd-primary-light)!important}.border-primary-light{border-color:var(--sd-primary-light)!important}.text-primary-dark{color:var(--sd-primary-dark)!important}.bg-primary-dark{background:var(--sd-primary-dark)!important}.border-primary-dark{border-color:var(--sd-primary-dark)!important}.text-info{color:var(--sd-info)!important}.bg-info{background:var(--sd-info)!important}.border-info{border-color:var(--sd-info)!important}.text-info-light{color:var(--sd-info-light)!important}.bg-info-light{background:var(--sd-info-light)!important}.border-info-light{border-color:var(--sd-info-light)!important}.text-info-dark{color:var(--sd-info-dark)!important}.bg-info-dark{background:var(--sd-info-dark)!important}.border-info-dark{border-color:var(--sd-info-dark)!important}.text-success{color:var(--sd-success)!important}.bg-success{background:var(--sd-success)!important}.border-success{border-color:var(--sd-success)!important}.text-success-light{color:var(--sd-success-light)!important}.bg-success-light{background:var(--sd-success-light)!important}.border-success-light{border-color:var(--sd-success-light)!important}.text-success-dark{color:var(--sd-success-dark)!important}.bg-success-dark{background:var(--sd-success-dark)!important}.border-success-dark{border-color:var(--sd-success-dark)!important}.text-warning{color:var(--sd-warning)!important}.bg-warning{background:var(--sd-warning)!important}.border-warning{border-color:var(--sd-warning)!important}.text-warning-light{color:var(--sd-warning-light)!important}.bg-warning-light{background:var(--sd-warning-light)!important}.border-warning-light{border-color:var(--sd-warning-light)!important}.text-warning-dark{color:var(--sd-warning-dark)!important}.bg-warning-dark{background:var(--sd-warning-dark)!important}.border-warning-dark{border-color:var(--sd-warning-dark)!important}.text-error{color:var(--sd-error)!important}.bg-error{background:var(--sd-error)!important}.border-error{border-color:var(--sd-error)!important}.text-error-light{color:var(--sd-error-light)!important}.bg-error-light{background:var(--sd-error-light)!important}.border-error-light{border-color:var(--sd-error-light)!important}.text-error-dark{color:var(--sd-error-dark)!important}.bg-error-dark{background:var(--sd-error-dark)!important}.border-error-dark{border-color:var(--sd-error-dark)!important}.text-secondary{color:var(--sd-secondary)!important}.bg-secondary{background:var(--sd-secondary)!important}.border-secondary{border-color:var(--sd-secondary)!important}.text-secondary-light{color:var(--sd-secondary-light)!important}.bg-secondary-light{background:var(--sd-secondary-light)!important}.border-secondary-light{border-color:var(--sd-secondary-light)!important}.text-secondary-dark{color:var(--sd-secondary-dark)!important}.bg-secondary-dark{background:var(--sd-secondary-dark)!important}.border-secondary-dark{border-color:var(--sd-secondary-dark)!important}.text-light{color:var(--sd-light)!important}.bg-light{background:var(--sd-light)!important}.border-light{border-color:var(--sd-light)!important}.text-dark{color:var(--sd-dark)!important}.bg-dark{background:var(--sd-dark)!important}.border-dark{border-color:var(--sd-dark)!important}.text-black500{color:var(--sd-black500)!important}.bg-black500{background:var(--sd-black500)!important}.border-black500{border-color:var(--sd-black500)!important}.text-black400{color:var(--sd-black400)!important}.bg-black400{background:var(--sd-black400)!important}.border-black400{border-color:var(--sd-black400)!important}.text-black300{color:var(--sd-black300)!important}.bg-black300{background:var(--sd-black300)!important}.border-black300{border-color:var(--sd-black300)!important}.text-black200{color:var(--sd-black200)!important}.bg-black200{background:var(--sd-black200)!important}.border-black200{border-color:var(--sd-black200)!important}.text-black100{color:var(--sd-black100)!important}.bg-black100{background:var(--sd-black100)!important}.border-black100{border-color:var(--sd-black100)!important}.text-white{color:#fff!important}.bg-white{background:#fff!important}.border-white{border-color:#fff!important}.text-black{color:#000!important}.bg-black{background:#000!important}.border-black{border-color:#000!important}:host{display:block}:host(.sd-has-label){padding-top:4px}:host(.sd-viewed){padding-top:0}:host ::ng-deep .mat-mdc-form-field.mat-form-field-appearance-outline.mat-form-field-disabled .mat-mdc-text-field-wrapper{background:var(--sd-black100)}:host ::ng-deep .mat-mdc-form-field input.mat-mdc-input-element:disabled{color:var(--sd-black400)!important}:host ::ng-deep .mat-mdc-form-field .mat-mdc-placeholder-required{color:var(--sd-error)}:host(.sd-bare){position:relative}.sd-inline-view{cursor:pointer;display:inline-flex;align-items:center;width:100%;padding:1px 6px;border-radius:4px;background-color:#0000000a;transition:background-color .15s ease}.sd-inline-view:hover{background-color:#00000014}.sd-inline-view .sd-inline-clear{display:none;align-items:center;margin-left:4px;padding:0;border:0;background:transparent;cursor:pointer;line-height:0;color:var(--sd-text-secondary, #6b7280);transition:color .15s ease}.sd-inline-view .sd-inline-clear mat-icon{font-size:16px;width:16px;height:16px}.sd-inline-view .sd-inline-clear:hover{color:var(--sd-error, #b32626)}.sd-inline-view:hover .sd-inline-clear{display:inline-flex}.sd-inline-editor{position:absolute;inset:0;opacity:0;pointer-events:none}.sd-inline-editor ::ng-deep *{pointer-events:none!important}:host(.sd-bare){display:inline-flex;align-items:center}:host(.sd-bare) ::ng-deep .mat-mdc-form-field{width:auto}:host(.sd-bare) ::ng-deep .mat-mdc-text-field-wrapper{padding:0;background:transparent}:host(.sd-bare) ::ng-deep .mat-mdc-form-field-flex{padding:0;align-items:center}:host(.sd-bare) ::ng-deep .mdc-notched-outline{display:none}:host(.sd-bare) ::ng-deep .mat-mdc-form-field-subscript-wrapper{display:none}:host(.sd-bare) ::ng-deep .mat-mdc-form-field-infix{padding:0;min-height:0;width:auto;border:0;display:inline-flex;align-items:center}\n"], dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "ngmodule", type: FormsModule }, { kind: "directive", type: i1$1.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i1$1.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i1$1.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { kind: "ngmodule", type: ReactiveFormsModule }, { kind: "directive", type: i1$1.FormControlDirective, selector: "[formControl]", inputs: ["formControl", "disabled", "ngModel"], outputs: ["ngModelChange"], exportAs: ["ngForm"] }, { kind: "ngmodule", type: MatInputModule }, { kind: "directive", type: i2.MatInput, selector: "input[matInput], textarea[matInput], select[matNativeControl],      input[matNativeControl], textarea[matNativeControl]", inputs: ["disabled", "id", "placeholder", "name", "required", "type", "errorStateMatcher", "aria-describedby", "value", "readonly", "disabledInteractive"], exportAs: ["matInput"] }, { kind: "component", type: i2.MatFormField, selector: "mat-form-field", inputs: ["hideRequiredMarker", "color", "floatLabel", "appearance", "subscriptSizing", "hintLabel"], exportAs: ["matFormField"] }, { kind: "directive", type: i2.MatLabel, selector: "mat-label" }, { kind: "directive", type: i2.MatError, selector: "mat-error, [matError]", inputs: ["id"] }, { kind: "directive", type: i2.MatSuffix, selector: "[matSuffix], [matIconSuffix], [matTextSuffix]", inputs: ["matTextSuffix"] }, { kind: "ngmodule", type: MatIconModule }, { kind: "component", type: i3.MatIcon, selector: "mat-icon", inputs: ["color", "inline", "svgIcon", "fontSet", "fontIcon"], exportAs: ["matIcon"] }, { kind: "ngmodule", type: MatTooltipModule }, { kind: "directive", type: i4.MatTooltip, selector: "[matTooltip]", inputs: ["matTooltipPosition", "matTooltipPositionAtOrigin", "matTooltipDisabled", "matTooltipShowDelay", "matTooltipHideDelay", "matTooltipTouchGestures", "matTooltip", "matTooltipClass"], exportAs: ["matTooltip"] }, { kind: "ngmodule", type: MatFormFieldModule }, { kind: "component", type: SdLabel, selector: "sd-label", inputs: ["label", "description", "required", "helperText"] }, { kind: "component", type: SdView, selector: "sd-view", inputs: ["label", "value", "display", "hyperlink", "labelTemplate", "valueTemplate", "selectedItems"] }, { kind: "pipe", type: i5.DatePipe, name: "date" }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.24", ngImport: i0, type: SdDatetime, decorators: [{
            type: Component,
            args: [{ selector: 'sd-datetime', changeDetection: ChangeDetectionStrategy.OnPush, host: { '[class.sd-bare]': 'isInline()', '[class.sd-viewed]': 'isViewed() || isInline()', '[class.sd-has-label]': '!!label()' }, providers: [
                        // DateFnsAdapter inject MAT_DATE_LOCALE; cấp default en-US để parse/format hoạt động.
                        { provide: MAT_DATE_LOCALE, useValue: enUS },
                        provideDateFnsAdapter(SD_DATETIME_FORMATS),
                    ], standalone: true, imports: [
                        CommonModule,
                        FormsModule,
                        ReactiveFormsModule,
                        MatInputModule,
                        MatIconModule,
                        MatTooltipModule,
                        MatFormFieldModule,
                        SdLabel,
                        SdView,
                    ], template: "@let lbl = label();\n@let app = appearance();\n@let hideErr = hideInlineError();\n@let errMsg = errorMessage();\n@let hText = helperText();\n@let req = required();\n@let _isInline = isInline();\n@let _bare = _isInline;\n@let _hasValue = !!formControl.value;\n\n@let minD = resolvedMin();\n@let maxD = resolvedMax();\n\n@let vDate = viewedDate();\n@if (isViewed()) {\n  <sd-view\n    [label]=\"lbl\"\n    [labelTemplate]=\"sdLabelTemplate()\"\n    [value]=\"vDate\"\n    [display]=\"vDate | date: (showSeconds() ? 'dd/MM/yyyy HH:mm:ss' : 'dd/MM/yyyy HH:mm')\"\n    [hyperlink]=\"hyperlink()\"\n    [valueTemplate]=\"viewTemplate()\">\n  </sd-view>\n} @else {\n  @if (_isInline) {\n    <!-- why: inline \u2014 sd-view l\u00E0 \"m\u1EB7t\" + trigger; datetime editor render \u1EA9n (.sd-inline-editor) ch\u1EC9 \u0111\u1EC3 m\u1EDF overlay. -->\n    <span class=\"sd-inline-view\" role=\"button\" tabindex=\"0\" (click)=\"enterInlineEdit()\" (keydown.enter)=\"enterInlineEdit()\">\n      <sd-view\n        [label]=\"lbl\"\n        [labelTemplate]=\"sdLabelTemplate()\"\n        [value]=\"vDate\"\n        [display]=\"vDate | date: (showSeconds() ? 'dd/MM/yyyy HH:mm:ss' : 'dd/MM/yyyy HH:mm')\"\n        [hyperlink]=\"hyperlink()\"\n        [valueTemplate]=\"viewTemplate()\">\n      </sd-view>\n      @if (clearable() && _hasValue && !req && !formControl.disabled) {\n        <button type=\"button\" class=\"sd-inline-clear\" (click)=\"clear($event)\" title=\"X\u00F3a\" aria-label=\"X\u00F3a\">\n          <mat-icon>close</mat-icon>\n        </button>\n      }\n    </span>\n  }\n  @if (!app) {\n    <ng-content select=\"[sdLabel]\">\n      @if (lbl) {\n        <sd-label [label]=\"lbl\" [required]=\"req\"></sd-label>\n      }\n    </ng-content>\n  }\n\n  <div\n    class=\"d-flex align-items-center\"\n    [class.sd-inline-editor]=\"_isInline\"\n    [class.c-focused]=\"isFocused\"\n    [class.c-disabled]=\"formControl.disabled\"\n    (click)=\"onClick()\"\n    aria-hidden=\"true\">\n      <mat-form-field\n        class=\"c-form-field-datetime-input\"\n        [class.sd-md]=\"size() === 'md'\"\n        [class.sd-sm]=\"size() === 'sm'\"\n        [class.hide-inline-error]=\"hideErr\"\n        [appearance]=\"app || 'outline'\"\n        [floatLabel]=\"floatLabel()\">\n        @if (app && lbl) {\n          <mat-label style=\"display: inline-block\">\n            <div class=\"d-flex align-items-center gap-4\">\n              <span>{{ lbl }}</span>\n              @if (hText) {\n                <mat-icon [matTooltip]=\"hText\" matTooltipPosition=\"below\">info_outline</mat-icon>\n              }\n            </div>\n          </mat-label>\n        }\n\n        <input\n          aria-hidden=\"true\"\n          [attr.data-autoId]=\"autoId()\"\n          [attr.data-disabled]=\"dataDisabled()\"\n          [attr.data-invalid]=\"dataInvalid()\"\n          [attr.data-empty]=\"dataEmpty()\"\n          [attr.data-value]=\"dataValue()\"\n          [attr.data-required]=\"dataRequired()\"\n          [attr.data-error-message]=\"dataErrorMessage()\"\n          [id]=\"id\"\n          (blur)=\"onConfirmInput($event)\"\n          (keyup.enter)=\"onConfirmInput($event)\"\n          (keydown)=\"onKeyDown($event)\"\n          [autocomplete]=\"id\"\n          autocorrect=\"off\"\n          [formControl]=\"formControl\"\n          [required]=\"req\"\n          [placeholder]=\"placeholder() || lbl || ''\"\n          [min]=\"minD\"\n          [max]=\"maxD\"\n          (focus)=\"onFocus()\"\n          (blur)=\"onBlur()\"\n          #input\n          matInput />\n\n        @if (hideErr && errMsg && formControl.touched) {\n          <mat-icon matSuffix class=\"sd-error-icon\" [matTooltip]=\"errMsg\" matTooltipPosition=\"above\"> error </mat-icon>\n        }\n\n        @if (!hideErr && errMsg && formControl.touched) {\n          <mat-error>{{ errMsg }}</mat-error>\n        }\n\n        @if (formControl.value && !req && !formControl.disabled && !_bare) {\n          <button\n            type=\"button\"\n            class=\"sd-clear-btn sd-hover\"\n            matSuffix\n            (click)=\"clear($event)\"\n            title=\"X\u00F3a\"\n            aria-label=\"X\u00F3a\">\n            <mat-icon>close</mat-icon>\n          </button>\n        }\n\n        <span class=\"cursor-pointer sd-suffix-icon\" (click)=\"!formControl.disabled && open()\" matSuffix\n          ><svg fill=\"currentColor\" viewBox=\"0 0 24 24\" fill=\"currentColor\" focusable=\"false\">\n            <path\n              d=\"M15,13H16.5V15.82L18.94,17.23L18.19,18.53L15,16.69V13M19,8H5V19H9.67C9.24,18.09 9,17.07 9,16A7,7 0 0,1 16,9C17.07,9 18.09,9.24 19,9.67V8M5,21C3.89,21 3,20.1 3,19V5C3,3.89 3.89,3 5,3H6V1H8V3H16V1H18V3H19A2,2 0 0,1 21,5V11.1C22.24,12.36 23,14.09 23,16A7,7 0 0,1 16,23C14.09,23 12.36,22.24 11.1,21H5M16,11.15A4.85,4.85 0 0,0 11.15,16C11.15,18.68 13.32,20.85 16,20.85A4.85,4.85 0 0,0 20.85,16C20.85,13.32 18.68,11.15 16,11.15Z\"></path></svg\n        ></span>\n      </mat-form-field>\n  </div>\n}\n", styles: [".text-primary{color:var(--sd-primary)!important}.bg-primary{background:var(--sd-primary)!important}.border-primary{border-color:var(--sd-primary)!important}.text-primary-light{color:var(--sd-primary-light)!important}.bg-primary-light{background:var(--sd-primary-light)!important}.border-primary-light{border-color:var(--sd-primary-light)!important}.text-primary-dark{color:var(--sd-primary-dark)!important}.bg-primary-dark{background:var(--sd-primary-dark)!important}.border-primary-dark{border-color:var(--sd-primary-dark)!important}.text-info{color:var(--sd-info)!important}.bg-info{background:var(--sd-info)!important}.border-info{border-color:var(--sd-info)!important}.text-info-light{color:var(--sd-info-light)!important}.bg-info-light{background:var(--sd-info-light)!important}.border-info-light{border-color:var(--sd-info-light)!important}.text-info-dark{color:var(--sd-info-dark)!important}.bg-info-dark{background:var(--sd-info-dark)!important}.border-info-dark{border-color:var(--sd-info-dark)!important}.text-success{color:var(--sd-success)!important}.bg-success{background:var(--sd-success)!important}.border-success{border-color:var(--sd-success)!important}.text-success-light{color:var(--sd-success-light)!important}.bg-success-light{background:var(--sd-success-light)!important}.border-success-light{border-color:var(--sd-success-light)!important}.text-success-dark{color:var(--sd-success-dark)!important}.bg-success-dark{background:var(--sd-success-dark)!important}.border-success-dark{border-color:var(--sd-success-dark)!important}.text-warning{color:var(--sd-warning)!important}.bg-warning{background:var(--sd-warning)!important}.border-warning{border-color:var(--sd-warning)!important}.text-warning-light{color:var(--sd-warning-light)!important}.bg-warning-light{background:var(--sd-warning-light)!important}.border-warning-light{border-color:var(--sd-warning-light)!important}.text-warning-dark{color:var(--sd-warning-dark)!important}.bg-warning-dark{background:var(--sd-warning-dark)!important}.border-warning-dark{border-color:var(--sd-warning-dark)!important}.text-error{color:var(--sd-error)!important}.bg-error{background:var(--sd-error)!important}.border-error{border-color:var(--sd-error)!important}.text-error-light{color:var(--sd-error-light)!important}.bg-error-light{background:var(--sd-error-light)!important}.border-error-light{border-color:var(--sd-error-light)!important}.text-error-dark{color:var(--sd-error-dark)!important}.bg-error-dark{background:var(--sd-error-dark)!important}.border-error-dark{border-color:var(--sd-error-dark)!important}.text-secondary{color:var(--sd-secondary)!important}.bg-secondary{background:var(--sd-secondary)!important}.border-secondary{border-color:var(--sd-secondary)!important}.text-secondary-light{color:var(--sd-secondary-light)!important}.bg-secondary-light{background:var(--sd-secondary-light)!important}.border-secondary-light{border-color:var(--sd-secondary-light)!important}.text-secondary-dark{color:var(--sd-secondary-dark)!important}.bg-secondary-dark{background:var(--sd-secondary-dark)!important}.border-secondary-dark{border-color:var(--sd-secondary-dark)!important}.text-light{color:var(--sd-light)!important}.bg-light{background:var(--sd-light)!important}.border-light{border-color:var(--sd-light)!important}.text-dark{color:var(--sd-dark)!important}.bg-dark{background:var(--sd-dark)!important}.border-dark{border-color:var(--sd-dark)!important}.text-black500{color:var(--sd-black500)!important}.bg-black500{background:var(--sd-black500)!important}.border-black500{border-color:var(--sd-black500)!important}.text-black400{color:var(--sd-black400)!important}.bg-black400{background:var(--sd-black400)!important}.border-black400{border-color:var(--sd-black400)!important}.text-black300{color:var(--sd-black300)!important}.bg-black300{background:var(--sd-black300)!important}.border-black300{border-color:var(--sd-black300)!important}.text-black200{color:var(--sd-black200)!important}.bg-black200{background:var(--sd-black200)!important}.border-black200{border-color:var(--sd-black200)!important}.text-black100{color:var(--sd-black100)!important}.bg-black100{background:var(--sd-black100)!important}.border-black100{border-color:var(--sd-black100)!important}.text-white{color:#fff!important}.bg-white{background:#fff!important}.border-white{border-color:#fff!important}.text-black{color:#000!important}.bg-black{background:#000!important}.border-black{border-color:#000!important}:host{display:block}:host(.sd-has-label){padding-top:4px}:host(.sd-viewed){padding-top:0}:host ::ng-deep .mat-mdc-form-field.mat-form-field-appearance-outline.mat-form-field-disabled .mat-mdc-text-field-wrapper{background:var(--sd-black100)}:host ::ng-deep .mat-mdc-form-field input.mat-mdc-input-element:disabled{color:var(--sd-black400)!important}:host ::ng-deep .mat-mdc-form-field .mat-mdc-placeholder-required{color:var(--sd-error)}:host(.sd-bare){position:relative}.sd-inline-view{cursor:pointer;display:inline-flex;align-items:center;width:100%;padding:1px 6px;border-radius:4px;background-color:#0000000a;transition:background-color .15s ease}.sd-inline-view:hover{background-color:#00000014}.sd-inline-view .sd-inline-clear{display:none;align-items:center;margin-left:4px;padding:0;border:0;background:transparent;cursor:pointer;line-height:0;color:var(--sd-text-secondary, #6b7280);transition:color .15s ease}.sd-inline-view .sd-inline-clear mat-icon{font-size:16px;width:16px;height:16px}.sd-inline-view .sd-inline-clear:hover{color:var(--sd-error, #b32626)}.sd-inline-view:hover .sd-inline-clear{display:inline-flex}.sd-inline-editor{position:absolute;inset:0;opacity:0;pointer-events:none}.sd-inline-editor ::ng-deep *{pointer-events:none!important}:host(.sd-bare){display:inline-flex;align-items:center}:host(.sd-bare) ::ng-deep .mat-mdc-form-field{width:auto}:host(.sd-bare) ::ng-deep .mat-mdc-text-field-wrapper{padding:0;background:transparent}:host(.sd-bare) ::ng-deep .mat-mdc-form-field-flex{padding:0;align-items:center}:host(.sd-bare) ::ng-deep .mdc-notched-outline{display:none}:host(.sd-bare) ::ng-deep .mat-mdc-form-field-subscript-wrapper{display:none}:host(.sd-bare) ::ng-deep .mat-mdc-form-field-infix{padding:0;min-height:0;width:auto;border:0;display:inline-flex;align-items:center}\n"] }]
        }], ctorParameters: () => [], propDecorators: { inputRef: [{ type: i0.ViewChild, args: ['input', { isSignal: true }] }], sdLabelTemplate: [{ type: i0.ContentChild, args: ['sdLabel', { isSignal: true }] }], sdValueTemplate: [{ type: i0.ContentChild, args: ['sdValue', { isSignal: true }] }], sdViewDef: [{ type: i0.ContentChild, args: [i0.forwardRef(() => SdViewDefDirective), { isSignal: true }] }], autoIdInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "autoId", required: false }] }], name: [{ type: i0.Input, args: [{ isSignal: true, alias: "name", required: false }] }], size: [{ type: i0.Input, args: [{ isSignal: true, alias: "size", required: false }] }], form: [{ type: i0.Input, args: [{ isSignal: true, alias: "form", required: false }] }], label: [{ type: i0.Input, args: [{ isSignal: true, alias: "label", required: false }] }], helperText: [{ type: i0.Input, args: [{ isSignal: true, alias: "helperText", required: false }] }], placeholder: [{ type: i0.Input, args: [{ isSignal: true, alias: "placeholder", required: false }] }], hideInlineError: [{ type: i0.Input, args: [{ isSignal: true, alias: "hideInlineError", required: false }] }], required: [{ type: i0.Input, args: [{ isSignal: true, alias: "required", required: false }] }], disabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "disabled", required: false }] }], viewed: [{ type: i0.Input, args: [{ isSignal: true, alias: "viewed", required: false }] }], showSeconds: [{ type: i0.Input, args: [{ isSignal: true, alias: "showSeconds", required: false }] }], clearable: [{ type: i0.Input, args: [{ isSignal: true, alias: "clearable", required: false }] }], inlineError: [{ type: i0.Input, args: [{ isSignal: true, alias: "inlineError", required: false }] }], hyperlink: [{ type: i0.Input, args: [{ isSignal: true, alias: "hyperlink", required: false }] }], appearanceInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "appearance", required: false }] }], floatLabel: [{ type: i0.Input, args: [{ isSignal: true, alias: "floatLabel", required: false }] }], minInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "min", required: false }] }], minDateInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "minDate", required: false }] }], maxInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "max", required: false }] }], maxDateInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "maxDate", required: false }] }], valueModel: [{ type: i0.Input, args: [{ isSignal: true, alias: "model", required: false }] }, { type: i0.Output, args: ["modelChange"] }], sdChange: [{ type: i0.Output, args: ["sdChange"] }], sdFocus: [{ type: i0.Output, args: ["sdFocus"] }] } });

/**
 * Generated bundle index. Do not edit.
 */

export { SdDatetime };
//# sourceMappingURL=sdcorejs-angular-forms-datetime.mjs.map
