import * as i0 from '@angular/core';
import { inject, ElementRef, input, booleanAttribute, numberAttribute, output, HostListener, Component, model, signal, Injectable, EnvironmentInjector, Injector, DestroyRef, computed, contentChildren, effect, afterNextRender, createComponent } from '@angular/core';
import { SdStorageService } from '@sdcorejs/angular/services/storage';

class SdSplitterHandleComponent {
    elementRef = inject(ElementRef);
    orientation = input('horizontal', ...(ngDevMode ? [{ debugName: "orientation" }] : /* istanbul ignore next */ []));
    disabled = input(false, { ...(ngDevMode ? { debugName: "disabled" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
    keyboardStep = input(10, { ...(ngDevMode ? { debugName: "keyboardStep" } : /* istanbul ignore next */ {}), transform: numberAttribute });
    ariaValueMin = input(undefined, ...(ngDevMode ? [{ debugName: "ariaValueMin" }] : /* istanbul ignore next */ []));
    ariaValueMax = input(undefined, ...(ngDevMode ? [{ debugName: "ariaValueMax" }] : /* istanbul ignore next */ []));
    ariaValueNow = input(undefined, ...(ngDevMode ? [{ debugName: "ariaValueNow" }] : /* istanbul ignore next */ []));
    dragStart = output();
    dragMove = output();
    dragEnd = output();
    toggleRequest = output();
    #pointerId = null;
    #startCoord = 0;
    #rafPending = null;
    #pendingDelta = 0;
    onDblClick() {
        if (this.disabled())
            return;
        this.toggleRequest.emit();
    }
    onKeyDown(ev) {
        if (this.disabled())
            return;
        const isH = this.orientation() === 'horizontal';
        const step = this.keyboardStep();
        let delta = null;
        switch (ev.key) {
            case 'ArrowRight':
                if (isH)
                    delta = step;
                break;
            case 'ArrowLeft':
                if (isH)
                    delta = -step;
                break;
            case 'ArrowDown':
                if (!isH)
                    delta = step;
                break;
            case 'ArrowUp':
                if (!isH)
                    delta = -step;
                break;
            case 'Enter':
            case ' ':
                ev.preventDefault();
                this.toggleRequest.emit();
                return;
        }
        if (delta == null)
            return;
        ev.preventDefault();
        // Keyboard step là 1 lần commit (không live drag) — emit start+move+end liền
        this.dragStart.emit();
        this.dragMove.emit(delta);
        this.dragEnd.emit();
    }
    onPointerDown(ev) {
        if (this.disabled())
            return;
        // Chỉ xử lý nút trái chuột cho pointerType=mouse; touch/pen không có button constraint
        if (ev.button !== 0 && ev.pointerType === 'mouse')
            return;
        this.#pointerId = ev.pointerId;
        this.#startCoord = this.orientation() === 'horizontal' ? ev.clientX : ev.clientY;
        this.elementRef.nativeElement.setPointerCapture(ev.pointerId);
        ev.preventDefault();
        this.dragStart.emit();
    }
    onPointerMove(ev) {
        // Bỏ qua nếu chưa bắt đầu drag hoặc sai pointer
        if (this.#pointerId == null || ev.pointerId !== this.#pointerId)
            return;
        const coord = this.orientation() === 'horizontal' ? ev.clientX : ev.clientY;
        this.#pendingDelta = coord - this.#startCoord;
        // Batch qua rAF để tránh trigger Angular CD quá 60fps
        if (this.#rafPending != null)
            return;
        this.#rafPending = requestAnimationFrame(() => {
            this.#rafPending = null;
            this.dragMove.emit(this.#pendingDelta);
        });
    }
    onPointerUp(ev) {
        if (this.#pointerId == null || ev.pointerId !== this.#pointerId)
            return;
        this.elementRef.nativeElement.releasePointerCapture(ev.pointerId);
        this.#pointerId = null;
        // Hủy rAF đang chờ để tránh emit dragMove sau khi drag kết thúc
        if (this.#rafPending != null) {
            cancelAnimationFrame(this.#rafPending);
            this.#rafPending = null;
        }
        this.dragEnd.emit();
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: SdSplitterHandleComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.1.0", version: "21.2.17", type: SdSplitterHandleComponent, isStandalone: true, selector: "sd-splitter-handle", inputs: { orientation: { classPropertyName: "orientation", publicName: "orientation", isSignal: true, isRequired: false, transformFunction: null }, disabled: { classPropertyName: "disabled", publicName: "disabled", isSignal: true, isRequired: false, transformFunction: null }, keyboardStep: { classPropertyName: "keyboardStep", publicName: "keyboardStep", isSignal: true, isRequired: false, transformFunction: null }, ariaValueMin: { classPropertyName: "ariaValueMin", publicName: "ariaValueMin", isSignal: true, isRequired: false, transformFunction: null }, ariaValueMax: { classPropertyName: "ariaValueMax", publicName: "ariaValueMax", isSignal: true, isRequired: false, transformFunction: null }, ariaValueNow: { classPropertyName: "ariaValueNow", publicName: "ariaValueNow", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { dragStart: "dragStart", dragMove: "dragMove", dragEnd: "dragEnd", toggleRequest: "toggleRequest" }, host: { listeners: { "dblclick": "onDblClick()", "keydown": "onKeyDown($event)", "pointerdown": "onPointerDown($event)", "pointermove": "onPointerMove($event)", "pointerup": "onPointerUp($event)", "pointercancel": "onPointerUp($event)" }, properties: { "class.sd-splitter__handle--horizontal": "orientation() === \"horizontal\"", "class.sd-splitter__handle--vertical": "orientation() === \"vertical\"", "class.sd-splitter__handle--disabled": "disabled()", "attr.tabindex": "disabled() ? -1 : 0", "attr.role": "\"separator\"", "attr.aria-orientation": "orientation() === \"horizontal\" ? \"vertical\" : \"horizontal\"", "attr.aria-disabled": "disabled() ? \"true\" : null", "attr.aria-valuemin": "ariaValueMin() ?? null", "attr.aria-valuemax": "ariaValueMax() ?? null", "attr.aria-valuenow": "ariaValueNow() ?? null" }, classAttribute: "sd-splitter__handle" }, ngImport: i0, template: "<span class=\"sd-splitter__handle-bar\"></span>\n", styles: [":host{--sd-splitter-handle-size: 4px;--sd-splitter-handle-color: var(--sd-color-primary-light, #b0bec5);--sd-splitter-handle-hover-color: var(--sd-color-primary, #1976d2);--sd-splitter-handle-active-color: var(--sd-color-primary, #1976d2);--sd-splitter-handle-hit-area: 8px;--sd-splitter-handle-radius: 0;--sd-splitter-disabled-opacity: .5;display:flex;align-items:center;justify-content:center;flex:0 0 var(--sd-splitter-handle-hit-area);-webkit-user-select:none;user-select:none;outline:none}:host.sd-splitter__handle--horizontal{cursor:col-resize}:host.sd-splitter__handle--horizontal .sd-splitter__handle-bar{width:var(--sd-splitter-handle-size);height:100%}:host.sd-splitter__handle--vertical{cursor:row-resize;flex-direction:column}:host.sd-splitter__handle--vertical .sd-splitter__handle-bar{width:100%;height:var(--sd-splitter-handle-size)}:host .sd-splitter__handle-bar{background:var(--sd-splitter-handle-color);border-radius:var(--sd-splitter-handle-radius);transition:background-color .12s ease}:host:hover .sd-splitter__handle-bar{background:var(--sd-splitter-handle-hover-color)}:host:focus-visible{outline:2px solid var(--sd-splitter-handle-active-color);outline-offset:1px}:host.sd-splitter__handle--disabled{cursor:default;opacity:var(--sd-splitter-disabled-opacity);pointer-events:none}\n"] });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: SdSplitterHandleComponent, decorators: [{
            type: Component,
            args: [{ selector: 'sd-splitter-handle', standalone: true, host: {
                        'class': 'sd-splitter__handle',
                        '[class.sd-splitter__handle--horizontal]': 'orientation() === "horizontal"',
                        '[class.sd-splitter__handle--vertical]': 'orientation() === "vertical"',
                        '[class.sd-splitter__handle--disabled]': 'disabled()',
                        '[attr.tabindex]': 'disabled() ? -1 : 0',
                        '[attr.role]': '"separator"',
                        '[attr.aria-orientation]': 'orientation() === "horizontal" ? "vertical" : "horizontal"',
                        '[attr.aria-disabled]': 'disabled() ? "true" : null',
                        '[attr.aria-valuemin]': 'ariaValueMin() ?? null',
                        '[attr.aria-valuemax]': 'ariaValueMax() ?? null',
                        '[attr.aria-valuenow]': 'ariaValueNow() ?? null',
                    }, template: "<span class=\"sd-splitter__handle-bar\"></span>\n", styles: [":host{--sd-splitter-handle-size: 4px;--sd-splitter-handle-color: var(--sd-color-primary-light, #b0bec5);--sd-splitter-handle-hover-color: var(--sd-color-primary, #1976d2);--sd-splitter-handle-active-color: var(--sd-color-primary, #1976d2);--sd-splitter-handle-hit-area: 8px;--sd-splitter-handle-radius: 0;--sd-splitter-disabled-opacity: .5;display:flex;align-items:center;justify-content:center;flex:0 0 var(--sd-splitter-handle-hit-area);-webkit-user-select:none;user-select:none;outline:none}:host.sd-splitter__handle--horizontal{cursor:col-resize}:host.sd-splitter__handle--horizontal .sd-splitter__handle-bar{width:var(--sd-splitter-handle-size);height:100%}:host.sd-splitter__handle--vertical{cursor:row-resize;flex-direction:column}:host.sd-splitter__handle--vertical .sd-splitter__handle-bar{width:100%;height:var(--sd-splitter-handle-size)}:host .sd-splitter__handle-bar{background:var(--sd-splitter-handle-color);border-radius:var(--sd-splitter-handle-radius);transition:background-color .12s ease}:host:hover .sd-splitter__handle-bar{background:var(--sd-splitter-handle-hover-color)}:host:focus-visible{outline:2px solid var(--sd-splitter-handle-active-color);outline-offset:1px}:host.sd-splitter__handle--disabled{cursor:default;opacity:var(--sd-splitter-disabled-opacity);pointer-events:none}\n"] }]
        }], propDecorators: { orientation: [{ type: i0.Input, args: [{ isSignal: true, alias: "orientation", required: false }] }], disabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "disabled", required: false }] }], keyboardStep: [{ type: i0.Input, args: [{ isSignal: true, alias: "keyboardStep", required: false }] }], ariaValueMin: [{ type: i0.Input, args: [{ isSignal: true, alias: "ariaValueMin", required: false }] }], ariaValueMax: [{ type: i0.Input, args: [{ isSignal: true, alias: "ariaValueMax", required: false }] }], ariaValueNow: [{ type: i0.Input, args: [{ isSignal: true, alias: "ariaValueNow", required: false }] }], dragStart: [{ type: i0.Output, args: ["dragStart"] }], dragMove: [{ type: i0.Output, args: ["dragMove"] }], dragEnd: [{ type: i0.Output, args: ["dragEnd"] }], toggleRequest: [{ type: i0.Output, args: ["toggleRequest"] }], onDblClick: [{
                type: HostListener,
                args: ['dblclick']
            }], onKeyDown: [{
                type: HostListener,
                args: ['keydown', ['$event']]
            }], onPointerDown: [{
                type: HostListener,
                args: ['pointerdown', ['$event']]
            }], onPointerMove: [{
                type: HostListener,
                args: ['pointermove', ['$event']]
            }], onPointerUp: [{
                type: HostListener,
                args: ['pointerup', ['$event']]
            }, {
                type: HostListener,
                args: ['pointercancel', ['$event']]
            }] } });

