<!DOCTYPE html>
<html>
<head>
    <title>Homepage Editor - Canvas Mode</title>
    <!-- Use local css -->
    <link rel="stylesheet" href="<?php echo base_url('assets/css/frontend.css'); ?>">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- Interact.js for Drag and Resize -->
    <script src="https://cdn.jsdelivr.net/npm/interactjs/dist/interact.min.js"></script>
    <style>
        body {
            margin: 0;
            overflow: auto; /* Allow scrolling */
            font-family: 'Montserrat', sans-serif;
            background: #f0f0f0;
            display: flex;
            min-height: 100vh;
        }
        
        /* Sidebar */
        #sidebar {
            width: 250px;
            background: #fff;
            border-right: 1px solid #ddd;
            display: flex;
            flex-direction: column;
            z-index: 1000;
            box-shadow: 2px 0 10px rgba(0,0,0,0.05);
            position: fixed; /* Fixed sidebar */
            top: 0;
            bottom: 0;
            left: 0;
            height: 100vh;
        }
        
        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid #eee;
        }
        
        .sidebar-header h2 {
            font-size: 16px;
            margin: 0;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        
        .project-list {
            flex: 1;
            overflow-y: auto;
            padding: 10px;
        }
        
        .project-thumb {
            width: 100%;
            margin-bottom: 10px;
            cursor: grab;
            position: relative;
            background: #f9f9f9;
            border: 1px solid #eee;
            border-radius: 4px;
            overflow: hidden;
            transition: all 0.2s;
        }
        
        .project-thumb:hover {
            border-color: #000;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        .project-thumb img {
            width: 100%;
            height: 120px;
            object-fit: cover;
            display: block;
        }
        
        .project-title {
            padding: 8px;
            font-size: 11px;
            font-weight: 600;
            text-align: center;
        }

        .controls {
            padding: 20px;
            border-top: 1px solid #eee;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        
        .save-btn {
            background: #000;
            color: #fff;
            border: none;
            padding: 12px;
            text-transform: uppercase;
            font-weight: 600;
            cursor: pointer;
            width: 100%;
        }
        
        .back-btn {
            background: transparent;
            color: #666;
            border: 1px solid #ddd;
            padding: 12px;
            text-transform: uppercase;
            font-weight: 600;
            cursor: pointer;
            width: 100%;
            text-align: center;
            text-decoration: none;
            font-size: 13px;
        }

        /* Canvas Area */
        #canvas-container {
            flex: 1;
            position: relative;
            background: #e5e5e5;
            display: flex;
            justify-content: center;
            padding: 40px;
            margin-left: 250px; /* Offset for fixed sidebar */
            min-height: 100vh;
        }
        
        #artboard {
            width: 1440px; /* Fixed Reference Width */
            height: 5000px; /* Huge height for infinite scrolling */
            background: #fff;
            position: relative; /* Absolute children relative to this */
            box-shadow: 0 0 50px rgba(0,0,0,0.1);
            overflow: hidden; /* Mask content */
            flex-shrink: 0; /* Prevent shrinking */
        }
        
        /* Draggable Items on Canvas */
        .canvas-item {
            position: absolute;
            box-sizing: border-box;
            user-select: none;
            touch-action: none;
            cursor: grab;
            border: 3px solid transparent; /* Selection border */
            transition: border-color 0.2s;
        }
        
        .canvas-item.selected {
            border-color: var(--color-go-primary);
            z-index: 1000 !important;
        }
        
        .canvas-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            pointer-events: none; /* Let clicks pass to container for drag */
            display: block;
        }
        
        .remove-btn {
            position: absolute;
            top: -12px;
            right: -12px;
            width: 24px;
            height: 24px;
            background: red;
            color: white;
            border-radius: 50%;
            display: none;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 12px;
            z-index: 2000;
        }
        
        .canvas-item.selected .remove-btn {
            display: flex;
        }
        
        /* Loading Overlay */
        #loader {
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(255,255,255,0.8);
            z-index: 9999;
            display: none;
            align-items: center;
            justify-content: center;
        }

        /* Toggle Sidebar */
        .toggle-btn {
            position: absolute;
            top: 10px;
            right: -30px;
            width: 30px;
            height: 30px;
            background: #000;
            color: #fff;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 0 4px 4px 0;
            z-index: 2000;
        }

        #sidebar.collapsed {
            transform: translateX(-100%);
        }

        #canvas-container.full-width {
            margin-left: 0;
        }

    </style>
</head>
<body>

<div id="loader"><i class="fas fa-spinner fa-spin fa-2x"></i></div>

