// grid.js — "Grid mode" plugin for browse. Loads the classifier tool
// as an iframe scoped to the current directory so users get classifier's
// full bulk-rename workflow without leaving browse.
//
// Availability: only inside an `incoming/` subtree (case-insensitive).
// Working/staging support the classifier tool at the URL level, but
// they're file-staging contexts in normal use, not rename surfaces —
// the Grid toggle is for the inbound side. Outside an incoming/ path,
// the Grid button is hidden entirely (no explanatory empty state).
//
// Iframe src resolution: <currentDirURL>/classifier.html. Iframe
// embedding only works in server mode; file:// pages don't get the
// Grid toggle.
(function () {
    'use strict';

    var state = window.app.state;
    var mounted = false;

    function classifierAvailableHere() {
        // Grid is the classifier-embedded view. Only meaningful in
        // incoming/ — that's where bulk-rename actually happens.
        var path = (window.location && window.location.pathname) || '';
        return /\/incoming(\/|$)/i.test(path);
    }

    function activate() {
        var host = document.getElementById('gridView');
        if (!host) return;
        if (mounted) return;
        if (state.source !== 'server' || !classifierAvailableHere()) return;

        // Compute the iframe src: current page's directory + classifier.html.
        var pathname = window.location.pathname || '/';
        if (!pathname.endsWith('/')) {
            var lastSlash = pathname.lastIndexOf('/');
            pathname = lastSlash >= 0 ? pathname.substring(0, lastSlash + 1) : '/';
        }
        var src = pathname + 'classifier.html';

        host.innerHTML = '';
        var frame = document.createElement('iframe');
        frame.src = src;
        frame.title = 'ZDDC Classifier (Grid mode)';
        frame.style.cssText = 'width:100%;height:100%;border:0;display:block;'
            + 'background:var(--bg);';
        host.appendChild(frame);
        mounted = true;
    }

    // When the user navigates between scopes (client-side rescope on
    // dblclick), the iframe needs to be reloaded for the new path.
    // Callers reset before re-activating.
    function reset() {
        mounted = false;
        var host = document.getElementById('gridView');
        if (host) host.innerHTML = '';
    }

    window.app.modules.grid = {
        activate: activate,
        reset: reset,
        // Hook for events.js to show/hide the Grid toggle button.
        availableHere: function () {
            return state.source === 'server' && classifierAvailableHere();
        }
    };
})();