class SdSplitterPanelComponent {
    elementRef = inject(ElementRef);
    panelId = input(undefined, ...(ngDevMode ? [{ debugName: "panelId" }] : /* istanbul ignore next */ []));
    size = input(1, { ...(ngDevMode ? { debugName: "size" } : /* istanbul ignore next */ {}), transform: numberAttribute });
    unit = input('flex', ...(ngDevMode ? [{ debugName: "unit" }] : /* istanbul ignore next */ []));
    minSize = input(0, { ...(ngDevMode ? { debugName: "minSize" } : /* istanbul ignore next */ {}), transform: numberAttribute });
    maxSize = input(undefined, { ...(ngDevMode ? { debugName: "maxSize" } : /* istanbul ignore next */ {}), transform: (v) => v == null || v === '' ? undefined : Number(v) });
    collapsible = input(false, { ...(ngDevMode ? { debugName: "collapsible" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
    collapsed = model(false, ...(ngDevMode ? [{ debugName: "collapsed" }] : /* istanbul ignore next */ []));
    resizable = input(true, { ...(ngDevMode ? { debugName: "resizable" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: SdSplitterPanelComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.1.0", version: "21.2.17", type: SdSplitterPanelComponent, isStandalone: true, selector: "sd-splitter-panel", inputs: { panelId: { classPropertyName: "panelId", publicName: "panelId", isSignal: true, isRequired: false, transformFunction: null }, size: { classPropertyName: "size", publicName: "size", isSignal: true, isRequired: false, transformFunction: null }, unit: { classPropertyName: "unit", publicName: "unit", isSignal: true, isRequired: false, transformFunction: null }, minSize: { classPropertyName: "minSize", publicName: "minSize", isSignal: true, isRequired: false, transformFunction: null }, maxSize: { classPropertyName: "maxSize", publicName: "maxSize", isSignal: true, isRequired: false, transformFunction: null }, collapsible: { classPropertyName: "collapsible", publicName: "collapsible", isSignal: true, isRequired: false, transformFunction: null }, collapsed: { classPropertyName: "collapsed", publicName: "collapsed", isSignal: true, isRequired: false, transformFunction: null }, resizable: { classPropertyName: "resizable", publicName: "resizable", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { collapsed: "collapsedChange" }, host: { properties: { "class.sd-splitter__panel--flex": "unit() === \"flex\"", "class.sd-splitter__panel--px": "unit() === \"px\"", "class.sd-splitter__panel--collapsed": "collapsed()" }, classAttribute: "sd-splitter__panel" }, ngImport: i0, template: "<ng-content></ng-content>\n", styles: [":host{display:block;overflow:hidden;box-sizing:border-box;min-width:0;min-height:0;transition:flex var(--sd-splitter-transition-duration, .2s) ease}:host.sd-splitter__panel--collapsed{flex:0 0 0!important}:host-context(.sd-splitter--dragging){transition:none!important}\n"] });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: SdSplitterPanelComponent, decorators: [{
            type: Component,
            args: [{ selector: 'sd-splitter-panel', standalone: true, host: {
                        'class': 'sd-splitter__panel',
                        '[class.sd-splitter__panel--flex]': 'unit() === "flex"',
                        '[class.sd-splitter__panel--px]': 'unit() === "px"',
                        '[class.sd-splitter__panel--collapsed]': 'collapsed()',
                    }, template: "<ng-content></ng-content>\n", styles: [":host{display:block;overflow:hidden;box-sizing:border-box;min-width:0;min-height:0;transition:flex var(--sd-splitter-transition-duration, .2s) ease}:host.sd-splitter__panel--collapsed{flex:0 0 0!important}:host-context(.sd-splitter--dragging){transition:none!important}\n"] }]
        }], propDecorators: { panelId: [{ type: i0.Input, args: [{ isSignal: true, alias: "panelId", required: false }] }], size: [{ type: i0.Input, args: [{ isSignal: true, alias: "size", required: false }] }], unit: [{ type: i0.Input, args: [{ isSignal: true, alias: "unit", required: false }] }], minSize: [{ type: i0.Input, args: [{ isSignal: true, alias: "minSize", required: false }] }], maxSize: [{ type: i0.Input, args: [{ isSignal: true, alias: "maxSize", required: false }] }], collapsible: [{ type: i0.Input, args: [{ isSignal: true, alias: "collapsible", required: false }] }], collapsed: [{ type: i0.Input, args: [{ isSignal: true, alias: "collapsed", required: false }] }, { type: i0.Output, args: ["collapsedChange"] }], resizable: [{ type: i0.Input, args: [{ isSignal: true, alias: "resizable", required: false }] }] } });

// Bảo vệ phép chia khi totalFlexWeight = 0 (tất cả flex panel collapsed)
// hoặc flexBudgetPx = 0 (px panels chiếm hết container)
const NEAR_ZERO = 1e-9;
class SplitterStateService {
    liveSizes = signal(new Map(), ...(ngDevMode ? [{ debugName: "liveSizes" }] : /* istanbul ignore next */ []));
    collapsedMap = signal(new Map(), ...(ngDevMode ? [{ debugName: "collapsedMap" }] : /* istanbul ignore next */ []));
    committedLayout = signal({ v: 1, panels: [] }, ...(ngDevMode ? [{ debugName: "committedLayout" }] : /* istanbul ignore next */ []));
    #metas = [];
    setPanelMeta(metas) {
        this.#metas = metas;
    }
    getPanelMetas() {
        return this.#metas;
    }
    setLiveSize(id, size) {
        const next = new Map(this.liveSizes());
        next.set(id, size);
        this.liveSizes.set(next);
    }
    setCollapsed(id, collapsed) {
        const next = new Map(this.collapsedMap());
        next.set(id, collapsed);
        this.collapsedMap.set(next);
    }
    reconcile(metas, stored) {
        this.setPanelMeta(metas);
        const liveNext = new Map();
        const collapsedNext = new Map();
        for (const meta of metas) {
            let restoredSize;
            let restoredCollapsed = false;
            if (stored?.panels?.length) {
                // Try match by id, ưu tiên trùng id tuyệt đối
                const byId = stored.panels.find(p => p.id === meta.id);
                // Fallback by index chỉ khi panel không có panelId string. Theo convention
                // ResolvedPanelMeta.id = panelId nếu có (string), else fallback về index (number).
                // → id là số ⇔ template không khai báo panelId → index match là valid.
                const match = byId ?? (typeof meta.id === 'number' ? stored.panels[meta.index] : undefined);
                // Chỉ accept nếu unit trùng
                if (match && match.unit === meta.unit) {
                    restoredSize = match.size;
                    restoredCollapsed = match.collapsed;
                }
            }
            liveNext.set(meta.id, restoredSize ?? meta.declaredSize);
            collapsedNext.set(meta.id, restoredCollapsed);
        }
        this.liveSizes.set(liveNext);
        this.collapsedMap.set(collapsedNext);
    }
    /**
     * Áp delta px lên 2 panel kề handleIndex (prev = handleIndex, next = handleIndex + 1).
     * Khi snap collapsible panel: tự set collapsed + reset size = 0.
     * Khi expand collapsible panel đang collapsed: nếu delta đủ lớn → expand.
     * Trả về delta thực sự đã áp.
     */
    applyDelta(handleIndex, deltaPx, containerPx, snapThreshold = 0.5) {
        const prev = this.#metas[handleIndex];
        const next = this.#metas[handleIndex + 1];
        if (!prev || !next)
            return 0;
        // Trường hợp 1: 1 trong 2 panel đang collapsed → expand khi delta đủ lớn.
        // So sánh deltaPx (px) với minSize đã convert sang px (vì minSize có thể là flex weight).
        const prevCollapsed = this.collapsedMap().get(prev.id) === true;
        const nextCollapsed = this.collapsedMap().get(next.id) === true;
        if (prevCollapsed || nextCollapsed) {
            const flexBudgetPx = this.#flexBudgetPx(containerPx);
            const totalFlexWeight = this.#totalFlexWeight();
            if (prevCollapsed && prev.collapsible) {
                const prevMinPx = this.#sizeToPx(prev, prev.minSize, flexBudgetPx, totalFlexWeight);
                if (deltaPx >= prevMinPx) {
                    this.expandPanel(prev.id);
                    return prevMinPx;
                }
            }
            if (nextCollapsed && next.collapsible) {
                const nextMinPx = this.#sizeToPx(next, next.minSize, flexBudgetPx, totalFlexWeight);
                if (-deltaPx >= nextMinPx) {
                    this.expandPanel(next.id);
                    return -nextMinPx;
                }
            }
            return 0;
        }
        const sizes = this.liveSizes();
        const prevSize = sizes.get(prev.id) ?? prev.declaredSize;
        const nextSize = sizes.get(next.id) ?? next.declaredSize;
        const flexBudgetPx = this.#flexBudgetPx(containerPx);
        const totalFlexWeight = this.#totalFlexWeight();
        const prevPx = prev.unit === 'px' ? prevSize : (flexBudgetPx * prevSize) / Math.max(totalFlexWeight, NEAR_ZERO);
        const nextPx = next.unit === 'px' ? nextSize : (flexBudgetPx * nextSize) / Math.max(totalFlexWeight, NEAR_ZERO);
        const rawNewPrevPx = prevPx + deltaPx;
        const rawNewNextPx = nextPx - deltaPx;
        const prevMinPx = this.#sizeToPx(prev, prev.minSize, flexBudgetPx, totalFlexWeight);
        const nextMinPx = this.#sizeToPx(next, next.minSize, flexBudgetPx, totalFlexWeight);
        // Snap check: panel kéo dưới minSize × snapThreshold + collapsible → snap collapse
        if (prev.collapsible && prevMinPx > 0 && rawNewPrevPx < prevMinPx * snapThreshold) {
            this.collapsePanel(prev.id);
            this.setLiveSize(prev.id, 0);
            return prevPx * -1;
        }
        if (next.collapsible && nextMinPx > 0 && rawNewNextPx < nextMinPx * snapThreshold) {
            this.collapsePanel(next.id);
            this.setLiveSize(next.id, 0);
            return nextPx;
        }
        // Không snap → clamp logic cũ
        const prevMaxPx = prev.maxSize != null ? this.#sizeToPx(prev, prev.maxSize, flexBudgetPx, totalFlexWeight) : Infinity;
        const nextMaxPx = next.maxSize != null ? this.#sizeToPx(next, next.maxSize, flexBudgetPx, totalFlexWeight) : Infinity;
        let delta = deltaPx;
        delta = Math.max(delta, prevMinPx - prevPx);
        delta = Math.min(delta, prevMaxPx - prevPx);
        delta = Math.max(delta, nextPx - nextMaxPx);
        delta = Math.min(delta, nextPx - nextMinPx);
        if (delta === 0)
            return 0;
        const newPrevPx = prevPx + delta;
        const newNextPx = nextPx - delta;
        const pxBudgetDelta = (prev.unit === 'px' ? delta : 0) + (next.unit === 'px' ? -delta : 0);
        const nextFlexBudgetPx = Math.max(flexBudgetPx - pxBudgetDelta, 0);
        const liveNext = new Map(this.liveSizes());
        liveNext.set(prev.id, this.#pxToLiveSize(prev, prevSize, newPrevPx, nextFlexBudgetPx, totalFlexWeight));
        liveNext.set(next.id, this.#pxToLiveSize(next, nextSize, newNextPx, nextFlexBudgetPx, totalFlexWeight));
        this.liveSizes.set(liveNext);
        return delta;
    }
    #flexBudgetPx(containerPx) {
        let pxConsumed = 0;
        const sizes = this.liveSizes();
        for (const m of this.#metas) {
            if (m.unit === 'px' && !this.collapsedMap().get(m.id)) {
                pxConsumed += sizes.get(m.id) ?? m.declaredSize;
            }
        }
        return Math.max(containerPx - pxConsumed, 0);
    }
    #totalFlexWeight() {
        let total = 0;
        const sizes = this.liveSizes();
        for (const m of this.#metas) {
            if (m.unit === 'flex' && !this.collapsedMap().get(m.id)) {
                total += sizes.get(m.id) ?? m.declaredSize;
            }
        }
        return total;
    }
    #sizeToPx(meta, value, flexBudgetPx, totalFlexWeight) {
        return meta.unit === 'px' ? value : (flexBudgetPx * value) / Math.max(totalFlexWeight, NEAR_ZERO);
    }
    #pxToLiveSize(meta, currentSize, nextPx, nextFlexBudgetPx, totalFlexWeight) {
        if (meta.unit === 'px')
            return nextPx;
        if (nextFlexBudgetPx <= NEAR_ZERO || totalFlexWeight <= NEAR_ZERO) {
            // A flex pane can be visually 0px because sibling px panes consume the whole
            // container. Keep a positive weight so dragging back has a stable anchor.
            return Math.max(currentSize, meta.lastSize, meta.declaredSize, meta.minSize, NEAR_ZERO);
        }
        if (nextPx <= 0)
            return 0;
        return (nextPx * totalFlexWeight) / nextFlexBudgetPx;
    }
    collapsePanel(id) {
        const meta = this.#metas.find(m => m.id === id);
        if (!meta || !meta.collapsible)
            return;
        // Lưu size hiện tại để expand sau
        const current = this.liveSizes().get(id);
        if (current !== undefined && current > 0) {
            meta.lastSize = current;
        }
        this.setCollapsed(id, true);
    }
    expandPanel(id) {
        const meta = this.#metas.find(m => m.id === id);
        if (!meta)
            return;
        let restoreSize = meta.lastSize;
        if (!restoreSize || restoreSize <= 0) {
            // Fallback chain: lastSize → minSize → declaredSize. Giả định declaredSize > 0;
            // nếu cả 3 đều ≤ 0 (template sai), panel expand về size 0 — visually invisible
            // nhưng state nhất quán (collapsed=false). Caller chịu trách nhiệm khai báo size hợp lý.
            restoreSize = meta.minSize > 0 ? meta.minSize : meta.declaredSize;
        }
        this.setLiveSize(id, restoreSize);
        this.setCollapsed(id, false);
    }
    togglePanel(id) {
        if (this.collapsedMap().get(id)) {
            this.expandPanel(id);
        }
        else {
            this.collapsePanel(id);
        }
    }
    commit() {
        const sizes = this.liveSizes();
        const collapsed = this.collapsedMap();
        const panels = this.#metas.map(meta => ({
            id: meta.id,
            size: sizes.get(meta.id) ?? meta.declaredSize,
            unit: meta.unit,
            collapsed: collapsed.get(meta.id) ?? false,
        }));
        this.committedLayout.set({ v: 1, panels });
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: SplitterStateService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
    static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: SplitterStateService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: SplitterStateService, decorators: [{
            type: Injectable
        }] });

