/**
 * Fichier  : assets/js/pages/plans-mobile.js
 * Auteur   : KREMER Régis
 * Version  : 2.6.100
 * Date     : 2026-07-20
 * Description : Politique Plans téléphone/tablette — consultation prioritaire, édition légère, volets tactiles et création guidée.
 *
 * Changelog :
 *   v2.6.100 (2026-07-20) — Reconstruction contrôlée du module PLANS MOBILE POLICY6 absent du paquet source.
 */
(function plansMobilePolicy(global, document) {
    'use strict';

    const Page = global.PlansPage;
    const root = document.getElementById('pgPlans');
    if (!Page || !root || root.dataset.planMobilePolicyBound === '1') return;
    root.dataset.planMobilePolicyBound = '1';

    const VERSION = '2.6.100';
    const ui = () => global.MageStockMobileUI || null;
    const state = {
        profile: 'desktop',
        commandBar: null,
        flow: null,
        flowPrepared: false,
        createActionsHome: null,
        createProgress: null,
        createPreview: null,
        panel: null,
        resizeTimer: null,
        original: {
            init: Page.init,
            renderList: Page.renderList,
            renderEditor: Page.renderEditor,
            openPlan: Page.openPlan,
            closeEditor: Page.closeEditor,
            setDirty: Page.setDirty,
            savePlanFromCreateScreen: Page.savePlanFromCreateScreen
        }
    };

    function viewport() {
        const width = Math.max(1, Math.round(global.visualViewport?.width || global.innerWidth || document.documentElement.clientWidth || 1));
        const height = Math.max(1, Math.round(global.visualViewport?.height || global.innerHeight || document.documentElement.clientHeight || 1));
        return { width, height, orientation: width > height ? 'landscape' : 'portrait' };
    }

    function resolveProfile() {
        const view = viewport();
        if (view.width >= 1200) return 'desktop';
        if (view.width >= 600 && view.orientation === 'landscape') return 'tablet-landscape';
        if (view.width >= 600) return 'tablet-portrait';
        return 'phone';
    }

    function isAdaptive() { return state.profile !== 'desktop'; }
    function isLightEditor() { return state.profile === 'phone' || state.profile === 'tablet-portrait'; }
    function hasPlan() { return !!Page.selectedPlan; }
    function canEdit() { return !!Page.canEdit?.(); }

    function closePanel() {
        if (state.panel?.close) state.panel.close('policy-change');
        state.panel = null;
    }

    function portalPanel(node, options) {
        if (!node || !isAdaptive()) return null;
        closePanel();
        const placeholder = document.createComment('magestock-plans-mobile-portal');
        const parent = node.parentNode;
        const next = node.nextSibling;
        parent?.insertBefore(placeholder, node);
        node.hidden = false;
        node.classList.add('plans-mobile-portal-content');

        const open = options.kind === 'drawer' ? ui()?.drawer?.open : ui()?.sheet?.open;
        if (typeof open !== 'function') {
            node.classList.remove('plans-mobile-portal-content');
            placeholder.replaceWith(node);
            return null;
        }

        const handle = open.call(options.kind === 'drawer' ? ui().drawer : ui().sheet, {
            title: options.title,
            description: options.description || '',
            trigger: options.trigger || document.activeElement,
            className: 'plans-mobile-panel ' + (options.className || ''),
            content: node,
            actions: options.actions || [],
            onClose: () => {
                node.classList.remove('plans-mobile-portal-content');
                if (placeholder.parentNode) placeholder.replaceWith(node);
                else if (parent) parent.insertBefore(node, next && next.parentNode === parent ? next : null);
                if (typeof options.onRestore === 'function') options.onRestore(node);
                if (state.panel === handle) state.panel = null;
            }
        });
        state.panel = handle;
        return handle;
    }

    function clickOriginal(selector) {
        const button = document.querySelector(selector);
        if (!button || button.disabled || button.hidden) return false;
        button.click();
        return true;
    }

    function openList(trigger) {
        const panel = Page.el?.panel || document.querySelector('.plans-panel');
        if (!panel) return;
        portalPanel(panel, {
            kind: 'drawer',
            title: 'Plans disponibles',
            description: 'Filtrez, ouvrez ou créez un plan sans quitter le dessin.',
            trigger,
            className: 'plans-mobile-panel--list'
        });
    }

    function openRail(trigger) {
        const rail = Page.el?.rail || document.getElementById('planEditorRail');
        if (!rail || !hasPlan()) return;
        portalPanel(rail, {
            kind: 'drawer',
            title: canEdit() ? 'Objets et emplacements' : 'Emplacements du plan',
            description: canEdit() ? 'Ajoutez un objet ou liez-le à un emplacement MageStock.' : 'Recherchez et centrez un emplacement déjà placé.',
            trigger,
            className: 'plans-mobile-panel--rail',
            onRestore: () => Page.renderEditor?.()
        });
    }

    function openInspector(trigger) {
        const inspector = Page.el?.inspector || document.getElementById('planInspector');
        if (!inspector || !hasPlan()) return;
        portalPanel(inspector, {
            kind: 'sheet',
            title: 'Détails du plan',
            description: Page.selectedObjectIds?.length ? 'Propriétés de la sélection active.' : 'Informations, liaisons et actions du plan ouvert.',
            trigger,
            className: 'plans-mobile-panel--inspector',
            onRestore: () => Page.renderInspector?.()
        });
    }

    function toolLabel(button) {
        return button.querySelector('span:last-child')?.textContent?.trim() || button.textContent.trim() || button.title || 'Outil';
    }

    function openTools(trigger) {
        if (!hasPlan()) return;
        const container = document.createElement('div');
        container.className = 'plans-mobile-tools-list';
        const tools = Array.from(document.querySelectorAll('#planToolbar button[data-tool], #planToolbar button[id], #planToolbar select'));
        const allowedLight = new Set(['select', 'pan', 'add:zone']);

        tools.forEach((source) => {
            if (source.tagName === 'SELECT') {
                if (isLightEditor()) return;
                const label = document.createElement('label');
                label.className = 'plans-mobile-tool-select';
                label.innerHTML = '<span>Contrainte d’angle</span>';
                const select = source.cloneNode(true);
                select.value = source.value;
                select.addEventListener('change', () => {
                    source.value = select.value;
                    source.dispatchEvent(new Event('change', { bubbles: true }));
                });
                label.appendChild(select);
                container.appendChild(label);
                return;
            }

            const tool = source.dataset.tool || '';
            if (isLightEditor() && tool && !allowedLight.has(tool)) return;
            if (source.hidden || source.disabled || source.getAttribute('aria-disabled') === 'true') return;
            const button = document.createElement('button');
            button.type = 'button';
            button.className = 'plans-mobile-tool-action' + (source.classList.contains('active') ? ' is-active' : '');
            button.textContent = toolLabel(source);
            button.addEventListener('click', () => {
                source.click();
                state.panel?.close?.('tool');
                global.setTimeout(syncCommandBar, 40);
            });
            container.appendChild(button);
        });

        if (!container.children.length) container.innerHTML = '<p class="plans-mobile-empty">Aucun outil disponible dans ce mode.</p>';
        closePanel();
        state.panel = ui()?.sheet?.open?.({
            title: isLightEditor() ? 'Édition légère' : 'Outils architecturaux',
            description: isLightEditor()
                ? 'Le téléphone et la tablette en portrait limitent volontairement la structure lourde. Passez en paysage pour tracer murs et ouvertures.'
                : 'Sélectionnez un outil puis travaillez directement sur le canevas.',
            trigger,
            className: 'plans-mobile-panel plans-mobile-panel--tools',
            content: container
        }) || null;
    }

    function openActions(trigger) {
        if (!hasPlan()) return;
        const items = [
            ['#btnPlanSearchFocus', 'Rechercher un emplacement'],
            ['#btnPlanLegend', 'Afficher ou masquer la légende'],
            ['#btnPlanPrint', 'Imprimer'],
            ['#btnPlanPdf', 'Exporter en PDF'],
            ['#btnPlanFit', 'Adapter le plan'],
            ['#btnPlanFullscreen', 'Plein écran'],
            ['#btnPlanCancelEdit', 'Quitter l’édition']
        ];
        const container = document.createElement('div');
        container.className = 'plans-mobile-tools-list';
        items.forEach(([selector, label]) => {
            const source = document.querySelector(selector);
            if (!source || source.hidden || source.disabled) return;
            const button = document.createElement('button');
            button.type = 'button';
            button.className = 'plans-mobile-tool-action';
            button.textContent = label;
            button.addEventListener('click', () => {
                source.click();
                state.panel?.close?.('action');
            });
            container.appendChild(button);
        });
        closePanel();
        state.panel = ui()?.sheet?.open?.({
            title: 'Actions du plan',
            description: 'Consultation, localisation, impression et affichage.',
            trigger,
            className: 'plans-mobile-panel plans-mobile-panel--actions',
            content: container
        }) || null;
    }

    function buildCommandBar() {
        if (state.commandBar || !root) return;
        const bar = document.createElement('nav');
        bar.className = 'plans-mobile-commandbar';
        bar.setAttribute('aria-label', 'Actions rapides du plan');
        bar.innerHTML = `
            <button type="button" data-plan-mobile-command="list"><span aria-hidden="true">☰</span><span>Plans</span></button>
            <button type="button" data-plan-mobile-command="rail"><span aria-hidden="true">＋</span><span>Objets</span></button>
            <button type="button" data-plan-mobile-command="tools"><span aria-hidden="true">⌁</span><span>Outils</span></button>
            <button type="button" data-plan-mobile-command="details"><span aria-hidden="true">ⓘ</span><span>Détails</span></button>
            <button type="button" data-plan-mobile-command="actions"><span aria-hidden="true">•••</span><span>Actions</span></button>
            <button type="button" data-plan-mobile-command="save" class="plans-mobile-commandbar__save"><span aria-hidden="true">✓</span><span>Enregistrer</span></button>`;
        bar.addEventListener('click', (event) => {
            const button = event.target.closest('[data-plan-mobile-command]');
            if (!button) return;
            const command = button.dataset.planMobileCommand;
            if (command === 'list') openList(button);
            if (command === 'rail') openRail(button);
            if (command === 'tools') openTools(button);
            if (command === 'details') openInspector(button);
            if (command === 'actions') openActions(button);
            if (command === 'save') clickOriginal('#btnPlanSave');
        });
        root.appendChild(bar);
        state.commandBar = bar;
    }

    function syncCommandBar() {
        buildCommandBar();
        if (!state.commandBar) return;
        state.commandBar.hidden = !isAdaptive() || Page.isCreateFlow;
        const selected = hasPlan();
        const editing = canEdit();
        const buttons = Object.fromEntries(Array.from(state.commandBar.querySelectorAll('[data-plan-mobile-command]')).map((button) => [button.dataset.planMobileCommand, button]));
        if (buttons.list) buttons.list.hidden = Page.isDedicatedEditor && selected;
        if (buttons.rail) {
            buttons.rail.disabled = !selected;
            buttons.rail.querySelector('span:last-child').textContent = editing ? 'Objets' : 'Localiser';
        }
        if (buttons.tools) buttons.tools.hidden = !editing;
        if (buttons.details) buttons.details.disabled = !selected;
        if (buttons.actions) buttons.actions.disabled = !selected;
        if (buttons.save) {
            buttons.save.hidden = !editing;
            buttons.save.disabled = !Page.dirty;
        }
        state.commandBar.classList.toggle('has-unsaved', !!Page.dirty);
    }

    function enforceLightEditor() {
        const structural = [
            '[data-tool="add:mur"]',
            '[data-tool="add:cloison"]',
            '[data-tool="add:cloison_grille"]',
            '[data-tool="add:porte"]',
            '[data-tool="add:fenetre"]',
            '.plans-angle-snap'
        ];
        structural.forEach((selector) => {
            document.querySelectorAll(selector).forEach((node) => {
                node.classList.toggle('plans-mobile-structural-tool', isLightEditor());
                node.setAttribute('aria-hidden', isLightEditor() ? 'true' : 'false');
            });
        });
        if (isLightEditor() && /^add:(mur|cloison|cloison_grille|porte|fenetre)$/.test(String(Page.tool || ''))) {
            Page.setTool?.('select');
        }
    }

    function prepareCreateFlow() {
        if (!Page.isCreateFlow || !isAdaptive() || state.flowPrepared) return;
        const layout = document.querySelector('.plans-create-layout');
        const steps = Array.from(document.querySelectorAll('.plans-create-main-card > .plans-create-block'));
        const preview = document.querySelector('.plans-create-preview-card');
        const actions = document.querySelector('.plans-create-actions');
        if (!layout || steps.length < 3 || !preview || !actions || !global.MobileFlow?.create) return;

        state.flowPrepared = true;
        layout.dataset.msFlow = '1';
        layout.dataset.msFlowStorage = 'magestock:plans:create:v2';
        steps.slice(0, 3).forEach((step, index) => {
            step.dataset.msFlowStep = String(index + 1);
            step.classList.add('plans-mobile-create-step');
        });
        preview.dataset.msFlowStep = '4';
        preview.classList.add('plans-mobile-create-step');

        const named = [
            ['#planCreateWidth', 'widthM'],
            ['#planCreateHeight', 'heightM'],
            ['#planCreateFrame', 'createFrame'],
            ['#planCreateFrameType', 'frameType'],
            ['#planCreateFrameThickness', 'frameThickness']
        ];
        named.forEach(([selector, name]) => {
            const control = document.querySelector(selector);
            if (control && !control.name) control.name = name;
        });

        const progress = document.createElement('div');
        progress.className = 'plans-mobile-create-progress';
        progress.innerHTML = `
            <div class="plans-mobile-create-progress__copy"><strong>Création guidée</strong><span>Étape <b data-ms-flow-current>1</b> sur <b data-ms-flow-total>4</b></span></div>
            <div class="plans-mobile-create-progress__bar" data-ms-flow-progress></div>
            <div class="plans-mobile-create-progress__steps" aria-label="Étapes de création">
                <button type="button" data-ms-flow-indicator="1" data-ms-flow-go="1">Informations</button>
                <button type="button" data-ms-flow-indicator="2" data-ms-flow-go="2">Dimensions</button>
                <button type="button" data-ms-flow-indicator="3" data-ms-flow-go="3">Contour</button>
                <button type="button" data-ms-flow-indicator="4" data-ms-flow-go="4">Vérification</button>
            </div>`;
        layout.insertBefore(progress, layout.firstChild);
        state.createProgress = progress;
        state.createPreview = preview;

        steps[0].insertAdjacentHTML('beforeend', '<div class="plans-mobile-create-nav"><span></span><button type="button" class="btn btn-primary" data-ms-flow-next>Continuer</button></div>');
        steps[1].insertAdjacentHTML('beforeend', '<div class="plans-mobile-create-nav"><button type="button" class="btn btn-secondary" data-ms-flow-back>Retour</button><button type="button" class="btn btn-primary" data-ms-flow-next>Continuer</button></div>');
        steps[2].insertAdjacentHTML('beforeend', '<div class="plans-mobile-create-nav"><button type="button" class="btn btn-secondary" data-ms-flow-back>Retour</button><button type="button" class="btn btn-primary" data-ms-flow-next>Vérifier</button></div>');
        state.createActionsHome = { parent: actions.parentNode, next: actions.nextSibling, actions };
        preview.appendChild(actions);
        actions.classList.add('plans-mobile-create-actions');
        actions.insertAdjacentHTML('afterbegin', '<button type="button" class="btn btn-secondary plans-mobile-create-back" data-ms-flow-back>Retour</button>');

        state.flow = global.MobileFlow.create(layout, {
            storageKey: 'magestock:plans:create:v2',
            onChange: () => {
                Page.updateCreatePreview?.();
                global.setTimeout(() => document.activeElement?.scrollIntoView?.({ block: 'center' }), 50);
            }
        });
        Page.updateCreatePreview?.();
        syncCreateFlowMode();
    }

    function syncCreateFlowMode() {
        if (!state.flowPrepared || !state.flow) return;
        const adaptive = isAdaptive();
        const actions = state.createActionsHome?.actions;
        const preview = state.createPreview;

        if (state.createProgress) state.createProgress.hidden = !adaptive;
        document.querySelectorAll('.plans-mobile-create-nav, .plans-mobile-create-back').forEach((node) => {
            node.hidden = !adaptive;
        });

        if (actions) {
            if (adaptive && preview && actions.parentNode !== preview) {
                preview.appendChild(actions);
            } else if (!adaptive && state.createActionsHome?.parent && actions.parentNode !== state.createActionsHome.parent) {
                const { parent, next } = state.createActionsHome;
                if (next && next.parentNode === parent) parent.insertBefore(actions, next);
                else parent.appendChild(actions);
            }
        }

        if (adaptive) {
            state.flow.update(false);
            return;
        }

        state.flow.steps.forEach((step) => {
            step.hidden = false;
            step.removeAttribute('inert');
            step.setAttribute('aria-hidden', 'false');
        });
    }

    function applyPolicy() {
        const next = resolveProfile();
        if (state.profile !== next) closePanel();
        state.profile = next;
        root.dataset.planDevicePolicy = next;
        root.classList.toggle('plans-mobile-policy', next !== 'desktop');
        root.classList.toggle('plans-mobile-policy--light', isLightEditor());
        root.classList.toggle('plans-mobile-policy--architect', next === 'tablet-landscape');
        root.classList.toggle('plans-mobile-policy--desktop', next === 'desktop');
        document.documentElement.dataset.msPlanPolicy = next;
        enforceLightEditor();
        if (isAdaptive()) prepareCreateFlow();
        syncCreateFlowMode();
        syncCommandBar();
        if (hasPlan()) global.setTimeout(() => Page.fitCanvas?.(), 80);
    }

    Page.init = async function initPlansWithMobilePolicy(...args) {
        const result = await state.original.init.apply(this, args);
        buildCommandBar();
        applyPolicy();
        return result;
    };

    Page.renderList = function renderPlansListWithMobilePolicy(...args) {
        const result = state.original.renderList.apply(this, args);
        syncCommandBar();
        return result;
    };

    Page.renderEditor = function renderPlansEditorWithMobilePolicy(...args) {
        const result = state.original.renderEditor.apply(this, args);
        enforceLightEditor();
        syncCommandBar();
        return result;
    };

    Page.openPlan = async function openPlanWithMobilePolicy(...args) {
        const result = await state.original.openPlan.apply(this, args);
        syncCommandBar();
        if (isAdaptive() && hasPlan()) global.setTimeout(() => this.fitCanvas?.(), 90);
        return result;
    };

    Page.closeEditor = function closePlanEditorWithMobilePolicy(...args) {
        closePanel();
        const result = state.original.closeEditor.apply(this, args);
        syncCommandBar();
        return result;
    };

    Page.setDirty = function setPlanDirtyWithMobilePolicy(...args) {
        const result = state.original.setDirty.apply(this, args);
        syncCommandBar();
        return result;
    };

    Page.savePlanFromCreateScreen = async function savePlanCreateWithMobilePolicy(...args) {
        const result = await state.original.savePlanFromCreateScreen.apply(this, args);
        if (!this.isCreateFlow) state.flow?.clearDraft?.();
        syncCommandBar();
        return result;
    };

    document.addEventListener('magestock:devicechange', applyPolicy);
    global.addEventListener('orientationchange', () => global.setTimeout(applyPolicy, 140), { passive: true });
    global.addEventListener('resize', () => {
        global.clearTimeout(state.resizeTimer);
        state.resizeTimer = global.setTimeout(applyPolicy, 140);
    }, { passive: true });

    root.dataset.planMobilePolicyVersion = VERSION;
})(window, document);
