<?php
require __DIR__ . '/includes/bootstrap.php';
$token = isset($_GET['t']) ? (string)$_GET['t'] : '';
$jsonFlags = JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT;
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Carpeta compartida</title>
    <link rel="stylesheet" href="assets/vendor/font-awesome/css/all.min.css">
    <style>
        * { box-sizing: border-box; }
        body { margin: 0; font-family: system-ui, Segoe UI, Roboto, sans-serif; background: #1a1d23; color: #e8eaed; min-height: 100vh; }
        .share-wrap { max-width: 720px; margin: 0 auto; padding: 16px; }
        .share-head { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 16px; }
        .share-head h1 { font-size: 1.15rem; font-weight: 600; margin: 0; flex: 1; min-width: 0; display:flex; align-items:center; gap:10px; }
        .share-home-btn { display:inline-flex; align-items:center; justify-content:center; width:38px; height:38px; border-radius: 10px; border: 1px solid rgba(255,255,255,0.15); background: rgba(255,255,255,0.06); color: inherit; cursor: pointer; flex-shrink:0; }
        .share-home-btn:hover { background: rgba(255,255,255,0.12); }
        .share-title-link { display:inline-flex; align-items:center; gap:8px; min-width:0; color: inherit; text-decoration:none; cursor:pointer; }
        .share-title-link:hover { text-decoration: underline; text-underline-offset: 3px; }
        .share-crumb { font-size: 0.85rem; opacity: 0.85; word-break: break-all; }
        .share-up { display: inline-flex; align-items: center; gap: 6px; padding: 8px 14px; border: 1px solid rgba(255,255,255,0.15); border-radius: 8px; background: rgba(255,255,255,0.06); color: inherit; cursor: pointer; font-size: 0.9rem; }
        .share-up:disabled { opacity: 0.4; cursor: not-allowed; }
        .share-list { border: 1px solid rgba(255,255,255,0.1); border-radius: 10px; overflow: hidden; }
        .share-row { display: flex; align-items: center; gap: 10px; padding: 10px 14px; border-bottom: 1px solid rgba(255,255,255,0.08); cursor: pointer; }
        .share-row:last-child { border-bottom: 0; }
        .share-row:hover { background: rgba(255,255,255,0.06); }
        .share-row i { width: 22px; text-align: center; opacity: 0.85; }
        .share-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .share-meta { font-size: 0.8rem; opacity: 0.65; flex-shrink: 0; }
        /* Misma barra que el visor de archivos (main.css .file-viewer-float-toolbar) */
        .share-wrap .share-file-toolbar.file-viewer-float-toolbar {
            position: static;
            margin-left: auto;
            flex-shrink: 0;
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            justify-content: flex-end;
            gap: 8px;
            padding: 8px 10px;
            border-radius: 12px;
            background: rgba(30,30,30,0.82);
            border: 1px solid rgba(255,255,255,0.12);
            box-shadow: 0 8px 32px rgba(0,0,0,0.35);
            backdrop-filter: blur(16px);
            -webkit-backdrop-filter: blur(16px);
            pointer-events: auto;
        }
        .share-wrap .share-file-toolbar.file-viewer-float-toolbar button {
            background: rgba(255,255,255,0.1);
            border: none;
            color: #fff;
            border-radius: 8px;
            width: 38px;
            height: 38px;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 0.95rem;
            transition: background 0.15s ease, transform 0.1s ease;
        }
        .share-wrap .share-file-toolbar.file-viewer-float-toolbar button:hover {
            background: rgba(255,255,255,0.2);
            transform: scale(1.04);
        }
        .share-row-file { cursor: pointer; }
        .share-err { padding: 20px; text-align: center; color: #f88; }
        .share-empty { padding: 24px; text-align: center; opacity: 0.7; }
    </style>
</head>
<body>
    <div class="share-wrap">
        <div class="share-head">
            <h1 id="shareTitle">
                <button type="button" class="share-home-btn" id="shareHomeBtn" title="Inicio" aria-label="Inicio">
                    <i class="fas fa-home" aria-hidden="true"></i>
                </button>
                <a href="#" class="share-title-link" id="shareTitleLink" aria-label="Ir a la raíz de la carpeta compartida">
                    <i class="fas fa-folder-open" aria-hidden="true"></i>
                    <span id="shareRootName">…</span>
                </a>
            </h1>
            <button type="button" class="share-up" id="shareUp" disabled title="Subir carpeta"><i class="fas fa-level-up-alt"></i> Subir</button>
        </div>
        <div class="share-crumb" id="shareCrumb"></div>
        <div id="shareMain" style="margin-top:14px;"></div>
    </div>
    <script>
        const SHARE_TOKEN = <?php echo json_encode($token, $jsonFlags); ?>;
        const INDEX_API = 'index.php';

        async function shareList(path) {
            const res = await fetch(INDEX_API + '?action=shareList', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ token: SHARE_TOKEN, path: path || '' }),
                credentials: 'same-origin'
            });
            return await res.json();
        }

        let currentPath = '';

        function render(data) {
            const main = document.getElementById('shareMain');
            const up = document.getElementById('shareUp');
            const crumb = document.getElementById('shareCrumb');
            const rootNameEl = document.getElementById('shareRootName');

            if (!data || !data.success) {
                main.innerHTML = '<div class="share-err">' + (data && data.error ? String(data.error) : 'No se pudo cargar') + '</div>';
                return;
            }

            rootNameEl.textContent = data.rootName || 'Carpeta';
            currentPath = data.path || '';
            up.disabled = !currentPath;

            const parts = currentPath ? currentPath.split('/').filter(Boolean) : [];
            const segs = [];
            let acc = '';
            parts.forEach((p) => {
                acc = acc ? (acc + '/' + p) : p;
                segs.push({ label: p, path: acc });
            });
            crumb.innerHTML = segs.length
                ? '<span style="opacity:0.6">Ruta:</span> ' + segs.map((s, i) =>
                    '<a href="#" data-path="' + s.path.replace(/"/g, '&quot;') + '" style="color:#8ab4f8">' + s.label.replace(/</g, '&lt;') + '</a>'
                    + (i < segs.length - 1 ? ' / ' : '')
                ).join('')
                : '';

            crumb.querySelectorAll('a[data-path]').forEach((a) => {
                a.addEventListener('click', (e) => {
                    e.preventDefault();
                    const p = a.getAttribute('data-path') || '';
                    load(p);
                });
            });

            const items = data.items || [];
            if (items.length === 0) {
                main.innerHTML = '<div class="share-empty">Carpeta vacía</div>';
                return;
            }

            items.sort((a, b) => {
                const da = a.type === 'dir' ? 0 : 1;
                const db = b.type === 'dir' ? 0 : 1;
                if (da !== db) return da - db;
                return (a.name || '').localeCompare(b.name || '', undefined, { sensitivity: 'base' });
            });

            const list = document.createElement('div');
            list.className = 'share-list';
            items.forEach((it) => {
                const row = document.createElement('div');
                const isDir = it.type === 'dir';
                row.className = 'share-row' + (isDir ? '' : ' share-row-file');
                const rel = it.relPath || '';
                const viewUrl = 'file.php?t=' + encodeURIComponent(SHARE_TOKEN) + '&rel=' + encodeURIComponent(rel);
                const downloadUrl = viewUrl + '&download=1';
                if (isDir) {
                    row.innerHTML =
                        '<i class="fas fa-folder" aria-hidden="true"></i>' +
                        '<span class="share-name">' + (it.name || '').replace(/</g, '&lt;') + '</span>' +
                        '<span class="share-meta">Carpeta</span>';
                    row.addEventListener('click', () => load(rel));
                } else {
                    row.innerHTML =
                        '<i class="fas fa-file" aria-hidden="true"></i>' +
                        '<span class="share-name">' + (it.name || '').replace(/</g, '&lt;') + '</span>' +
                        '<span class="share-meta">' + formatSize(it.size) + '</span>' +
                        '<div class="file-viewer-float-toolbar share-file-toolbar" role="toolbar" aria-label="Acciones del archivo">' +
                        '<button type="button" class="external-btn" title="Ver"><i class="fas fa-external-link-alt" aria-hidden="true"></i></button>' +
                        '<button type="button" class="download-btn" title="Descargar"><i class="fas fa-download" aria-hidden="true"></i></button>' +
                        '</div>';
                    const openView = () => window.open(viewUrl, '_blank', 'noopener,noreferrer');
                    row.querySelector('.external-btn').addEventListener('click', (e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        openView();
                    });
                    row.querySelector('.download-btn').addEventListener('click', (e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        const a = document.createElement('a');
                        a.href = downloadUrl;
                        a.rel = 'noopener';
                        const baseName = (it.name || 'archivo').replace(/[/\\?%*:|"<>]/g, '_');
                        a.download = baseName;
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                    });
                    row.addEventListener('click', (e) => {
                        if (e.target.closest('.share-file-toolbar')) return;
                        openView();
                    });
                }
                list.appendChild(row);
            });
            main.innerHTML = '';
            main.appendChild(list);
        }

        function formatSize(n) {
            const b = Number(n) || 0;
            if (b < 1024) return b + ' B';
            if (b < 1024 * 1024) return (b / 1024).toFixed(1) + ' KB';
            return (b / (1024 * 1024)).toFixed(1) + ' MB';
        }

        async function load(path) {
            const main = document.getElementById('shareMain');
            main.innerHTML = '<div class="share-empty">Cargando…</div>';
            try {
                const data = await shareList(path);
                render(data);
            } catch (e) {
                main.innerHTML = '<div class="share-err">Error de red</div>';
            }
        }

        document.getElementById('shareUp').addEventListener('click', () => {
            if (!currentPath) return;
            const parts = currentPath.split('/').filter(Boolean);
            parts.pop();
            load(parts.join('/'));
        });

        const goHome = () => load('');
        document.getElementById('shareHomeBtn').addEventListener('click', (e) => {
            e.preventDefault();
            goHome();
        });
        document.getElementById('shareTitleLink').addEventListener('click', (e) => {
            e.preventDefault();
            goHome();
        });

        if (!SHARE_TOKEN) {
            document.getElementById('shareMain').innerHTML = '<div class="share-err">Falta el enlace de compartición</div>';
        } else {
            load('');
        }
    </script>
</body>
</html>