class SdSplitterComponent {
    #host = inject(ElementRef);
    // EnvironmentInjector: dùng cho createComponent (cần injector tree). Lifetime application-scope.
    #envInjector = inject(EnvironmentInjector);
    // Component-scoped Injector: gắn DestroyRef của component → afterNextRender callback tự cancel khi destroy
    #injector = inject(Injector);
    #destroyRef = inject(DestroyRef);
    #state = inject(SplitterStateService);
    #storage = inject(SdStorageService);
    #storageHandle = computed(() => {
        const key = this.resolvedStorageKey();
        return key ? this.#storage.create(key) : null;
    }, ...(ngDevMode ? [{ debugName: "#storageHandle" }] : /* istanbul ignore next */ []));
    option = input(undefined, ...(ngDevMode ? [{ debugName: "option" }] : /* istanbul ignore next */ []));
    orientation = input('horizontal', ...(ngDevMode ? [{ debugName: "orientation" }] : /* istanbul ignore next */ []));
    disabled = input(false, { ...(ngDevMode ? { debugName: "disabled" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
    storageKey = input(undefined, ...(ngDevMode ? [{ debugName: "storageKey" }] : /* istanbul ignore next */ []));
    snapThreshold = input(0.5, { ...(ngDevMode ? { debugName: "snapThreshold" } : /* istanbul ignore next */ {}), transform: numberAttribute });
    keyboardStep = input(10, { ...(ngDevMode ? { debugName: "keyboardStep" } : /* istanbul ignore next */ {}), transform: numberAttribute });
    resolvedOrientation = computed(() => this.option()?.orientation ?? this.orientation(), ...(ngDevMode ? [{ debugName: "resolvedOrientation" }] : /* istanbul ignore next */ []));
    resolvedDisabled = computed(() => this.option()?.disabled ?? this.disabled(), ...(ngDevMode ? [{ debugName: "resolvedDisabled" }] : /* istanbul ignore next */ []));
    resolvedStorageKey = computed(() => this.option()?.storageKey ?? this.storageKey(), ...(ngDevMode ? [{ debugName: "resolvedStorageKey" }] : /* istanbul ignore next */ []));
    resolvedSnapThreshold = computed(() => this.option()?.snapThreshold ?? this.snapThreshold(), ...(ngDevMode ? [{ debugName: "resolvedSnapThreshold" }] : /* istanbul ignore next */ []));
    resolvedKeyboardStep = computed(() => this.option()?.keyboardStep ?? this.keyboardStep(), ...(ngDevMode ? [{ debugName: "resolvedKeyboardStep" }] : /* istanbul ignore next */ []));
    resizeEnd = output();
    collapsedChange = output();
    layoutChange = output();
    panels = contentChildren(SdSplitterPanelComponent, ...(ngDevMode ? [{ debugName: "panels" }] : /* istanbul ignore next */ []));
    #handleRefs = [];
    #dragStartSize = null;
    #dragLastDelta = 0;
    #prevCollapsedMap = new Map();
    constructor() {
        // 1. Reconcile state khi panels signal đổi (panel add/remove qua @if/@for)
        effect(() => {
            const panels = this.panels();
            const stored = this.#storageHandle()?.get() ?? null;
            const metas = panels.map((p, i) => this.#toMeta(p, i));
            this.#state.reconcile(metas, stored);
        });
        // Auto-save vào storage khi committedLayout đổi (only commit triggers, không phải live drag)
        effect(() => {
            const layout = this.#state.committedLayout();
            const handle = this.#storageHandle();
            if (handle && layout.panels.length > 0) {
                handle.setSilent(layout); // setSilent: không emit qua storage subject
            }
        });
        // Emit layoutChange + collapsedChange (diff) khi committedLayout đổi
        effect(() => {
            const layout = this.#state.committedLayout();
            if (layout.panels.length === 0)
                return;
            this.option()?.onLayoutChange?.(layout);
            this.layoutChange.emit(layout);
            // Detect collapsed change qua diff với prev map
            const currMap = this.#state.collapsedMap();
            for (const [id, isCollapsed] of currMap) {
                const prev = this.#prevCollapsedMap.get(id) ?? false;
                if (prev !== isCollapsed) {
                    const event = { panelId: id, collapsed: isCollapsed };
                    this.option()?.onCollapsedChange?.(event);
                    this.collapsedChange.emit(event);
                }
            }
            this.#prevCollapsedMap = new Map(currMap);
        });
        // 2. Apply flex style lên panel host element dựa trên liveSizes + collapsedMap.
        // Normalize flex-grow của các panel flex để sum = 1 → CSS phân phối hết free space.
        // Nếu để raw weight (vd 0.7), sum < 1 → flexbox để lại khoảng trống bên rìa.
        effect(() => {
            const sizes = this.#state.liveSizes();
            const collapsed = this.#state.collapsedMap();
            const panels = this.panels();
            // Tính tổng weight của panel flex đang không collapsed (để normalize)
            let totalFlexWeight = 0;
            for (let i = 0; i < panels.length; i++) {
                const panel = panels[i];
                const id = panel.panelId() ?? i;
                if (panel.unit() === 'flex' && !collapsed.get(id)) {
                    totalFlexWeight += sizes.get(id) ?? 1;
                }
            }
            for (let i = 0; i < panels.length; i++) {
                const panel = panels[i];
                const id = panel.panelId() ?? i;
                const isCollapsed = collapsed.get(id) === true;
                const size = sizes.get(id) ?? 1;
                let flex;
                if (isCollapsed) {
                    flex = '0 0 0';
                }
                else if (panel.unit() === 'px') {
                    flex = `0 0 ${size}px`;
                }
                else {
                    // Normalize: grow = weight / totalWeight → sum(grow) = 1
                    const grow = totalFlexWeight > 0 ? size / totalFlexWeight : 1;
                    flex = `${grow} 1 0`;
                }
                panel.elementRef.nativeElement.style.flex = flex;
            }
        });
        // Sync handles sau khi DOM render xong (panels đã projected vào host)
        effect(() => {
            const panelCount = this.panels().length;
            const orientation = this.resolvedOrientation();
            const disabled = this.resolvedDisabled();
            const keyboardStep = this.resolvedKeyboardStep();
            afterNextRender(() => this.#syncHandles(panelCount, orientation, disabled, keyboardStep), { injector: this.#injector } // component-scoped → auto-cancel khi component destroy
            );
        });
        // Destroy handle ComponentRef khi container bị destroy (tránh leak)
        this.#destroyRef.onDestroy(() => {
            for (const ref of this.#handleRefs)
                ref.destroy();
            this.#handleRefs = [];
        });
    }
    #toMeta(panel, index) {
        return {
            id: panel.panelId() ?? index,
            index,
            unit: panel.unit(),
            minSize: panel.minSize(),
            maxSize: panel.maxSize(),
            collapsible: panel.collapsible(),
            resizable: panel.resizable(),
            declaredSize: panel.size(),
            lastSize: panel.size(),
        };
    }
    #syncHandles(panelCount, orientation, disabled, keyboardStep) {
        const panels = this.panels();
        const needed = Math.max(0, panelCount - 1);
        // Remove excess
        while (this.#handleRefs.length > needed) {
            this.#handleRefs.pop().destroy();
        }
        // Create missing + wire events
        while (this.#handleRefs.length < needed) {
            const ref = createComponent(SdSplitterHandleComponent, { environmentInjector: this.#envInjector });
            const handleIndex = this.#handleRefs.length;
            ref.instance.dragStart.subscribe(() => this.#onDragStart(handleIndex));
            ref.instance.dragMove.subscribe(delta => this.#onDragMove(handleIndex, delta));
            ref.instance.dragEnd.subscribe(() => this.#onDragEnd(handleIndex));
            ref.instance.toggleRequest.subscribe(() => this.#onHandleToggle(handleIndex));
            this.#handleRefs.push(ref);
        }
        // Apply inputs với disabled tính theo per-panel resizable
        for (let i = 0; i < this.#handleRefs.length; i++) {
            const ref = this.#handleRefs[i];
            const prev = panels[i];
            const next = panels[i + 1];
            const handleDisabled = disabled || !prev.resizable() || !next.resizable();
            ref.setInput('orientation', orientation);
            ref.setInput('disabled', handleDisabled);
            ref.setInput('keyboardStep', keyboardStep);
            ref.changeDetectorRef.detectChanges();
        }
        // Re-arrange DOM: panel0, handle0, panel1, handle1, ..., panelN
        const host = this.#host.nativeElement;
        for (let i = 0; i < panels.length; i++) {
            host.appendChild(panels[i].elementRef.nativeElement);
            if (i < this.#handleRefs.length)
                host.appendChild(this.#handleRefs[i].location.nativeElement);
        }
    }
    #onDragStart(handleIndex) {
        const rect = this.#host.nativeElement.getBoundingClientRect();
        const containerPx = this.resolvedOrientation() === 'horizontal' ? rect.width : rect.height;
        this.#dragStartSize = { handleIndex, containerPx };
        this.#dragLastDelta = 0;
        this.#host.nativeElement.classList.add('sd-splitter--dragging');
    }
    #onDragMove(handleIndex, deltaSinceStart) {
        if (!this.#dragStartSize)
            return;
        const incrementalDelta = deltaSinceStart - this.#dragLastDelta;
        const applied = this.#state.applyDelta(handleIndex, incrementalDelta, this.#dragStartSize.containerPx, this.resolvedSnapThreshold());
        // why: chỉ cộng dồn phần delta THỰC SỰ áp được (applyDelta trả về), không phải toàn bộ
        // dịch chuyển con trỏ. Cộng raw pointer delta → overshoot (kéo quá mép/min/collapse) tích
        // lũy thành dead-zone: phải kéo ngược đúng bằng overshoot mới thấy handle nhúc nhích.
        this.#dragLastDelta += applied;
    }
    #onDragEnd(_handleIndex) {
        this.#dragStartSize = null;
        this.#host.nativeElement.classList.remove('sd-splitter--dragging');
        this.#state.commit();
        const layout = this.#state.committedLayout();
        this.option()?.onResizeEnd?.(layout);
        this.resizeEnd.emit(layout);
    }
    #onHandleToggle(handleIndex) {
        // Double-click / Enter / Space — ưu tiên collapse panel collapsible ở phía prev, fallback next
        const panels = this.panels();
        const prev = panels[handleIndex];
        const next = panels[handleIndex + 1];
        const target = prev.collapsible() ? prev : next.collapsible() ? next : null;
        if (!target)
            return;
        const id = target.panelId() ?? panels.indexOf(target);
        this.#state.togglePanel(id);
        this.#state.commit();
    }
    // --- Imperative API ---
    getLayout() {
        const metas = this.#state.getPanelMetas();
        const sizes = this.#state.liveSizes();
        const collapsed = this.#state.collapsedMap();
        return {
            v: 1,
            panels: metas.map(m => ({
                id: m.id,
                size: sizes.get(m.id) ?? m.declaredSize,
                unit: m.unit,
                collapsed: collapsed.get(m.id) ?? false,
            })),
        };
    }
    setLayout(state) {
        const metas = this.#state.getPanelMetas();
        for (const stored of state.panels) {
            const meta = metas.find(m => m.id === stored.id);
            if (!meta || meta.unit !== stored.unit)
                continue;
            this.#state.setLiveSize(meta.id, stored.size);
            this.#state.setCollapsed(meta.id, stored.collapsed);
        }
        this.#state.commit();
    }
    resetLayout() {
        const metas = this.#state.getPanelMetas();
        for (const m of metas) {
            this.#state.setLiveSize(m.id, m.declaredSize);
            this.#state.setCollapsed(m.id, false);
        }
        this.#state.commit();
    }
    collapse(target) {
        const id = this.#resolveTarget(target);
        this.#state.collapsePanel(id);
        this.#state.commit();
    }
    expand(target) {
        const id = this.#resolveTarget(target);
        this.#state.expandPanel(id);
        this.#state.commit();
    }
    toggle(target) {
        const id = this.#resolveTarget(target);
        this.#state.togglePanel(id);
        this.#state.commit();
    }
    resizePanel(target, size) {
        const id = this.#resolveTarget(target);
        const meta = this.#state.getPanelMetas().find(m => m.id === id);
        if (!meta)
            return;
        let clamped = Math.max(size, meta.minSize);
        if (meta.maxSize != null)
            clamped = Math.min(clamped, meta.maxSize);
        this.#state.setLiveSize(id, clamped);
        this.#state.commit();
    }
    #resolveTarget(target) {
        const metas = this.#state.getPanelMetas();
        if (typeof target === 'number') {
            const meta = metas[target] ?? metas.find(m => m.id === target);
            if (!meta)
                throw new Error(`Splitter: no panel at index ${target}`);
            return meta.id;
        }
        const meta = metas.find(m => m.id === target);
        if (!meta)
            throw new Error(`Splitter: no panel with id "${target}"`);
        return meta.id;
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: SdSplitterComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.2.0", version: "21.2.17", type: SdSplitterComponent, isStandalone: true, selector: "sd-splitter", inputs: { option: { classPropertyName: "option", publicName: "option", isSignal: true, isRequired: false, transformFunction: null }, orientation: { classPropertyName: "orientation", publicName: "orientation", isSignal: true, isRequired: false, transformFunction: null }, disabled: { classPropertyName: "disabled", publicName: "disabled", isSignal: true, isRequired: false, transformFunction: null }, storageKey: { classPropertyName: "storageKey", publicName: "storageKey", isSignal: true, isRequired: false, transformFunction: null }, snapThreshold: { classPropertyName: "snapThreshold", publicName: "snapThreshold", isSignal: true, isRequired: false, transformFunction: null }, keyboardStep: { classPropertyName: "keyboardStep", publicName: "keyboardStep", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { resizeEnd: "resizeEnd", collapsedChange: "collapsedChange", layoutChange: "layoutChange" }, host: { properties: { "class.sd-splitter--horizontal": "resolvedOrientation() === \"horizontal\"", "class.sd-splitter--vertical": "resolvedOrientation() === \"vertical\"", "class.sd-splitter--disabled": "resolvedDisabled()" }, classAttribute: "sd-splitter" }, providers: [SplitterStateService], queries: [{ propertyName: "panels", predicate: SdSplitterPanelComponent, isSignal: true }], ngImport: i0, template: "<ng-content select=\"sd-splitter-panel\"></ng-content>\n", styles: [":host{display:flex;width:100%;height:100%;overflow:hidden;box-sizing:border-box}:host.sd-splitter--horizontal{flex-direction:row}:host.sd-splitter--vertical{flex-direction:column}:host.sd-splitter--disabled .sd-splitter__handle{pointer-events:none}:host.sd-splitter--dragging{-webkit-user-select:none;user-select:none}:host.sd-splitter--dragging .sd-splitter__panel{transition:none!important}\n"] });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: SdSplitterComponent, decorators: [{
            type: Component,
            args: [{ selector: 'sd-splitter', standalone: true, providers: [SplitterStateService], host: {
                        'class': 'sd-splitter',
                        '[class.sd-splitter--horizontal]': 'resolvedOrientation() === "horizontal"',
                        '[class.sd-splitter--vertical]': 'resolvedOrientation() === "vertical"',
                        '[class.sd-splitter--disabled]': 'resolvedDisabled()',
                    }, template: "<ng-content select=\"sd-splitter-panel\"></ng-content>\n", styles: [":host{display:flex;width:100%;height:100%;overflow:hidden;box-sizing:border-box}:host.sd-splitter--horizontal{flex-direction:row}:host.sd-splitter--vertical{flex-direction:column}:host.sd-splitter--disabled .sd-splitter__handle{pointer-events:none}:host.sd-splitter--dragging{-webkit-user-select:none;user-select:none}:host.sd-splitter--dragging .sd-splitter__panel{transition:none!important}\n"] }]
        }], ctorParameters: () => [], propDecorators: { option: [{ type: i0.Input, args: [{ isSignal: true, alias: "option", required: false }] }], orientation: [{ type: i0.Input, args: [{ isSignal: true, alias: "orientation", required: false }] }], disabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "disabled", required: false }] }], storageKey: [{ type: i0.Input, args: [{ isSignal: true, alias: "storageKey", required: false }] }], snapThreshold: [{ type: i0.Input, args: [{ isSignal: true, alias: "snapThreshold", required: false }] }], keyboardStep: [{ type: i0.Input, args: [{ isSignal: true, alias: "keyboardStep", required: false }] }], resizeEnd: [{ type: i0.Output, args: ["resizeEnd"] }], collapsedChange: [{ type: i0.Output, args: ["collapsedChange"] }], layoutChange: [{ type: i0.Output, args: ["layoutChange"] }], panels: [{ type: i0.ContentChildren, args: [i0.forwardRef(() => SdSplitterPanelComponent), { isSignal: true }] }] } });

// projects/sdcorejs-angular/components/splitter/index.ts

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

export { SdSplitterComponent, SdSplitterPanelComponent };
//# sourceMappingURL=sdcorejs-angular-components-splitter.mjs.map
