<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Chatbot Generator</title>
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <style>
/* Reset and base styles */
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body {
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
    line-height: 1.6;
    color: #333;
    background-color: #f5f7fa;
    padding-bottom: 5rem;/* Adjust based on your header height */
}

/* Header styles */
h1 {
    font-size: 2.5rem;
    color: #1a365d;
    margin-bottom: 1rem;
    font-weight: 700;
}

h2 {
    font-size: 1.8rem;
    color: #2d4a7e;
    margin: 2rem 0 1rem;
    font-weight: 600;
}

h3 {
    font-size: 1.4rem;
    color: #2d4a7e;
    margin-bottom: 1rem;
    font-weight: 500;
}

p {
    color: #4a5568;
    margin-bottom: 2rem;
}

/* Container styles */
.container {
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.1);
    padding: 2rem;
    margin-bottom: 2rem;
    border: 1px solid rgba(226, 232, 240, 0.8);
    transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.container:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 8px rgba(0, 0, 0, 0.05), 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* Form elements */
label {
    display: block;
    font-weight: 600;
    color: #2d4a7e;
    margin-bottom: 0.5rem;
    font-size: 0.95rem;
}

input,
select,
textarea {
    width: 100%;
    padding: 0.75rem 1rem;
    border: 2px solid #e2e8f0;
    border-radius: 8px;
    font-size: 1rem;
    transition: border-color 0.2s ease, box-shadow 0.2s ease;
    margin-bottom: 1rem;
    background-color: #fff;
}

input:focus,
select:focus,
textarea:focus {
    outline: none;
    border-color: #4299e1;
    box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.15);
}

/* Button styles */
button {
    padding: 0.75rem 1.5rem;
    border-radius: 8px;
    font-weight: 600;
    font-size: 0.95rem;
    cursor: pointer;
    transition: all 0.2s ease;
    border: none;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
}

button:hover {
    transform: translateY(-1px);
}

button:active {
    transform: translateY(0);
}

#addStep {
    background-color: #3182ce;
    color: white;
    margin: 1rem 0 2rem;
}

#addStep:hover {
    background-color: #2c5282;
}

.add-option {
    background-color: #48bb78;
    color: white;
    margin-right: 1rem;
}

.add-option:hover {
    background-color: #38a169;
}

.remove-step {
    background-color: #f56565;
    color: white;
}

.remove-step:hover {
    background-color: #c53030;
}

#saveButton {
    background-color: #4299e1;
    color: white;
    margin-right: 1rem;
}

#saveButton:hover {
    background-color: #3182ce;
}

#importButton {
    background-color: #9f7aea;
    color: white;
    margin-right: 1rem;
}

#importButton:hover {
    background-color: #805ad5;
}

#copyJsonButton {
    background-color: #667eea;
    color: white;
}

#copyJsonButton:hover {
    background-color: #5a67d8;
}

/* Options container */
.options-container {
    background-color: #f7fafc;
    border-radius: 8px;
    padding: 1.5rem;
    margin: 1rem 0;
    border: 1px solid #e2e8f0;
}