<div id="sidebar">
    <button class="toggle-btn" onclick="toggleSidebar()"><i class="fas fa-chevron-left"></i></button>
    <div class="sidebar-header">
        <h2>Projects Library</h2>
        <small>Drag to Canvas</small>
    </div>
    
    <div class="project-list" id="projectList">
        <?php foreach ($projects as $project): ?>
            <?php 
                // Smart Fallback Logic matches projects.php
                // Priority 1: Custom Thumbnail
                if (!empty($project->thumbnail_path) && file_exists(FCPATH . $project->thumbnail_path)) {
                    $media_source = $project->thumbnail_path;
                    $media_type = $project->thumbnail_type;
                } 
                // Priority 2: Selected Thumbnail (Flagged)
                elseif (!empty($project->selected_thumb)) {
                     $media_source = $project->selected_thumb;
                     $media_type = $project->selected_thumb_type ?: 'image';
                }
                // Priority 3: Raw Project Media (Legacy)
                elseif (!empty($project->media_path) && file_exists(FCPATH . $project->media_path)) {
                    $media_source = $project->media_path;
                    $media_type = $project->media_type ?: 'image';
                }
                // Priority 4: Fallback from Gallery (First Item)
                elseif (!empty($project->fallback_media)) {
                     $media_source = $project->fallback_media;
                     $media_type = $project->fallback_type ?: 'image';
                }
                // Priority 5: Placeholder
                else {
                    $media_source = 'assets/images/placeholder.jpg';
                    $media_type = 'image';
                }
            ?>
            <div class="project-thumb" draggable="true" 
                 data-id="<?php echo $project->id; ?>" 
                 data-type="<?php echo $media_type; ?>"
                 data-img="<?php echo base_url($media_source); ?>?v=<?php echo time(); ?>">
                <?php if ($media_type == 'video'): ?>
                    <video src="<?php echo base_url($media_source); ?>?v=<?php echo time(); ?>" style="width:100%; height:120px; object-fit:cover;" muted preload="metadata"></video>
                    <i class="fas fa-video" style="position:absolute; top:5px; right:5px; color:white; text-shadow:0 1px 2px rgba(0,0,0,0.5);"></i>
                <?php else: ?>
                    <img src="<?php echo base_url($media_source); ?>?v=<?php echo time(); ?>" loading="lazy">
                <?php endif; ?>
                <div class="project-title"><?php echo $project->title; ?></div>
            </div>
        <?php endforeach; ?>
    </div>
    
    <div class="controls">
        <div style="margin-bottom: 10px;">
            <label style="font-size: 11px; font-weight: 600; text-transform: uppercase;">Page Height (px):</label>
            <input type="number" id="canvasHeightInput" value="<?php echo isset($canvas_height) && $canvas_height ? $canvas_height : 3000; ?>" class="form-control" style="width: 100%; border: 1px solid #ddd; padding: 5px;" onchange="updateCanvasHeight(this.value)">
        </div>
        <button class="save-btn" onclick="saveLayout()">Save Layout</button>
        <a href="<?php echo base_url('admin/dashboard'); ?>" class="back-btn">Back using Dashboard</a>
    </div>
</div>

<div id="canvas-container">
    <div id="artboard" data-tap-to-deselect="true" style="height: <?php echo isset($canvas_height) && $canvas_height ? $canvas_height : 3000; ?>px;">
        <!-- Canvas Items will be injected here -->
    </div>
</div>

