<?php
/**
 * ============================================
 * FLOWBOT DCI v3.0 - NEW PROCESS (STAGE 1)
 * ============================================
 * Clean URL input form
 */
declare(strict_types=1);

$baseUrl = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
$pageTitle = 'New Process';
$currentPage = 'new';
$csrfToken = $csrfToken ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($pageTitle) ?> - Flowb0t DCI v3.0</title>
    <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'><rect width='32' height='32' rx='8' fill='%233B82F6'/><path d='M8 10h16M8 16h12M8 22h8' stroke='white' stroke-width='2.5' stroke-linecap='round'/></svg>">
    <link rel="stylesheet" href="<?= $baseUrl ?>/assets/css/v3-styles.css?v=<?= time() ?>">
    <style>
        .form-grid {
            display: grid;
            grid-template-columns: 1fr 320px;
            gap: var(--spacing-xl);
            align-items: start;
        }
        @media (max-width: 900px) {
            .form-grid { grid-template-columns: 1fr; }
        }
        .url-textarea {
            width: 100%;
            min-height: 400px;
            padding: var(--spacing-lg);
            font-family: var(--font-mono);
            font-size: 0.875rem;
            line-height: 1.7;
            background: var(--bg-tertiary);
            border: 2px solid var(--border-color);
            border-radius: var(--radius-lg);
            color: var(--text-primary);
            resize: vertical;
            transition: all var(--transition-fast);
        }
        .url-textarea:focus {
            outline: none;
            border-color: var(--color-primary);
            box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.15);
        }
        .url-textarea::placeholder {
            color: var(--text-muted);
        }
        /* Drag & Drop Styles */
        .textarea-wrapper {
            position: relative;
        }
        .textarea-wrapper.dragging .url-textarea {
            border-color: var(--color-primary);
            border-style: dashed;
            background: rgba(59, 130, 246, 0.05);
        }
        .drop-overlay {
            display: none;
            position: absolute;
            inset: 0;
            background: rgba(59, 130, 246, 0.1);
            border: 2px dashed var(--color-primary);
            border-radius: var(--radius-lg);
            align-items: center;
            justify-content: center;
            z-index: 10;
            pointer-events: none;
        }
        .textarea-wrapper.dragging .drop-overlay {
            display: flex;
        }
        .drop-overlay-content {
            text-align: center;
            padding: var(--spacing-xl);
        }
        .drop-overlay-icon {
            width: 48px;
            height: 48px;
            margin: 0 auto var(--spacing-md);
            color: var(--color-primary);
        }
        .drop-overlay-text {
            font-size: 1rem;
            font-weight: 600;
            color: var(--color-primary);
        }
        .drop-overlay-hint {
            font-size: 0.8125rem;
            color: var(--text-muted);
            margin-top: var(--spacing-xs);
        }
        .clear-btn {
            background: none;
            border: none;
            color: var(--text-muted);
            cursor: pointer;
            padding: var(--spacing-xs) var(--spacing-sm);
            font-size: 0.8125rem;
            border-radius: var(--radius-sm);
            transition: all var(--transition-fast);
        }
        .clear-btn:hover {
            color: var(--color-error);
            background: rgba(239, 68, 68, 0.1);
        }
        .input-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: var(--spacing-md);
            padding-top: var(--spacing-md);
            border-top: 1px solid var(--border-light);
        }
        .url-counter {
            font-size: 0.8125rem;
            color: var(--text-muted);
        }
        .url-counter strong {
            color: var(--text-primary);
            font-weight: 600;
        }
        .validation-card {
            background: var(--bg-card);
            border: 1px solid var(--border-color);
            border-radius: var(--radius-lg);
            padding: var(--spacing-lg);
        }
        .validation-title {
            font-size: 0.9375rem;
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: var(--spacing-md);
            display: flex;
            align-items: center;
            gap: var(--spacing-sm);
        }
        .validation-stats {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: var(--spacing-sm);
        }
        .val-stat {
            display: flex;
            align-items: center;
            gap: var(--spacing-sm);
            padding: var(--spacing-sm) var(--spacing-md);
            background: var(--bg-tertiary);
            border-radius: var(--radius-md);
            font-size: 0.8125rem;
        }
        .val-stat.success { color: var(--color-success); }
        .val-stat.error { color: var(--color-error); }
        .val-stat.warning { color: var(--color-warning); }
        .val-stat.info { color: var(--color-info); }
        .val-stat span { color: var(--text-secondary); }
        .val-stat strong { color: var(--text-primary); }
        .mode-selector {
            margin-top: var(--spacing-lg);
            padding-top: var(--spacing-lg);
            border-top: 1px solid var(--border-light);
        }
        .mode-option {
            display: flex;
            align-items: flex-start;
            gap: var(--spacing-md);
            padding: var(--spacing-md);
            background: var(--bg-tertiary);
            border: 2px solid transparent;
            border-radius: var(--radius-md);
            cursor: pointer;
            margin-bottom: var(--spacing-sm);
            transition: all var(--transition-fast);
        }
        .mode-option:hover {
            border-color: var(--border-color);
        }
        .mode-option.selected {
            border-color: var(--color-primary);
            background: rgba(59, 130, 246, 0.1);
        }
        .mode-option input {
            margin-top: 4px;
        }
        .mode-info h4 {
            font-size: 0.875rem;
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 2px;
        }
        .mode-info p {
            font-size: 0.75rem;
            color: var(--text-muted);
            margin: 0;
        }
        .step-indicator {
            display: flex;
            align-items: center;
            gap: var(--spacing-md);
            margin-bottom: var(--spacing-xl);
        }
        .step {
            display: flex;
            align-items: center;
            gap: var(--spacing-sm);
            padding: var(--spacing-sm) var(--spacing-md);
            border-radius: var(--radius-full);
            font-size: 0.8125rem;
            font-weight: 500;
        }
        .step.active {
            background: var(--color-primary);
            color: white;
        }
        .step.inactive {
            background: var(--bg-tertiary);
            color: var(--text-muted);
        }
        .step-line {
            flex: 1;
            height: 2px;
            background: var(--border-color);
            max-width: 60px;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="main-nav">
        <div class="nav-container">
            <div class="nav-brand">
                <a href="<?= $baseUrl ?>/" class="brand-link">
                    <span class="brand-logo">
                        <svg viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <rect width="32" height="32" rx="8" fill="url(#brand-gradient)"/>
                            <path d="M8 10h16M8 16h12M8 22h8" stroke="white" stroke-width="2.5" stroke-linecap="round"/>
                            <circle cx="24" cy="22" r="4" fill="#10B981"/>
                            <defs>
                                <linearGradient id="brand-gradient" x1="0" y1="0" x2="32" y2="32">
                                    <stop stop-color="#3B82F6"/>
                                    <stop offset="1" stop-color="#8B5CF6"/>
                                </linearGradient>
                            </defs>
                        </svg>
                    </span>
                    <span class="brand-text">Flowb0t DCI</span>
                    <span class="brand-version">v3.0</span>
                </a>
            </div>

            <div class="nav-main">
                <a href="<?= $baseUrl ?>/" class="nav-link">
                    <svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <rect x="3" y="3" width="7" height="7" rx="1"/>
                        <rect x="14" y="3" width="7" height="7" rx="1"/>
                        <rect x="3" y="14" width="7" height="7" rx="1"/>
                        <rect x="14" y="14" width="7" height="7" rx="1"/>
                    </svg>
                    <span>Dashboard</span>
                </a>
                <a href="<?= $baseUrl ?>/new" class="nav-link active">
                    <svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="12" r="9"/>
                        <line x1="12" y1="8" x2="12" y2="16"/>
                        <line x1="8" y1="12" x2="16" y2="12"/>
                    </svg>
                    <span>New Process</span>
                </a>
                <a href="/flowb0t.com/v2/views/crawler-ultimate.php" class="nav-link">
                    <svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="11" cy="11" r="8"/>
                        <line x1="21" y1="21" x2="16.65" y2="16.65"/>
                    </svg>
                    <span>Crawler</span>
                </a>
                <a href="<?= $baseUrl ?>/history" class="nav-link">
                    <svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="12" r="9"/>
                        <polyline points="12,7 12,12 16,14"/>
                    </svg>
                    <span>History</span>
                </a>
            </div>

            <div class="nav-right">
                <a href="<?= $baseUrl ?>/" class="btn btn-ghost btn-sm">Cancel</a>
            </div>
        </div>
    </nav>

    <!-- Main Content -->
    <main class="main-content">
        <!-- Step Indicator -->
        <div class="step-indicator">
            <div class="step active">
                <span>1</span> URL Input
            </div>
            <div class="step-line"></div>
            <div class="step inactive">
                <span>2</span> Analysis
            </div>
            <div class="step-line"></div>
            <div class="step inactive">
                <span>3</span> Processing
            </div>
        </div>

        <!-- Page Header -->
        <div class="page-header">
            <h1 class="page-title">New Process</h1>
            <p class="page-subtitle">Enter or paste the URLs you want to process. One URL per line.</p>
        </div>

        <!-- Form -->
        <form method="POST" action="<?= $baseUrl ?>/new" id="urlForm">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">

            <div class="form-grid">
                <!-- Main Input -->
                <div class="section">
                    <div class="section-header">
                        <h2 class="section-title">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>
                                <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>
                            </svg>
                            URL Input
                        </h2>
                        <label class="btn btn-ghost btn-sm" style="cursor: pointer;">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                                <polyline points="17 8 12 3 7 8"/>
                                <line x1="12" y1="3" x2="12" y2="15"/>
                            </svg>
                            Import File
                            <input type="file" accept=".txt,.csv" style="display: none;" id="fileImport">
                        </label>
                    </div>
                    <div class="section-body">
                        <div class="textarea-wrapper" id="dropZone">
                            <textarea
                                name="urls"
                                id="urlInput"
                                class="url-textarea"
                                placeholder="https://example.com/page1&#10;https://twitter.com/user/status/123&#10;https://instagram.com/p/abc123&#10;...&#10;&#10;Paste your URLs here, one per line.&#10;&#10;Or drag & drop a text file here!"
                                required
                            ></textarea>
                            <div class="drop-overlay">
                                <div class="drop-overlay-content">
                                    <svg class="drop-overlay-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                                        <polyline points="17 8 12 3 7 8"/>
                                        <line x1="12" y1="3" x2="12" y2="15"/>
                                    </svg>
                                    <div class="drop-overlay-text">Drop your file here</div>
                                    <div class="drop-overlay-hint">Supports .txt and .csv files</div>
                                </div>
                            </div>
                        </div>

                        <div class="input-footer">
                            <div class="url-counter">
                                <strong id="urlCount">0</strong> URLs &bull;
                                <strong id="domainCount">0</strong> domains
                                <button type="button" class="clear-btn" id="clearBtn" style="display: none; margin-left: 8px;">
                                    Clear all
                                </button>
                            </div>
                            <button type="submit" class="btn btn-primary btn-lg" id="submitBtn" disabled>
                                Analyze URLs
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="18" height="18">
                                    <line x1="5" y1="12" x2="19" y2="12"/>
                                    <polyline points="12 5 19 12 12 19"/>
                                </svg>
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Sidebar -->
                <div>
                    <!-- Live Validation -->
                    <div class="validation-card">
                        <h3 class="validation-title">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="18" height="18">
                                <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
                                <polyline points="22 4 12 14.01 9 11.01"/>
                            </svg>
                            Live Validation
                        </h3>

                        <div class="validation-stats">
                            <div class="val-stat success">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                                    <polyline points="20 6 9 17 4 12"/>
                                </svg>
                                <span>Valid:</span>
                                <strong id="validCount">0</strong>
                            </div>
                            <div class="val-stat error">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                                    <line x1="18" y1="6" x2="6" y2="18"/>
                                    <line x1="6" y1="6" x2="18" y2="18"/>
                                </svg>
                                <span>Invalid:</span>
                                <strong id="invalidCount">0</strong>
                            </div>
                            <div class="val-stat warning">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                                    <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
                                    <line x1="12" y1="9" x2="12" y2="13"/>
                                    <line x1="12" y1="17" x2="12.01" y2="17"/>
                                </svg>
                                <span>Duplicates:</span>
                                <strong id="dupCount">0</strong>
                            </div>
                            <div class="val-stat info">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                                    <circle cx="12" cy="12" r="10"/>
                                    <line x1="2" y1="12" x2="22" y2="12"/>
                                    <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
                                </svg>
                                <span>Domains:</span>
                                <strong id="domainCountSide">0</strong>
                            </div>
                        </div>

                        <!-- Processing Mode -->
                        <div class="mode-selector">
                            <h4 class="validation-title" style="font-size: 0.8125rem;">Processing Mode</h4>

                            <label class="mode-option selected">
                                <input type="radio" name="mode" value="standard" checked>
                                <div class="mode-info">
                                    <h4>Standard Mode</h4>
                                    <p>4-phase processing with retry. ~85% success rate.</p>
                                </div>
                            </label>

                            <label class="mode-option">
                                <input type="radio" name="mode" value="fast">
                                <div class="mode-info">
                                    <h4>Fast Mode</h4>
                                    <p>Single pass, minimal retries. 2x faster, ~70% success.</p>
                                </div>
                            </label>

                            <label class="mode-option">
                                <input type="radio" name="mode" value="thorough">
                                <div class="mode-info">
                                    <h4>Thorough Mode</h4>
                                    <p>Extended retries, longer delays. ~95% success rate.</p>
                                </div>
                            </label>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </main>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const textarea = document.getElementById('urlInput');
        const submitBtn = document.getElementById('submitBtn');
        const urlCount = document.getElementById('urlCount');
        const domainCount = document.getElementById('domainCount');
        const validCount = document.getElementById('validCount');
        const invalidCount = document.getElementById('invalidCount');
        const dupCount = document.getElementById('dupCount');
        const domainCountSide = document.getElementById('domainCountSide');
        const fileImport = document.getElementById('fileImport');
        const modeOptions = document.querySelectorAll('.mode-option');

        // URL validation regex
        const urlPattern = /^https?:\/\/[^\s/$.?#].[^\s]*$/i;

        function validateUrls() {
            const lines = textarea.value.split('\n').filter(line => line.trim());
            const urls = new Set();
            const domains = new Set();
            let valid = 0;
            let invalid = 0;
            let duplicates = 0;

            lines.forEach(line => {
                const url = line.trim();
                if (!url) return;

                if (urls.has(url)) {
                    duplicates++;
                    return;
                }

                if (urlPattern.test(url)) {
                    valid++;
                    urls.add(url);
                    try {
                        const domain = new URL(url).hostname;
                        domains.add(domain);
                    } catch (e) {}
                } else {
                    invalid++;
                }
            });

            urlCount.textContent = valid;
            domainCount.textContent = domains.size;
            validCount.textContent = valid;
            invalidCount.textContent = invalid;
            dupCount.textContent = duplicates;
            domainCountSide.textContent = domains.size;

            submitBtn.disabled = valid === 0;
        }

        textarea.addEventListener('input', validateUrls);
        textarea.addEventListener('paste', () => setTimeout(validateUrls, 100));

        // File import
        fileImport.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (!file) return;
            handleFile(file);
        });

        // Handle file content
        function handleFile(file) {
            if (!file) return;

            const validTypes = ['text/plain', 'text/csv', 'application/csv'];
            const validExtensions = ['.txt', '.csv'];
            const isValidType = validTypes.includes(file.type) ||
                validExtensions.some(ext => file.name.toLowerCase().endsWith(ext));

            if (!isValidType) {
                alert('Please drop a .txt or .csv file');
                return;
            }

            const reader = new FileReader();
            reader.onload = function(e) {
                textarea.value = e.target.result;
                validateUrls();
            };
            reader.readAsText(file);
        }

        // Drag & Drop functionality
        const dropZone = document.getElementById('dropZone');
        const clearBtn = document.getElementById('clearBtn');
        let dragCounter = 0;

        // Show/hide clear button based on content
        function updateClearButton() {
            const hasContent = textarea.value.trim().length > 0;
            clearBtn.style.display = hasContent ? 'inline' : 'none';
        }

        textarea.addEventListener('input', function() {
            validateUrls();
            updateClearButton();
        });

        clearBtn.addEventListener('click', function() {
            textarea.value = '';
            validateUrls();
            updateClearButton();
            textarea.focus();
        });

        // Drag events
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropZone.addEventListener(eventName, preventDefaults, false);
            document.body.addEventListener(eventName, preventDefaults, false);
        });

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        dropZone.addEventListener('dragenter', function(e) {
            dragCounter++;
            dropZone.classList.add('dragging');
        });

        dropZone.addEventListener('dragleave', function(e) {
            dragCounter--;
            if (dragCounter === 0) {
                dropZone.classList.remove('dragging');
            }
        });

        dropZone.addEventListener('dragover', function(e) {
            dropZone.classList.add('dragging');
        });

        dropZone.addEventListener('drop', function(e) {
            dragCounter = 0;
            dropZone.classList.remove('dragging');

            const files = e.dataTransfer.files;
            if (files.length > 0) {
                handleFile(files[0]);
            }
        });

        // Mode selection
        modeOptions.forEach(option => {
            option.addEventListener('click', function() {
                modeOptions.forEach(o => o.classList.remove('selected'));
                this.classList.add('selected');
                this.querySelector('input').checked = true;
            });
        });

        // Initial update
        updateClearButton();
    });
    </script>
</body>
</html>
