<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LiteDiff</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* Custom styles for the diff table */
        body {
            font-family: 'Inter', sans-serif;
        }
        .diff_table {
            width: 100%;
            border-collapse: collapse;
            font-family: monospace;
            font-size: 12px;
        }
        .diff_table th {
            background-color: #f2f2f2;
            padding: 8px;
            text-align: left;
            border: 1px solid #ddd;
        }
        .diff_table td {
            padding: 4px;
            border: 1px solid #ddd;
            vertical-align: top;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
        .diff_header {
            font-weight: bold;
        }
        .diff_next {
            background-color: #e6ffed; /* Green for added */
        }
        .diff_add {
            background-color: #e6ffed;
        }
        .diff_chg {
            background-color: #fff3cd; /* Yellow for changed */
        }
        .diff_sub {
            background-color: #fde2e2; /* Red for deleted */
        }
        .loader {
            border: 8px solid #f3f3f3;
            border-radius: 50%;
            border-top: 8px solid #3498db;
            width: 60px;
            height: 60px;
            animation: spin 2s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body class="bg-gray-100 text-gray-800">

    <div class="container mx-auto p-4 md:p-8">
        <header class="text-center mb-8">
            <h1 class="text-2xl font-bold text-gray-900">Diff files or directories side-by-side</h1>
        </header>

        <div class="bg-white p-6 rounded-lg shadow-lg mb-8">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label for="path1" class="block text-sm font-medium text-gray-700 mb-2">Path 1 (File or Directory):</label>
                    <input type="text" id="path1" name="path1" class="w-full p-3 border border-gray-300 rounded-md focus:ring-indigo-500 focus:border-indigo-500" placeholder="e.g., /path/to/your/first/item">
                </div>
                <div>
                    <label for="path2" class="block text-sm font-medium text-gray-700 mb-2">Path 2 (File or Directory):</label>
                    <input type="text" id="path2" name="path2" class="w-full p-3 border border-gray-300 rounded-md focus:ring-indigo-500 focus:border-indigo-500" placeholder="e.g., /path/to/your/second/item">
                </div>
            </div>
            <div class="mt-6 flex flex-wrap items-center justify-center gap-4">
                <button id="compareBtn" class="bg-indigo-600 text-white font-bold py-3 px-6 rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition duration-300">
                    <i class="fas fa-exchange-alt mr-2"></i>Compare Paths
                </button>
                <div class="mt-2 flex items-center justify-center">
                    <input type="checkbox" id="unifiedMode" name="unifiedMode" class="mr-2" checked>
                    <label for="unifiedMode" class="text-sm text-gray-700 mb-0">Unified diff</label>
                </div>
                <div class="mt-2 flex items-center justify-center">
                    <input type="checkbox" id="includeUnique" name="includeUnique" class="mr-2">
                    <label for="includeUnique" class="text-sm text-gray-700">Include unique files</label>
                </div>
            </div>
        </div>

        <!-- Loading Indicator -->
        <div id="loader" class="hidden flex justify-center items-center my-8">
            <div class="loader"></div>
        </div>
        
        <!-- Error Message -->
        <div id="error-message" class="hidden bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-md relative mb-6" role="alert">
            <strong class="font-bold">Error:</strong>
            <span class="block sm:inline" id="error-text"></span>
        </div>

        <!-- Results Section -->
        <div id="results" class="space-y-6"></div>

    </div>
    
    <!-- CSS for Diff2Html -->
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/diff2html/bundles/css/diff2html.min.css" />
    <script src="https://cdn.jsdelivr.net/npm/diff2html/bundles/js/diff2html.min.js"></script>

    <script>
        document.getElementById('compareBtn').addEventListener('click', async () => {
            const path1 = document.getElementById('path1').value.trim();
            const path2 = document.getElementById('path2').value.trim();
            const unifiedMode = document.getElementById('unifiedMode').checked;
            const mode = unifiedMode ? 'unified' : 'html';
            const includeUnique = document.getElementById('includeUnique').checked;
            const resultsDiv = document.getElementById('results');
            const loader = document.getElementById('loader');
            const errorMessage = document.getElementById('error-message');
            const errorText = document.getElementById('error-text');

            // Clear previous results and errors
            resultsDiv.innerHTML = '';
            errorMessage.classList.add('hidden');

            if (!path1 || !path2) {
                errorText.textContent = 'Please enter paths for both inputs.';
                errorMessage.classList.remove('hidden');
                return;
            }

            // Show loader
            loader.classList.remove('hidden');

            try {
                const response = await fetch('/diff', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ path1, path2, mode, includeUnique }),
                });

                const data = await response.json();

                if (!response.ok) {
                    throw new Error(data.error || 'An unknown error occurred.');
                }

                if (mode === 'html') {
                    displayResults(data.diffs);
                } else if (mode === 'unified') {
                    displayUnifiedDiffs(data.diffs);
                }

            } catch (error) {
                errorText.textContent = error.message;
                errorMessage.classList.remove('hidden');
            } finally {
                // Hide loader
                loader.classList.add('hidden');
            }
        });

        function displayResults(diffs) {
            const resultsDiv = document.getElementById('results');
            if (diffs.length === 0) {
                resultsDiv.innerHTML = '<div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-md"><p class="font-bold">No differences found!</p><p>The directories are identical or no common files were found.</p></div>';
                return;
            }

            diffs.forEach(item => {
                const fileContainer = document.createElement('div');
                fileContainer.className = 'bg-white p-4 rounded-lg shadow-md';

                let headerColor = 'bg-gray-200';
                let statusIcon = '<i class="fas fa-file-alt mr-2"></i>';
                let statusText = '';
                
                if (item.status === 'modified') {
                    headerColor = 'bg-yellow-200 text-yellow-800';
                    statusIcon = '<i class="fas fa-pencil-alt mr-2"></i>';
                    statusText = 'Modified';
                } else if (item.status === 'unique_to_dir1') {
                    headerColor = 'bg-red-200 text-red-800';
                    statusIcon = '<i class="fas fa-minus-circle mr-2"></i>';
                    statusText = `Only in Directory 1`;
                } else if (item.status === 'unique_to_dir2') {
                    headerColor = 'bg-green-200 text-green-800';
                    statusIcon = '<i class="fas fa-plus-circle mr-2"></i>';
                    statusText = `Only in Directory 2`;
                } else if (item.status === 'error') {
                    headerColor = 'bg-red-200 text-red-800';
                    statusIcon = '<i class="fas fa-exclamation-triangle mr-2"></i>';
                    statusText = 'Comparison Error';
                }

                let contentHtml = '';
                if (item.diff) {
                    contentHtml = `<div class="overflow-x-auto mt-4">${item.diff}</div>`;
                } else if (item.error) {
                     contentHtml = `<div class="mt-4 text-red-600 font-mono">${item.error}</div>`;
                } else {
                     contentHtml = `<div class="mt-4 text-gray-600">${statusText}</div>`;
                }


                fileContainer.innerHTML = `
                    <div class="p-3 rounded-t-lg ${headerColor}">
                        <h3 class="font-bold text-lg">${statusIcon}${item.file}</h3>
                    </div>
                    ${contentHtml}
                `;
                resultsDiv.appendChild(fileContainer);
            });
        }

        function displayUnifiedDiffs(diffs) {
            const resultsDiv = document.getElementById('results');
            // Check if all diffs are empty or only error/empty
            const allEmpty = diffs.length === 0 || diffs.every(item => !item.diff || item.diff.trim() === '');
            if (allEmpty) {
                resultsDiv.innerHTML = '<div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-md"><p class="font-bold">No differences found!</p><p>The files or directories are identical.</p></div>';
                return;
            }

            diffs.forEach(item => {
                const fileContainer = document.createElement('div');
                fileContainer.className = 'bg-white p-4 rounded-lg shadow-md';

                if (item.diff && item.diff.trim() !== '') {
                    const diffHtml = Diff2Html.html(item.diff, { drawFileList: false, matching: 'lines', outputFormat: 'side-by-side' });
                    fileContainer.innerHTML = `<div class="overflow-x-auto">${diffHtml}</div>`;
                } else if (item.diff && item.diff.trim() === '') {
                    fileContainer.innerHTML = `<div class='text-green-700'>No differences found in <b>${item.file}</b>.</div>`;
                } else if (item.error) {
                    fileContainer.innerHTML = `<div class="mt-4 text-red-600 font-mono">${item.error}</div>`;
                }

                resultsDiv.appendChild(fileContainer);
            });
        }
    </script>
</body>
</html>
