import { CommonModule } from '@angular/common';
import { Component, inject, Input } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { IonButton, IonDatetime, IonModal } from '@ionic/angular/standalone';
import { I18nService } from '../../../services/i18n';
import { PresetService } from '../../../services/presets';
import * as i0 from "@angular/core";
import * as i1 from "@angular/forms";
const DATE_INPUT_I18N = {
    es: { selectDate: 'Seleccionar fecha', selectTime: 'Seleccionar hora' },
    en: { selectDate: 'Select date', selectTime: 'Select time' },
};
/**
 * val-date-input
 *
 * A date picker input integrated with Angular forms, using Ionic's datetime component.
 *
 * Cuando el control no tiene valor, muestra un botón con el texto `placeholder`
 * (o un default i18n "Seleccionar fecha") en vez de renderizar en blanco —
 * `ion-datetime-button` no soporta placeholder, por eso usamos un trigger propio.
 *
 * @example
 * <val-date-input [props]="{ control: myControl, hint: 'Select a date' }"></val-date-input>
 *
 * @input props: DateInputMetadata - Configuration for the date input (form control, hint, etc.)
 */
export class DateInputComponent {
    constructor() {
        this.i18n = inject(I18nService);
        this.presets = inject(PresetService);
        /**
         * Input configuration object. Values here override preset values.
         * @type {DateInputMetadata}
         * @property control - The Angular FormControl for the date input.
         * @property hint - The hint text for the input.
         */
        this.props = {};
        /**
         * Resolved props after merging preset + explicit props.
         */
        this.resolvedProps = {};
        // Auto-registro de defaults i18n (anti key-faltante → anti storm de CD).
        if (!this.i18n.hasNamespace('DateInput')) {
            this.i18n.registerContent('DateInput', DATE_INPUT_I18N);
        }
    }
    /** Done button text - from props or i18n default */
    get doneText() {
        return this.resolvedProps?.doneText || this.i18n.t('ok');
    }
    /** Cancel button text - from props or i18n default */
    get cancelText() {
        return this.resolvedProps?.cancelText || this.i18n.t('cancel');
    }
    /** Presentación del datetime (default: date). */
    get presentation() {
        return this.resolvedProps?.presentation || 'date';
    }
    /** Locale del datetime — honra el prop del consumer (default es-ES). */
    get datetimeLocale() {
        return this.resolvedProps?.locale || 'es-ES';
    }
    /** Primer día de la semana — honra el prop del consumer (default lunes). */
    get firstDayOfWeek() {
        return this.resolvedProps?.firstDayOfWeek ?? 1;
    }
    /**
     * Opciones de formato para `ion-datetime` (binding, NO string). Honra el prop
     * del consumer y cae a un default sensato (date medium / time short).
     */
    get datetimeFormatOptions() {
        return (this.resolvedProps?.formatOptions || {
            date: { dateStyle: 'medium' },
            time: { timeStyle: 'short' },
        });
    }
    /** Texto del trigger cuando NO hay valor (placeholder explícito o default i18n). */
    get placeholderText() {
        if (this.resolvedProps?.placeholder)
            return this.resolvedProps.placeholder;
        this.i18n.lang(); // reactividad ante cambio de idioma
        return this.presentation === 'time'
            ? this.i18n.t('selectTime', 'DateInput')
            : this.i18n.t('selectDate', 'DateInput');
    }
    /** Id del trigger/datetime — estable; se garantiza no vacío en resolveProps. */
    get triggerId() {
        return this.resolvedProps?.token || '';
    }
    /** Valor formateado del control para mostrar en el trigger ('' si vacío). */
    get displayValue() {
        const raw = this.resolvedProps?.control?.value;
        if (!raw)
            return '';
        const d = new Date(raw);
        if (isNaN(d.getTime()))
            return String(raw);
        this.i18n.lang(); // reactividad
        const locale = this.datetimeLocale;
        try {
            switch (this.presentation) {
                case 'time':
                    return new Intl.DateTimeFormat(locale, { timeStyle: 'short' }).format(d);
                case 'month':
                case 'month-year':
                    return new Intl.DateTimeFormat(locale, { month: 'long', year: 'numeric' }).format(d);
                case 'year':
                    return new Intl.DateTimeFormat(locale, { year: 'numeric' }).format(d);
                case 'date-time':
                    return new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short' }).format(d);
                default:
                    return new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }).format(d);
            }
        }
        catch {
            return String(raw);
        }
    }
    ngOnInit() {
        this.resolveProps();
        this.applyDefaultValue();
    }
    ngOnChanges(changes) {
        if (changes['preset'] || changes['props']) {
            this.resolveProps();
            this.applyDefaultValue();
        }
    }
    /**
     * Merge preset configuration with explicit props.
     * Explicit props take precedence over preset values.
     */
    resolveProps() {
        const presetProps = this.preset ? this.presets.get('dateInput', this.preset) : {};
        this.resolvedProps = {
            ...presetProps,
            ...this.props,
        };
        // Garantizar un token (id) no vacío: lo necesitan [trigger] del modal y el
        // [id] del ion-datetime para vincularse. Si el consumer no lo pasó, generamos uno.
        if (!this.resolvedProps.token) {
            this.resolvedProps.token = `val-date-${Math.random().toString(36).slice(2, 10)}`;
        }
    }
    applyDefaultValue() {
        if (!this.resolvedProps.control)
            return;
        // Only apply if withDefault or value is set
        if (!this.resolvedProps.withDefault && !this.resolvedProps.value)
            return;
        let defaultValue = null;
        // Explicit value takes precedence
        if (this.resolvedProps.value) {
            defaultValue = new Date(this.resolvedProps.value).toISOString();
        }
        else if (typeof this.resolvedProps.withDefault === 'string') {
            defaultValue = new Date(this.resolvedProps.withDefault).toISOString();
        }
        else if (this.resolvedProps.withDefault === true) {
            defaultValue = new Date().toISOString();
        }
        if (defaultValue) {
            this.resolvedProps.control.setValue(defaultValue);
            this.resolvedProps.control.markAsPristine();
            this.resolvedProps.control.updateValueAndValidity();
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: DateInputComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "18.2.14", type: DateInputComponent, isStandalone: true, selector: "val-date-input", inputs: { preset: "preset", props: "props" }, usesOnChanges: true, ngImport: i0, template: `
    <div class="button-container">
      <!-- Trigger propio (reemplaza ion-datetime-button, que renderiza en blanco
           cuando el control no tiene valor). Muestra el valor formateado o el
           placeholder, y abre el modal vía [trigger]. -->
      <ion-button
        [id]="triggerId"
        class="action date-trigger"
        fill="outline"
        color="medium"
        [class.is-placeholder]="!displayValue"
      >
        {{ displayValue || placeholderText }}
      </ion-button>
    </div>
    <ion-modal
      [trigger]="triggerId"
      [keepContentsMounted]="true"
      class="val-date-modal"
    >
      <ng-template>
        <ion-datetime
          [formControl]="resolvedProps.control"
          [id]="resolvedProps.token"
          [presentation]="presentation"
          [locale]="datetimeLocale"
          [firstDayOfWeek]="firstDayOfWeek"
          [showDefaultButtons]="true"
          [doneText]="doneText"
          [cancelText]="cancelText"
          [formatOptions]="datetimeFormatOptions"
        >
          <span slot="title">{{ resolvedProps.hint }}</span>
        </ion-datetime>
      </ng-template>
    </ion-modal>
  `, isInline: true, styles: ["@charset \"UTF-8\";:root{--val-container-sm: 540px;--val-container-md: 720px;--val-container-lg: 880px;--val-container-xl: 1100px;--val-container-padding: 16px;--ion-color-primary: #7026df;--ion-color-primary-rgb: 112, 38, 223;--ion-color-primary-contrast: #ffffff;--ion-color-primary-contrast-rgb: 255, 255, 255;--ion-color-primary-shade: #6321c4;--ion-color-primary-tint: #7e3ce2;--ion-color-secondary: #e2ccff;--ion-color-secondary-rgb: 226, 204, 255;--ion-color-secondary-contrast: #000000;--ion-color-secondary-contrast-rgb: 0, 0, 0;--ion-color-secondary-shade: #c7b4e0;--ion-color-secondary-tint: #e5d1ff;--ion-color-texti: #354c69;--ion-color-texti-rgb: 53, 76, 105;--ion-color-texti-contrast: #ffffff;--ion-color-texti-contrast-rgb: 255, 255, 255;--ion-color-texti-shade: #2f435c;--ion-color-texti-tint: #495e78;--ion-color-darki: #090f1b;--ion-color-darki-rgb: 9, 15, 27;--ion-color-darki-contrast: #ffffff;--ion-color-darki-contrast-rgb: 255, 255, 255;--ion-color-darki-shade: #080d18;--ion-color-darki-tint: #222732;--ion-color-medium: #9e9e9e;--ion-color-medium-rgb: 158, 158, 158;--ion-color-medium-contrast: #000000;--ion-color-medium-contrast-rgb: 0, 0, 0;--ion-color-medium-shade: #8b8b8b;--ion-color-medium-tint: #a8a8a8;--swiper-pagination-color: var(--ion-color-primary);--swiper-navigation-color: var(--ion-color-primary);--swiper-pagination-bullet-inactive-color: var(--ion-color-medium)}body.dark,html.ion-palette-dark,body[data-theme=dark]{--ion-color-texti: #8fc1ff;--ion-color-texti-rgb: 143, 193, 255;--ion-color-texti-contrast: #000000;--ion-color-texti-contrast-rgb: 0, 0, 0;--ion-color-texti-shade: #7eaae0;--ion-color-texti-tint: #9ac7ff;--ion-color-darki: #ffffff;--ion-color-darki-rgb: 255, 255, 255;--ion-color-darki-contrast: #000000;--ion-color-darki-contrast-rgb: 0, 0, 0;--ion-color-darki-shade: #e0e0e0;--ion-color-darki-tint: #ffffff;--ion-color-primary: #8f49f8;--ion-color-primary-rgb: 143, 73, 248;--ion-color-primary-contrast: #ffffff;--ion-color-primary-contrast-rgb: 255, 255, 255;--ion-color-primary-shade: #7e40da;--ion-color-primary-tint: #9a5bf9}.ion-color-texti{--ion-color-base: var(--ion-color-texti);--ion-color-base-rgb: var(--ion-color-texti-rgb);--ion-color-contrast: var(--ion-color-texti-contrast);--ion-color-contrast-rgb: var(--ion-color-texti-contrast-rgb);--ion-color-shade: var(--ion-color-texti-shade);--ion-color-tint: var(--ion-color-texti-tint)}.ion-color-darki{--ion-color-base: var(--ion-color-darki);--ion-color-base-rgb: var(--ion-color-darki-rgb);--ion-color-contrast: var(--ion-color-darki-contrast);--ion-color-contrast-rgb: var(--ion-color-darki-contrast-rgb);--ion-color-shade: var(--ion-color-darki-shade);--ion-color-tint: var(--ion-color-darki-tint)}.section{margin-top:1rem}.input{margin:var(--val-form-field-gap, .5rem) 0}@media (min-width: 768px){.input{margin:var(--val-form-field-gap, .75rem) 0}}.submit-actions--sticky{position:sticky;bottom:0;z-index:1;background:var(--ion-background-color);border-top:1px solid var(--ion-color-step-150, rgba(0, 0, 0, .08));padding:.75rem 0 calc(.75rem + env(safe-area-inset-bottom))}.field-description{display:block;font-size:.75rem;color:var(--ion-color-dark);margin-bottom:.25rem;line-height:1.4}.button-container{display:flex;flex-direction:column;align-items:flex-start}.action{margin-top:.25rem}ion-modal.val-date-modal{--width: fit-content;--min-width: pxToRem(320);--height: fit-content;--border-radius: pxToRem(16);--box-shadow: 0 pxToRem(12) pxToRem(48) rgba(0, 0, 0, .25)}ion-modal.val-date-modal ion-datetime{margin:0 auto}\n"], dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "ngmodule", type: ReactiveFormsModule }, { kind: "directive", type: i1.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i1.FormControlDirective, selector: "[formControl]", inputs: ["formControl", "disabled", "ngModel"], outputs: ["ngModelChange"], exportAs: ["ngForm"] }, { kind: "component", type: IonButton, selector: "ion-button", inputs: ["buttonType", "color", "disabled", "download", "expand", "fill", "form", "href", "mode", "rel", "routerAnimation", "routerDirection", "shape", "size", "strong", "target", "type"] }, { kind: "component", type: IonDatetime, selector: "ion-datetime", inputs: ["cancelText", "clearText", "color", "dayValues", "disabled", "doneText", "firstDayOfWeek", "formatOptions", "highlightedDates", "hourCycle", "hourValues", "isDateEnabled", "locale", "max", "min", "minuteValues", "mode", "monthValues", "multiple", "name", "preferWheel", "presentation", "readonly", "showAdjacentDays", "showClearButton", "showDefaultButtons", "showDefaultTimeLabel", "showDefaultTitle", "size", "titleSelectedDatesFormatter", "value", "yearValues"] }, { kind: "component", type: IonModal, selector: "ion-modal" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: DateInputComponent, decorators: [{
            type: Component,
            args: [{ selector: 'val-date-input', standalone: true, imports: [CommonModule, ReactiveFormsModule, IonButton, IonDatetime, IonModal], template: `
    <div class="button-container">
      <!-- Trigger propio (reemplaza ion-datetime-button, que renderiza en blanco
           cuando el control no tiene valor). Muestra el valor formateado o el
           placeholder, y abre el modal vía [trigger]. -->
      <ion-button
        [id]="triggerId"
        class="action date-trigger"
        fill="outline"
        color="medium"
        [class.is-placeholder]="!displayValue"
      >
        {{ displayValue || placeholderText }}
      </ion-button>
    </div>
    <ion-modal
      [trigger]="triggerId"
      [keepContentsMounted]="true"
      class="val-date-modal"
    >
      <ng-template>
        <ion-datetime
          [formControl]="resolvedProps.control"
          [id]="resolvedProps.token"
          [presentation]="presentation"
          [locale]="datetimeLocale"
          [firstDayOfWeek]="firstDayOfWeek"
          [showDefaultButtons]="true"
          [doneText]="doneText"
          [cancelText]="cancelText"
          [formatOptions]="datetimeFormatOptions"
        >
          <span slot="title">{{ resolvedProps.hint }}</span>
        </ion-datetime>
      </ng-template>
    </ion-modal>
  `, styles: ["@charset \"UTF-8\";:root{--val-container-sm: 540px;--val-container-md: 720px;--val-container-lg: 880px;--val-container-xl: 1100px;--val-container-padding: 16px;--ion-color-primary: #7026df;--ion-color-primary-rgb: 112, 38, 223;--ion-color-primary-contrast: #ffffff;--ion-color-primary-contrast-rgb: 255, 255, 255;--ion-color-primary-shade: #6321c4;--ion-color-primary-tint: #7e3ce2;--ion-color-secondary: #e2ccff;--ion-color-secondary-rgb: 226, 204, 255;--ion-color-secondary-contrast: #000000;--ion-color-secondary-contrast-rgb: 0, 0, 0;--ion-color-secondary-shade: #c7b4e0;--ion-color-secondary-tint: #e5d1ff;--ion-color-texti: #354c69;--ion-color-texti-rgb: 53, 76, 105;--ion-color-texti-contrast: #ffffff;--ion-color-texti-contrast-rgb: 255, 255, 255;--ion-color-texti-shade: #2f435c;--ion-color-texti-tint: #495e78;--ion-color-darki: #090f1b;--ion-color-darki-rgb: 9, 15, 27;--ion-color-darki-contrast: #ffffff;--ion-color-darki-contrast-rgb: 255, 255, 255;--ion-color-darki-shade: #080d18;--ion-color-darki-tint: #222732;--ion-color-medium: #9e9e9e;--ion-color-medium-rgb: 158, 158, 158;--ion-color-medium-contrast: #000000;--ion-color-medium-contrast-rgb: 0, 0, 0;--ion-color-medium-shade: #8b8b8b;--ion-color-medium-tint: #a8a8a8;--swiper-pagination-color: var(--ion-color-primary);--swiper-navigation-color: var(--ion-color-primary);--swiper-pagination-bullet-inactive-color: var(--ion-color-medium)}body.dark,html.ion-palette-dark,body[data-theme=dark]{--ion-color-texti: #8fc1ff;--ion-color-texti-rgb: 143, 193, 255;--ion-color-texti-contrast: #000000;--ion-color-texti-contrast-rgb: 0, 0, 0;--ion-color-texti-shade: #7eaae0;--ion-color-texti-tint: #9ac7ff;--ion-color-darki: #ffffff;--ion-color-darki-rgb: 255, 255, 255;--ion-color-darki-contrast: #000000;--ion-color-darki-contrast-rgb: 0, 0, 0;--ion-color-darki-shade: #e0e0e0;--ion-color-darki-tint: #ffffff;--ion-color-primary: #8f49f8;--ion-color-primary-rgb: 143, 73, 248;--ion-color-primary-contrast: #ffffff;--ion-color-primary-contrast-rgb: 255, 255, 255;--ion-color-primary-shade: #7e40da;--ion-color-primary-tint: #9a5bf9}.ion-color-texti{--ion-color-base: var(--ion-color-texti);--ion-color-base-rgb: var(--ion-color-texti-rgb);--ion-color-contrast: var(--ion-color-texti-contrast);--ion-color-contrast-rgb: var(--ion-color-texti-contrast-rgb);--ion-color-shade: var(--ion-color-texti-shade);--ion-color-tint: var(--ion-color-texti-tint)}.ion-color-darki{--ion-color-base: var(--ion-color-darki);--ion-color-base-rgb: var(--ion-color-darki-rgb);--ion-color-contrast: var(--ion-color-darki-contrast);--ion-color-contrast-rgb: var(--ion-color-darki-contrast-rgb);--ion-color-shade: var(--ion-color-darki-shade);--ion-color-tint: var(--ion-color-darki-tint)}.section{margin-top:1rem}.input{margin:var(--val-form-field-gap, .5rem) 0}@media (min-width: 768px){.input{margin:var(--val-form-field-gap, .75rem) 0}}.submit-actions--sticky{position:sticky;bottom:0;z-index:1;background:var(--ion-background-color);border-top:1px solid var(--ion-color-step-150, rgba(0, 0, 0, .08));padding:.75rem 0 calc(.75rem + env(safe-area-inset-bottom))}.field-description{display:block;font-size:.75rem;color:var(--ion-color-dark);margin-bottom:.25rem;line-height:1.4}.button-container{display:flex;flex-direction:column;align-items:flex-start}.action{margin-top:.25rem}ion-modal.val-date-modal{--width: fit-content;--min-width: pxToRem(320);--height: fit-content;--border-radius: pxToRem(16);--box-shadow: 0 pxToRem(12) pxToRem(48) rgba(0, 0, 0, .25)}ion-modal.val-date-modal ion-datetime{margin:0 auto}\n"] }]
        }], ctorParameters: () => [], propDecorators: { preset: [{
                type: Input
            }], props: [{
                type: Input
            }] } });
//# sourceMappingURL=data:application/json;base64, 