import * as i0 from '@angular/core';
import { inject, input, signal, model, viewChild, forwardRef, ChangeDetectionStrategy, Component } from '@angular/core';
import { UploadArea, UploadTriggerDirective } from '@ngstarter-ui/components/upload';
import { ProgressBar } from '@ngstarter-ui/components/progress-bar';
import { Button } from '@ngstarter-ui/components/button';
import { Icon } from '@ngstarter-ui/components/icon';
import { C as ContentBuilderStore, a as CONTENT_BUILDER, b as CONTENT_EDITOR_BLOCK } from './ngstarter-ui-components-content-editor-ngstarter-ui-components-content-editor-DNLTNGYa.mjs';
import { FormField, Label } from '@ngstarter-ui/components/form-field';
import { Input } from '@ngstarter-ui/components/input';
import * as i1 from '@angular/forms';
import { FormsModule } from '@angular/forms';
import { ResizableContainer } from '@ngstarter-ui/components/resizable-container';

class VideoBlockComponent {
    _store = inject(ContentBuilderStore);
    _contentBuilder = inject(CONTENT_BUILDER);
    id = input.required(...(ngDevMode ? [{ debugName: "id" }] : /* istanbul ignore next */ []));
    content = input.required(...(ngDevMode ? [{ debugName: "content" }] : /* istanbul ignore next */ []));
    settings = input.required(...(ngDevMode ? [{ debugName: "settings" }] : /* istanbul ignore next */ []));
    index = input.required(...(ngDevMode ? [{ debugName: "index" }] : /* istanbul ignore next */ []));
    uploading = signal(false, ...(ngDevMode ? [{ debugName: "uploading" }] : /* istanbul ignore next */ []));
    selectedVideo = signal('', ...(ngDevMode ? [{ debugName: "selectedVideo" }] : /* istanbul ignore next */ []));
    _src = signal('', ...(ngDevMode ? [{ debugName: "_src" }] : /* istanbul ignore next */ []));
    _caption = model('', ...(ngDevMode ? [{ debugName: "_caption" }] : /* istanbul ignore next */ []));
    _orientation = signal('landscape', ...(ngDevMode ? [{ debugName: "_orientation" }] : /* istanbul ignore next */ []));
    _settings = model({}, ...(ngDevMode ? [{ debugName: "_settings" }] : /* istanbul ignore next */ []));
    initialized = signal(false, ...(ngDevMode ? [{ debugName: "initialized" }] : /* istanbul ignore next */ []));
    videoElement = viewChild('videoPlayer', ...(ngDevMode ? [{ debugName: "videoElement" }] : /* istanbul ignore next */ []));
    _aspectRatio = 16 / 9;
    ngOnInit() {
        this._src.set(this.content().src);
        this._caption.set(this.content().caption);
        this._orientation.set(this.content().orientation || 'landscape');
        this._settings.set(this.settings() || {});
        this.initialized.set(true);
    }
    focus() {
        if (this._src()) {
            this._contentBuilder.focusBlock(this.id());
        }
    }
    getData() {
        return {
            content: {
                src: this._src(),
                caption: this._caption(),
                orientation: this._orientation()
            },
            settings: {
                ...this._settings(),
            }
        };
    }
    isEmpty() {
        const src = this.getData().content.src;
        return typeof src === 'string' ? src.trim().length === 0 : !src;
    }
    cancelUploading() {
        this.uploading.set(false);
    }
    onFileSelected(event) {
        this.uploading.set(true);
        const reader = new FileReader();
        reader.addEventListener('load', () => {
            this.selectedVideo.set(reader.result);
            const video = document.createElement('video');
            video.preload = 'metadata';
            video.onloadedmetadata = () => {
                window.URL.revokeObjectURL(video.src);
                const orientation = video.videoWidth > video.videoHeight ? 'landscape' : 'portrait';
                this._orientation.set(orientation);
                this._aspectRatio = video.videoWidth / video.videoHeight;
                let width = video.videoWidth;
                let height = video.videoHeight;
                if (width > 704) {
                    width = 704;
                    height = Math.round(width / this._aspectRatio);
                }
                if (height > 1000) {
                    width = Math.round(width / 2);
                    height = Math.round(height / 2);
                }
                // Initial settings based on video metadata
                this._settings.update(s => ({
                    ...s,
                    actualWidth: video.videoWidth,
                    actualHeight: video.videoHeight,
                    width,
                    height
                }));
            };
            video.src = URL.createObjectURL(event.files[0]);
            const uploadFn = this._contentBuilder.getBlockDefOption('video', 'uploadFn');
            uploadFn(event.files[0], reader.result)
                .then((url) => {
                if (!this.uploading()) {
                    this.selectedVideo.set('');
                    return;
                }
                this._src.set(url);
                this.selectedVideo.set('');
                this.uploading.set(false);
                this.update();
                this.focus();
            });
        }, false);
        reader.readAsDataURL(event.files[0]);
    }
    _onCaptionChange() {
        this.update();
    }
    _onVideoResized(event) {
        let width = event.width;
        if (width > 704) {
            width = 704;
        }
        const height = Math.round(width / this._aspectRatio);
        this._settings.update(s => ({
            ...s,
            width,
            height
        }));
        this.update();
    }
    _onVideoLoaded(event) {
        const video = event.target;
        this._aspectRatio = video.videoWidth / video.videoHeight;
    }
    handleKeyPress(event) {
        if (event.key === 'Enter') {
            event.preventDefault();
            event.stopPropagation();
            this._contentBuilder.insertEmptyBlock(this.index());
        }
    }
    update() {
        this._store.updateBlock(this.id(), { ...this.getData(), isEmpty: this.isEmpty() });
        this._contentBuilder.emitContentChangeEvent();
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: VideoBlockComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.4", type: VideoBlockComponent, isStandalone: true, selector: "ngs-video-block", inputs: { id: { classPropertyName: "id", publicName: "id", isSignal: true, isRequired: true, transformFunction: null }, content: { classPropertyName: "content", publicName: "content", isSignal: true, isRequired: true, transformFunction: null }, settings: { classPropertyName: "settings", publicName: "settings", isSignal: true, isRequired: true, transformFunction: null }, index: { classPropertyName: "index", publicName: "index", isSignal: true, isRequired: true, transformFunction: null }, _caption: { classPropertyName: "_caption", publicName: "_caption", isSignal: true, isRequired: false, transformFunction: null }, _settings: { classPropertyName: "_settings", publicName: "_settings", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { _caption: "_captionChange", _settings: "_settingsChange" }, host: { listeners: { "keypress": "handleKeyPress($event)" }, classAttribute: "block" }, providers: [
            {
                provide: CONTENT_EDITOR_BLOCK,
                useExisting: forwardRef(() => VideoBlockComponent),
                multi: true
            }
        ], viewQueries: [{ propertyName: "videoElement", first: true, predicate: ["videoPlayer"], descendants: true, isSignal: true }], ngImport: i0, template: "@if (uploading()) {\n  <div class=\"relative flex items-center justify-center overflow-hidden\">\n    <div class=\"absolute inset-0 z-10 flex items-center justify-center bg-white/80\">\n      <div class=\"absolute top-0 start-0 end-0 z-20\">\n        <ngs-progress-bar mode=\"indeterminate\"/>\n      </div>\n      <div class=\"absolute end-2 top-4 w-max z-30\">\n        <button ngsButton (click)=\"cancelUploading()\">\n          <ngs-icon name=\"fluent:delete-24-regular\"/>\n        </button>\n      </div>\n      <div class=\"bg-white px-3 text-sm py-1.5 rounded-lg border border-border\">Loading...</div>\n    </div>\n    <div [style.width.px]=\"_settings().width || null\"\n         [style.height.px]=\"_settings().height || null\"\n         [class.max-w-full]=\"!_settings().width\">\n      <video [src]=\"selectedVideo()\" muted class=\"w-full h-auto block\"></video>\n    </div>\n  </div>\n} @else if (_src()) {\n  <div class=\"flex items-center justify-center overflow-hidden\">\n    <ngs-resizable-container (resized)=\"_onVideoResized($event)\"\n                             [style.width.px]=\"_settings().width || null\"\n                             [style.height.px]=\"_settings().height || null\"\n                             [class.max-w-full]=\"!_settings().width\">\n      <video #videoPlayer\n             [src]=\"_src()\"\n             class=\"w-full h-auto block\"\n             (loadedmetadata)=\"_onVideoLoaded($event)\"\n             controls></video>\n    </ngs-resizable-container>\n  </div>\n  <ngs-form-field class=\"w-full mt-5\">\n    <ngs-label>Caption</ngs-label>\n    <input ngsInput [(ngModel)]=\"_caption\" (ngModelChange)=\"_onCaptionChange()\">\n  </ngs-form-field>\n} @else {\n  <ngs-upload-area #uploadArea=\"ngsUploadArea\"\n                   ngsUploadTrigger accept=\"video/*\"\n                   (fileSelected)=\"onFileSelected($event)\" multiple=\"false\"\n                   class=\"cursor-pointer hover:outline-2 hover:outline-[var(--color-primary)]\">\n    @if (!uploadArea.api.isDropActive) {\n      Drag & drop video here or click to upload\n    } @else {\n      <div class=\"font-medium\">Drop video here</div>\n    }\n  </ngs-upload-area>\n}\n", styles: [":host{display:block}:host ngs-upload-area{--ngs-upload-area-padding: calc(var(--spacing, .25rem) * 6) calc(var(--spacing, .25rem) * 10)}\n/*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */\n"], dependencies: [{ kind: "component", type: UploadArea, selector: "ngs-upload-area", inputs: ["accept", "allowHover", "multiple"], outputs: ["fileSelected"], exportAs: ["ngsUploadArea"] }, { kind: "directive", type: UploadTriggerDirective, selector: "[ngsUploadTrigger]", inputs: ["accept", "multiple"], outputs: ["fileSelected"], exportAs: ["ngsUploadTrigger"] }, { kind: "component", type: ProgressBar, selector: "ngs-progress-bar", inputs: ["color", "value", "bufferValue", "mode"], outputs: ["animationEnd"], exportAs: ["ngsProgressBar"] }, { kind: "component", type: Button, selector: "    button[ngsButton], button[ngsIconButton],    a[ngsButton], a[ngsIconButton]  ", inputs: ["ngsButton", "ngsIconButton", "loading", "disabled", "disabledInteractive", "disableRipple", "reverse", "fullWidth", "hideTextOnMobile"], exportAs: ["ngsButton"] }, { kind: "component", type: Icon, selector: "ngs-icon", inputs: ["name"], exportAs: ["ngsIcon"] }, { kind: "component", type: FormField, selector: "ngs-form-field", inputs: ["subscriptHiddenIfEmpty"], exportAs: ["ngsFormField"] }, { kind: "directive", type: Input, selector: "input[ngsInput], textarea[ngsInput]", inputs: ["id", "placeholder", "required", "disabled", "readonly", "errorStateMatcher"], exportAs: ["ngsInput"] }, { kind: "ngmodule", type: FormsModule }, { kind: "directive", type: i1.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.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i1.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "component", type: Label, selector: "ngs-label" }, { kind: "component", type: ResizableContainer, selector: "ngs-resizable-container", inputs: ["minWidth"], outputs: ["resized"], exportAs: ["ngsResizableContainer"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: VideoBlockComponent, decorators: [{
            type: Component,
            args: [{ selector: 'ngs-video-block', imports: [
                        UploadArea,
                        UploadTriggerDirective,
                        ProgressBar,
                        Button,
                        Icon,
                        FormField,
                        Input,
                        FormsModule,
                        Label,
                        ResizableContainer
                    ], providers: [
                        {
                            provide: CONTENT_EDITOR_BLOCK,
                            useExisting: forwardRef(() => VideoBlockComponent),
                            multi: true
                        }
                    ], changeDetection: ChangeDetectionStrategy.OnPush, host: {
                        '(keypress)': 'handleKeyPress($event)',
                        'class': 'block'
                    }, template: "@if (uploading()) {\n  <div class=\"relative flex items-center justify-center overflow-hidden\">\n    <div class=\"absolute inset-0 z-10 flex items-center justify-center bg-white/80\">\n      <div class=\"absolute top-0 start-0 end-0 z-20\">\n        <ngs-progress-bar mode=\"indeterminate\"/>\n      </div>\n      <div class=\"absolute end-2 top-4 w-max z-30\">\n        <button ngsButton (click)=\"cancelUploading()\">\n          <ngs-icon name=\"fluent:delete-24-regular\"/>\n        </button>\n      </div>\n      <div class=\"bg-white px-3 text-sm py-1.5 rounded-lg border border-border\">Loading...</div>\n    </div>\n    <div [style.width.px]=\"_settings().width || null\"\n         [style.height.px]=\"_settings().height || null\"\n         [class.max-w-full]=\"!_settings().width\">\n      <video [src]=\"selectedVideo()\" muted class=\"w-full h-auto block\"></video>\n    </div>\n  </div>\n} @else if (_src()) {\n  <div class=\"flex items-center justify-center overflow-hidden\">\n    <ngs-resizable-container (resized)=\"_onVideoResized($event)\"\n                             [style.width.px]=\"_settings().width || null\"\n                             [style.height.px]=\"_settings().height || null\"\n                             [class.max-w-full]=\"!_settings().width\">\n      <video #videoPlayer\n             [src]=\"_src()\"\n             class=\"w-full h-auto block\"\n             (loadedmetadata)=\"_onVideoLoaded($event)\"\n             controls></video>\n    </ngs-resizable-container>\n  </div>\n  <ngs-form-field class=\"w-full mt-5\">\n    <ngs-label>Caption</ngs-label>\n    <input ngsInput [(ngModel)]=\"_caption\" (ngModelChange)=\"_onCaptionChange()\">\n  </ngs-form-field>\n} @else {\n  <ngs-upload-area #uploadArea=\"ngsUploadArea\"\n                   ngsUploadTrigger accept=\"video/*\"\n                   (fileSelected)=\"onFileSelected($event)\" multiple=\"false\"\n                   class=\"cursor-pointer hover:outline-2 hover:outline-[var(--color-primary)]\">\n    @if (!uploadArea.api.isDropActive) {\n      Drag & drop video here or click to upload\n    } @else {\n      <div class=\"font-medium\">Drop video here</div>\n    }\n  </ngs-upload-area>\n}\n", styles: [":host{display:block}:host ngs-upload-area{--ngs-upload-area-padding: calc(var(--spacing, .25rem) * 6) calc(var(--spacing, .25rem) * 10)}\n/*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */\n"] }]
        }], propDecorators: { id: [{ type: i0.Input, args: [{ isSignal: true, alias: "id", required: true }] }], content: [{ type: i0.Input, args: [{ isSignal: true, alias: "content", required: true }] }], settings: [{ type: i0.Input, args: [{ isSignal: true, alias: "settings", required: true }] }], index: [{ type: i0.Input, args: [{ isSignal: true, alias: "index", required: true }] }], _caption: [{ type: i0.Input, args: [{ isSignal: true, alias: "_caption", required: false }] }, { type: i0.Output, args: ["_captionChange"] }], _settings: [{ type: i0.Input, args: [{ isSignal: true, alias: "_settings", required: false }] }, { type: i0.Output, args: ["_settingsChange"] }], videoElement: [{ type: i0.ViewChild, args: ['videoPlayer', { isSignal: true }] }] } });

export { VideoBlockComponent };
//# sourceMappingURL=ngstarter-ui-components-content-editor-video-block.component-DPlYe-_8.mjs.map