<script>
    function toggleSidebar() {
        const sidebar = document.getElementById('sidebar');
        const container = document.getElementById('canvas-container');
        const btnIcon = document.querySelector('.toggle-btn i');
        
        sidebar.classList.toggle('collapsed');
        container.classList.toggle('full-width');
        
        if(sidebar.classList.contains('collapsed')) {
            btnIcon.classList.remove('fa-chevron-left');
            btnIcon.classList.add('fa-chevron-right');
        } else {
            btnIcon.classList.add('fa-chevron-left');
            btnIcon.classList.remove('fa-chevron-right');
        }
    }

    const artboard = document.getElementById('artboard');
    const projectList = document.getElementById('projectList');
    const ARTBOARD_WIDTH = 1440; // Reference width
    
    let canvasItems = [];
    
    // Initialize Interact.js
    interact('.canvas-item')
        .draggable({
            listeners: {
                start (event) {
                    // Bring to front on drag start
                    const target = event.target;
                    target.parentNode.appendChild(target);
                },
                move (event) {
                    const target = event.target;
                    // Current position from style (or data-attribute fallback)
                    const x = (parseFloat(target.style.left) || 0) + event.dx;
                    const y = (parseFloat(target.style.top) || 0) + event.dy;

                    // Update style for visual move - Absolute Position
                    target.style.left = x + 'px';
                    target.style.top = y + 'px';

                    // Sync data attributes (for logic)
                    target.setAttribute('data-x', x);
                    target.setAttribute('data-y', y);
                    
                    // Clear transform if any
                    target.style.transform = 'none';
                }
            },
            modifiers: [
                // Allowed free movement - Removed restriction that caused snap-back
            ]
        })
        .resizable({
            edges: { left: true, right: true, bottom: true, top: true },
            listeners: {
                move: function (event) {
                    let x = parseFloat(event.target.style.left) || 0;
                    let y = parseFloat(event.target.style.top) || 0;

                    // Update position if resizing from left/top
                    x += event.deltaRect.left;
                    y += event.deltaRect.top;

                    Object.assign(event.target.style, {
                        width: `${event.rect.width}px`,
                        height: `${event.rect.height}px`,
                        left: `${x}px`,
                        top: `${y}px`,
                        transform: 'none' // Clear transform
                    });

                    Object.assign(event.target.dataset, { x, y });
                }
            }
        })
        .on('tap', function(event) {
            // Deselect all
            document.querySelectorAll('.canvas-item').forEach(el => el.classList.remove('selected'));
            // Select this & Bring to Front
            const target = event.currentTarget;
            target.classList.add('selected');
            target.parentNode.appendChild(target);
            event.stopPropagation();
        });
        
    // Deselect click on artboard
    artboard.addEventListener('click', function(e) {
        if(e.target === artboard) {
            document.querySelectorAll('.canvas-item').forEach(el => el.classList.remove('selected'));
        }
    });

    // Handle Drag from Sidebar
    projectList.addEventListener('dragstart', (e) => {
        if(e.target.closest('.project-thumb')) {
            const thumb = e.target.closest('.project-thumb');
            e.dataTransfer.setData('curr_id', thumb.dataset.id);
            e.dataTransfer.setData('curr_img', thumb.dataset.img);
            e.dataTransfer.setData('curr_type', thumb.dataset.type);
        }
    });

    artboard.addEventListener('dragover', (e) => {
        e.preventDefault();
    });

    artboard.addEventListener('drop', (e) => {
        e.preventDefault();
        const id = e.dataTransfer.getData('curr_id');
        const img = e.dataTransfer.getData('curr_img');
        const type = e.dataTransfer.getData('curr_type');
        
        if(id && img) {
            // Calculate drop position relative to artboard
            const rect = artboard.getBoundingClientRect();
            const x = e.clientX - rect.left - 100; // Center offset approx
            const y = e.clientY - rect.top - 75;
            
            addItemToCanvas({
                project_id: id,
                img: img,
                type: type,
                x: x > 0 ? x : 0,
                y: y > 0 ? y : 0,
                width: 300, // Default width
                height: 225, // Default height
                z_index: canvasItems.length + 1
            });
        }
    });

    function addItemToCanvas(data) {
        const div = document.createElement('div');
        div.className = 'canvas-item selected'; // Auto select
        div.style.width = data.width + 'px';
        div.style.height = data.height + 'px';
        
        // Use Absolute Display Position instead of Transform (More Robust for Saving)
        div.style.left = data.x + 'px';
        div.style.top = data.y + 'px';
        
        // Store explicit data attributes
        div.setAttribute('data-x', data.x);
        div.setAttribute('data-y', data.y);
        div.setAttribute('data-project-id', data.project_id);
        div.style.zIndex = data.z_index;
        
        let content = '';
        if (data.type === 'video') {
            content = `<video src="${data.img}" muted loop autoplay playsinline style="width:100%; height:100%; object-fit:cover; pointer-events:none;"></video>`;
        } else {
            content = `<img src="${data.img}" style="width:100%; height:100%; object-fit:cover; pointer-events:none; display:block;">`;
        }

        // Label Logic
        const labelHtml = `
            <div class="project-label" style="
              position: absolute;
              bottom: -30px;
              left: 0;
              text-align: left;
              width: 100%;
              padding-top: 8px;
              pointer-events: none;
            ">
              <h3 style="
                font-family: 'Inter', sans-serif;
                font-size: 0.75rem;
                font-weight: 400;
                letter-spacing: 0.05em;
                text-transform: uppercase;
                color: #666;
                margin: 0;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
              ">
                <span style="color: #666;">${data.title || ''}</span>
                ${data.model ? `<span style="margin: 0 4px; color: #999;">|</span><span style="color: #999;">${data.model}</span>` : ''}
              </h3>
            </div>
        `;

        div.innerHTML = `
            ${content}
            ${labelHtml}
            <div class="remove-btn" onclick="removeItem(this)"><i class="fas fa-times"></i></div>
            <div class="resize-handle"></div>
        `;
        
        // Remove selection from others
        document.querySelectorAll('.canvas-item').forEach(el => el.classList.remove('selected'));
        
        artboard.appendChild(div);
        
        return div;
    }
    
    window.removeItem = function(el) {
        // Find the parent canvas-item and remove it
        const item = el.closest('.canvas-item');
        if (item) {
            item.remove();
        }
    }

    function saveLayout() {
        const loader = document.getElementById('loader');
        loader.style.display = 'flex';
        
        const items = document.querySelectorAll('.canvas-item');
        const layoutData = [];
        const currentHeight = document.getElementById('canvasHeightInput').value;
        
        items.forEach((item, index) => {
            // Get position explicitly from style (Robust)
            const x = parseFloat(item.style.left) || 0;
            const y = parseFloat(item.style.top) || 0;
            const w = parseFloat(item.style.width);
            const h = parseFloat(item.style.height);
            
            layoutData.push({
                project_id: item.getAttribute('data-project-id'),
                x: x, 
                y: y,
                width: w,
                height: h,
                z_index: index + 1
            });
        });
        
        // ... (fetch logic remains same) ...
        fetch('<?php echo base_url('admin/update_homepage_layout'); ?>', {
            method: 'POST',
            body: JSON.stringify({ items: layoutData, canvas_height: currentHeight }),
            headers: { 'Content-Type': 'application/json' }
        })
        .then(res => res.json())
        .then(data => {
            loader.style.display = 'none';
            if(data.success) {
                alert('Layout Saved Successfully!');
            } else {
                alert('Error Saving: ' + (data.message || 'Unknown error'));
            }
        })
        .catch(err => {
            loader.style.display = 'none';
            console.error(err);
            alert('Network Error');
        });
    }

    // Load existing layout
    const savedLayout = <?php echo json_encode($layout ?? []); ?>;
    const projectsLookup = {};
    <?php foreach ($projects as $p): ?>
    <?php 
        // Re-calculate for JS Lookup (Smart Fallback)
        $js_source = $p->media_path;
        $js_type = $p->media_type ?: 'image';
        
        // Prioritize custom thumbnail IF it exists physically
        if (!empty($p->thumbnail_path) && file_exists(FCPATH . $p->thumbnail_path)) {
            $js_source = $p->thumbnail_path;
            $js_type = $p->thumbnail_type;
        }
        // Priority 2: Selected Thumbnail (Flagged)
        elseif (!empty($p->selected_thumb)) {
             $js_source = $p->selected_thumb;
             $js_type = $p->selected_thumb_type ?: 'image';
        }
        // Priority 3: Raw Project Media (Legacy)
        elseif (!empty($p->media_path) && file_exists(FCPATH . $p->media_path)) {
            $js_source = $p->media_path;
            $js_type = $p->media_type ?: 'image';
        }
        // Priority 4: Fallback
        elseif (!empty($p->fallback_media)) {
             $js_source = $p->fallback_media;
             $js_type = $p->fallback_type ?: 'image';
        }
        // Final safety net
        else {
             $js_source = 'assets/images/placeholder.jpg';
             $js_type = 'image';
        }
    ?>
    projectsLookup[<?php echo $p->id; ?>] = {
        img: "<?php echo base_url($js_source); ?>?v=<?php echo time(); ?>",
        type: "<?php echo $js_type; ?>",
        title: "<?php echo addslashes($p->title); ?>",
        model: "<?php echo isset($p->model_name) ? addslashes($p->model_name) : ''; ?>"
    };
    <?php endforeach; ?>

    if(savedLayout && savedLayout.length > 0) {
        savedLayout.forEach(item => {
            const projectData = projectsLookup[item.project_id];
            if(projectData) {
                addItemToCanvas({
                    project_id: item.project_id,
                    img: projectData.img,
                    type: projectData.type,
                    title: projectData.title,
                    model: projectData.model,
                    x: parseFloat(item.x_pos),
                    y: parseFloat(item.y_pos),
                    width: parseFloat(item.width),
                    height: parseFloat(item.height),
                    z_index: item.z_index
                });
            }
        });
    }
</script>

</body>
</html>