.option-row {
    display: grid;
    grid-template-columns: 2fr 1fr 1.5fr 0.5fr;
    gap: 1rem;
    align-items: center;
    margin-bottom: 1rem;
    background: white;
    padding: 1rem;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.option-row:last-child {
    margin-bottom: 0;
}

.remove-option {
    background-color: #fc8181;
    color: white;
    padding: 0.5rem 1rem;
}

.remove-option:hover {
    background-color: #f56565;
}

/* JSON output */
.json-output {
    background-color: #2d3748;
    color: #e2e8f0;
    padding: 2rem;
    border-radius: 12px;
    font-family: 'Monaco', 'Consolas', monospace;
    white-space: pre-wrap;
    font-size: 0.95rem;
    line-height: 1.5;
    overflow-x: auto;
    margin-top: 1rem;
    border: 1px solid #4a5568;
}

/* Quill editor customization */
.ql-container {
    border-radius: 0 0 8px 8px;
    min-height: 120px;
    background: white;
    margin-bottom: 1.5rem;
}

.ql-toolbar {
    border-radius: 8px 8px 0 0;
    border-color: #e2e8f0 !important;
    background: #f7fafc;
}

.ql-editor {
    font-size: 1rem;
    color: #2d3748;
}

/* Loading state for buttons */
button:disabled {
    opacity: 0.7;
    cursor: not-allowed;
}

/* Animations */
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.container {
    animation: fadeIn 0.3s ease-out;
}

/* Custom scrollbar */
::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

::-webkit-scrollbar-track {
    background: #f7fafc;
}

::-webkit-scrollbar-thumb {
    background: #cbd5e0;
    border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
    background: #a0aec0;
}

/* Fixed Header Styles */
.header-container {
    position: fixed;
    bottom: 0;
    left: 0; /* Adjust when sidebar is present */
    width: 100%;
    background-color: #f5f7fa;
    z-index: 10;
    
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    padding-left: 18rem;
}

/* Sidebar Styles */
.sidebar {
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 250px;
    background-color: #e2e8f0;
    padding: 4rem 1rem 2rem; /* Adjust top padding to be below header */
    overflow-y: auto;
    z-index: 5; /* Below the header */
    transition: left 0.3s ease; /* Smooth transition for mobile */
    z-index: 20;
}

.sidebar-title {
    font-weight: 600;
    margin-bottom: 1rem;
    color: #2d4a7e;
}

.sidebar-step {
    padding: 0.5rem 1rem;
    margin-bottom: 0.5rem;
    background-color: #f7fafc;
    border-radius: 8px;
    border: 1px solid #cbd5e0;
    cursor: pointer;
    transition: background-color 0.2s ease;
}

.sidebar-step:hover {
    background-color: #edf2f7;
}

/* Main Content Adjustments */
.main-content {
    margin-left: 250px; /* Same as sidebar width */
    padding: 4rem 2rem 2rem; /* Adjust top padding to be below header */
    transition: margin-left 0.3s ease; /* Smooth transition for mobile */
}

/* Hamburger Menu Button */
.hamburger-menu {
    display: none;
    position: fixed;
    top: 1rem;
    left: 1rem;
    z-index: 20; /* Above the header */
    background-color: #4299e1;
    color: white;
    border: none;
    padding: 0.5rem 0.75rem;
    border-radius: 5px;
    cursor: pointer;
}

.hamburger-menu:hover {
    background-color: #3182ce;
}

/* Media Query for Mobile Devices */
@media (max-width: 768px) {
    /* General Mobile Styles */
    body {
        padding: 4rem 1rem 1rem 1rem;
        padding-bottom: 5rem; /* Adjust body padding for smaller screens */
    }

    .option-row {
        grid-template-columns: 1fr;
        gap: 0.5rem;
    }

    .container {
        padding: 1.5rem;
    }

    h1 {
        font-size: 2rem;
    }

    button {
        width: 100%;
        margin-bottom: 0.5rem;
    }
    
    /* Header on Mobile */
    .header-container {
        left: 0; /* Reset left position */
        width: 100%; /* Take up full width */
    }

    /* Sidebar on Mobile */
    .sidebar {
        left: -250px; /* Off-screen by default */
        z-index: 20;
    }

    .sidebar.show {
        left: 0; /* Slide in when toggled */
    }

    /* Main Content on Mobile */
    .main-content {
        margin-left: 0; /* No margin when sidebar is hidden */
        padding: 4rem 1rem 2rem; /* Adjust padding */
    }

    /* Hamburger Menu */
    .hamburger-menu {
        display: block;
        width: 50px;
        z-index: 21;
    }
    .header-container {
        padding-left: 5rem;
    }
    #saveButton , #addStep
    {
        width: 130px;
        padding: 1rem 0.8rem;
    }
}
    </style>
</head>

<body>
    <button class="hamburger-menu">☰</button>

    <div class="sidebar">
        <h3 class="sidebar-title">Steps</h3>
        <div id="sidebarSteps"></div>
    </div>

    <div class="header-container">
            <button id="addStep">Add New Step</button>
        <button id="saveButton">Save Work</button>
    </div>

    <div class="main-content">
        <h1>Dynamic Chatbot Generator</h1>
        <p>Fill in the details below to generate your chatbot structure. Each step links dynamically.</p>
    
        <div id="stepsContainer"></div>

        <input type="file" id="importInput" style="display: none;" accept=".json">
        <button id="importButton">Import Work</button>
        <h2>Generated JSON:</h2>
        <button id="copyJsonButton">Copy JSON to Clipboard</button>
        <div id="jsonOutput" class="json-output"></div>
    </div>

    <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
    <script>
        // Use a different key for local storage to prevent conflicts with other scripts
        const STORAGE_KEY = 'chatbotFlowData2';

        let chatbotFlow = {};
        let stepCount = 0;

        // Function to get bot name from URL query string - this is used for saving and loading
        function getBotNameFromQueryString() {
            const queryParams = new URLSearchParams(window.location.search);
            return queryParams.get('bot');
        }

        // Function to save data to server
        function saveData() {
            const botName = getBotNameFromQueryString();
            if (!botName) {
                alert("Bot name is missing in the URL. Please use ?bot=name.");
                return;
            }

            const jsonData = { botdata: chatbotFlow }; // Wrap the chatbotFlow data under 'botdata'

            fetch('save_data2.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ botName: botName, data: jsonData })
            })
                .then(response => response.text())
                .then(data => {
                    alert(data); // Show success/error message from server
                })
                .catch(error => {
                    console.error('Error saving data:', error);
                    alert('Error saving data. See console for details.');
                });
        }

        // Function to load data from server on page load
        function loadExistingData() {
            const botName = getBotNameFromQueryString();
            if (botName) {
                fetch(`load_data.php?bot=${botName}`)
                    .then(response => {
                        if (!response.ok) {
                            if (response.status === 404) {
                                console.log(`No data found for bot: ${botName}`);
                                // Create initial step if no data is found
                                if (Object.keys(chatbotFlow).length === 0) {
                                    createStep();
                                }
                                return null;
                            }
                            throw new Error(`HTTP error! Status: ${response.status}`);
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data && data.botdata) {
                            console.log('Loaded data:', data);
                            importData(data.botdata);
                        } else {
                            // Create initial step if no data is found
                            if (Object.keys(chatbotFlow).length === 0) {
                                createStep();
                            }
                        }
                    })
                    .catch(error => {
                        console.error('Error loading data:', error);
                    });
            } else {
                // Create initial step if no bot name is provided in the URL
                if (Object.keys(chatbotFlow).length === 0) {
                    createStep();
                }
            }
        }

        function createStep() {
            stepCount++;
            const stepId = `step${stepCount}`;
            const stepContainer = document.createElement('div');
            stepContainer.classList.add('container');
            stepContainer.setAttribute('data-step', stepId);

            stepContainer.innerHTML = `<h3>Step ${stepCount}</h3>
                <label for="${stepId}-message">Message:</label>
                <div id="${stepId}-message-container"></div>
                <div class="options-container"></div>
                <button class="add-option" data-step="${stepId}">Add Option</button>
                <button class="remove-step" data-step="${stepId}">Remove Step</button>`;

            document.getElementById('stepsContainer').appendChild(stepContainer);

            const quill = new Quill(`#${stepId}-message-container`, {
                theme: 'snow',
                modules: {
                    toolbar: [
                        ['bold', 'italic', 'underline'],
                        ['link'],
                        [{ list: 'ordered' }, { list: 'bullet' }],
                        [{ align: [] }],
                        [{ indent: '-1' }, { indent: '+1' }],
                        [{ 'header': '1' }, { 'header': '2' }],
                        ['blockquote'],
                        ['image', 'video']
                    ]
                }
            });

            quill.on('text-change', () => updateMessage(stepId, quill));
            stepContainer.querySelector('.add-option').addEventListener('click', () => addOption(stepId));
            stepContainer.querySelector('.remove-step').addEventListener('click', () => {
                if (confirm('Are you sure you want to remove this step?')) {
                    removeStep(stepId);
                }
            });

            chatbotFlow[stepId] = { message: "", options: [] };
            updateJSONOutput();
            refreshNextStepDropdowns();
            addStepToSidebar(stepId); // Add step to sidebar
        }

        function updateMessage(stepId, quill) {
            const message = quill.root.innerHTML.trim();
            const step = chatbotFlow[stepId];
            if (step) {
                step.message = message;
            }
            updateJSONOutput();
        }

        function addOption(stepId) {
            const stepContainer = document.querySelector(`[data-step="${stepId}"]`);
            const optionsContainer = stepContainer.querySelector('.options-container');
            const optionRow = document.createElement('div');
            optionRow.classList.add('option-row');
            optionRow.innerHTML = `<input type="text" class="option-text" placeholder="Option text">
                <select class="option-type"><option value="step">Step</option><option value="link">Link</option><option value="button">Button</option></select>
                <select class="option-next"><option value="">-- Select Next Step --</option></select>
                <input type="text" class="option-url" placeholder="URL" style="display: none;">
                <button class="remove-option">Remove</button>`;

            optionsContainer.appendChild(optionRow);

            const typeSelect = optionRow.querySelector('.option-type');
            typeSelect.addEventListener('change', () => {
                const selectedType = typeSelect.value;
                const nextSelect = optionRow.querySelector('.option-next');
                const urlInput = optionRow.querySelector('.option-url');
                if (selectedType === 'step') {
                    nextSelect.style.display = 'inline-block';
                    urlInput.style.display = 'none';
                } else if (selectedType === 'link' || selectedType === 'button') {
                    nextSelect.style.display = 'none';
                    urlInput.style.display = 'inline-block';
                }
                updateOptions(stepId);
            });
            refreshNextStepDropdowns();

            typeSelect.addEventListener('change', () => updateOptions(stepId));
            optionRow.querySelector('.option-next').addEventListener('change', () => updateOptions(stepId));
            optionRow.querySelector('.option-url').addEventListener('input', () => updateOptions(stepId));
            optionRow.querySelector('.option-text').addEventListener('input', () => updateOptions(stepId));
            optionRow.querySelector('.remove-option').addEventListener('click', () => {
                optionRow.remove();
                updateOptions(stepId);
            });

            updateOptions(stepId);
        }

        function updateOptions(stepId) {
            const stepContainer = document.querySelector(`[data-step="${stepId}"]`);
            const options = stepContainer.querySelectorAll('.option-row');
            const step = chatbotFlow[stepId];

            if (step) {
                step.options = [];
                options.forEach(optionRow => {
                    const optionText = optionRow.querySelector('.option-text').value.trim();
                    const selectedType = optionRow.querySelector('.option-type').value;
                    let optionObj = { text: optionText };

                    if (selectedType === 'step') {
                        const nextStep = optionRow.querySelector('.option-next').value.trim();
                        if (nextStep) {
                            optionObj.next = nextStep;
                        }
                    } else if (selectedType === 'link' || selectedType === 'button') {
                        const url = optionRow.querySelector('.option-url').value.trim();
                        if (url) {
                            optionObj[selectedType] = url;
                        }
                    }
                    if (Object.keys(optionObj).length > 1) {
                        step.options.push(optionObj);
                    }
                });
            }

            updateJSONOutput();
        }

        function removeStep(stepId) {
            delete chatbotFlow[stepId];
            const stepContainer = document.querySelector(`[data-step="${stepId}"]`);
            stepContainer.remove();
            refreshNextStepDropdowns();
            updateJSONOutput();
            removeStepFromSidebar(stepId); // Remove step from sidebar
        }

        function refreshNextStepDropdowns() {
            const allStepSelectors = document.querySelectorAll('.option-next');
            const allStepIds = Object.keys(chatbotFlow);

            allStepSelectors.forEach(selector => {
                const currentValue = selector.value;
                selector.innerHTML = `<option value="">-- Select Next Step --</option>${allStepIds.map(stepId => `<option value="${stepId}" ${currentValue === stepId ? 'selected' : ''}>${stepId}</option>`).join('')}`;

            });
        }

        function updateJSONOutput() {
            document.getElementById('jsonOutput').textContent = JSON.stringify(chatbotFlow, null, 2);
        }

        function importData(importedData) {
            document.getElementById('stepsContainer').innerHTML = '';
            chatbotFlow = {};
            stepCount = 0;
            Object.entries(importedData).forEach(([stepId, stepData]) => {
                createStep();
            });
            stepCount = 0;

            Object.entries(importedData).forEach(([stepId, stepData]) => {
                stepCount++;
                const currentStepId = `step${stepCount}`;
                const editorContainer = document.querySelector(`#${currentStepId}-message-container .ql-editor`);

                if (editorContainer) {
                    editorContainer.innerHTML = stepData.message;
                }

                chatbotFlow[currentStepId] = { message: stepData.message, options: [] };
                const stepContainer = document.querySelector(`[data-step="${currentStepId}"]`);

                if (stepContainer) {
                    const optionsContainer = stepContainer.querySelector('.options-container');
                    optionsContainer.innerHTML = '';

                    stepData.options.forEach(optionData => {
                        addOptionWithData(currentStepId, optionData);
                    });
                }
            });

            updateJSONOutput();
            refreshNextStepDropdowns();

            // Clear and repopulate the sidebar
            document.getElementById('sidebarSteps').innerHTML = '';
            Object.keys(importedData).forEach(stepId => {
                addStepToSidebar(stepId);
            });
        }

        function addOptionWithData(stepId, optionData) {
            addOption(stepId);
            const stepContainer = document.querySelector(`[data-step="${stepId}"]`);
            const lastOptionRow = stepContainer.querySelector('.options-container .option-row:last-child');

            if (lastOptionRow) {
                const typeSelect = lastOptionRow.querySelector('.option-type');
                const nextSelect = lastOptionRow.querySelector('.option-next');
                const urlInput = lastOptionRow.querySelector('.option-url');
                const textInput = lastOptionRow.querySelector('.option-text');

                textInput.value = optionData.text;
                if (optionData.next) {
                    typeSelect.value = 'step';
                    nextSelect.value = optionData.next;
                    nextSelect.style.display = 'inline-block';
                    urlInput.style.display = 'none';

                } else if (optionData.link) {
                    typeSelect.value = 'link';
                    urlInput.value = optionData.link;
                    nextSelect.style.display = 'none';
                    urlInput.style.display = 'inline-block';

                } else if (optionData.button) {
                    typeSelect.value = 'button';
                    urlInput.value = optionData.button;
                    nextSelect.style.display = 'none';
                    urlInput.style.display = 'inline-block';

                }
                updateOptions(stepId);
            }
        }

        // --- Sidebar Functions ---

        function addStepToSidebar(stepId) {
            const sidebarSteps = document.getElementById('sidebarSteps');
            const stepButton = document.createElement('div'); // Use a div instead of a button
            stepButton.classList.add('sidebar-step');
            stepButton.textContent = `Step ${stepId.replace('step', '')}`;
            stepButton.setAttribute('data-step-id', stepId);

            stepButton.addEventListener('click', () => {
                const stepElement = document.querySelector(`[data-step="${stepId}"]`);
                if (stepElement) {
                    stepElement.scrollIntoView({ behavior: 'smooth' });
                }
            });

            sidebarSteps.appendChild(stepButton);
        }

        function removeStepFromSidebar(stepId) {
            const stepButton = document.querySelector(`.sidebar-step[data-step-id="${stepId}"]`);
            if (stepButton) {
                stepButton.remove();
            }
        }

        // --- Hamburger Menu Toggle ---

        document.querySelector('.hamburger-menu').addEventListener('click', () => {
            const sidebar = document.querySelector('.sidebar');
            sidebar.classList.toggle('show');
        });

        document.addEventListener('DOMContentLoaded', () => {
            loadExistingData(); // Load data from the server based on the bot name in the URL
            document.getElementById('saveButton').addEventListener('click', saveData); // Attach save functionality to the save button

            document.getElementById('addStep').addEventListener('click', createStep);

            document.getElementById('importButton').addEventListener('click', () => {
                document.getElementById('importInput').click();
            });

            document.getElementById('importInput').addEventListener('change', (event) => {
                const file = event.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function (e) {
                        try {
                            const importedData = JSON.parse(e.target.result);
                            importData(importedData);
                            alert('Import successful!');
                        } catch (error) {
                            console.error('Error importing file:', error);
                            alert('Error importing file. Please make sure it\'s a valid JSON file.');
                        }
                    };
                    reader.readAsText(file);
                }
            });

            document.getElementById('copyJsonButton').addEventListener('click', () => {
                const jsonOutput = document.getElementById('jsonOutput').textContent;
                navigator.clipboard.writeText(jsonOutput)
                    .then(() => { alert('JSON copied to clipboard!'); })
                    .catch(err => { console.error('Error copying JSON to clipboard: ', err); });
            });
        });
    </script>
</body>

</html>