<?php
/**
 * ============================================
 * FLOWBOT DCI v3.0 - ANALYSIS PREVIEW
 * ============================================
 * Stage 2: Pre-processing analysis with options
 */
declare(strict_types=1);

// Variables from controller (with safe defaults)
$baseUrl = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
$pageTitle = 'Analysis Preview';
$currentPage = 'new';
$csrfToken = $csrfToken ?? '';
$processId = $processId ?? '';

// Analysis data with safe defaults
$analysis = $analysis ?? [];
$totalUrls = $analysis['total_urls'] ?? 0;
$domainsCount = $analysis['domains_count'] ?? 0;
$domains = $analysis['domains'] ?? [];
$estimates = $analysis['estimates'] ?? [];
$timeMin = $estimates['time_min'] ?? 0;
$timeMax = $estimates['time_max'] ?? 0;
$successRate = $estimates['success_rate'] ?? 85;
$socialMediaCount = $analysis['social_media_count'] ?? 0;
$warnings = $analysis['warnings'] ?? [];
$invalidCount = $analysis['invalid_count'] ?? 0;
$invalidUrls = $analysis['invalid_urls'] ?? [];

// Format time estimate
function formatTimeEstimate(int|float $minutes): string {
    if ($minutes < 1) {
        return 'Less than 1 min';
    } elseif ($minutes < 60) {
        return round($minutes) . ' min';
    } else {
        $hours = floor($minutes / 60);
        $mins = round($minutes % 60);
        return $hours . 'h ' . $mins . 'm';
    }
}

$timeEstimate = formatTimeEstimate($timeMin);
if ($timeMax > $timeMin) {
    $timeEstimate .= ' - ' . formatTimeEstimate($timeMax);
}
?>
<!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() ?>">
</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="<?= $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">
                <span class="badge badge-info">Step 2 of 3</span>
            </div>
        </div>
    </nav>

    <!-- Main Content -->
    <main class="main-content">
        <!-- Step Indicator -->
        <div class="step-indicator">
            <div class="step completed">
                <div class="step-circle">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3">
                        <polyline points="20 6 9 17 4 12"/>
                    </svg>
                </div>
                <span class="step-label">URL Input</span>
            </div>
            <div class="step-line completed"></div>
            <div class="step active">
                <div class="step-circle">2</div>
                <span class="step-label">Analysis</span>
            </div>
            <div class="step-line"></div>
            <div class="step">
                <div class="step-circle">3</div>
                <span class="step-label">Processing</span>
            </div>
        </div>

        <!-- Page Header -->
        <div class="page-header">
            <div>
                <h1 class="page-title">Analysis Preview</h1>
                <p class="page-subtitle">Review your URLs and configure processing options</p>
            </div>
            <a href="<?= $baseUrl ?>/new<?= $processId ? '?process_id=' . htmlspecialchars($processId) : '' ?>" class="btn btn-secondary">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                    <line x1="19" y1="12" x2="5" y2="12"/>
                    <polyline points="12 19 5 12 12 5"/>
                </svg>
                Edit URLs
            </a>
        </div>

        <!-- Summary Stats -->
        <div class="stats-grid cols-4">
            <div class="stat-card">
                <div class="stat-icon">
                    <svg width="24" height="24" 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>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?= number_format($totalUrls) ?></span>
                    <span class="stat-label">Total URLs</span>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <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>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?= number_format($domainsCount) ?></span>
                    <span class="stat-label">Unique Domains</span>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="12" r="10"/>
                        <polyline points="12 6 12 12 16 14"/>
                    </svg>
                </div>
                <div class="stat-content">
                    <span class="stat-value">~<?= $timeEstimate ?></span>
                    <span class="stat-label">Est. Time</span>
                </div>
            </div>

            <div class="stat-card <?= $successRate >= 80 ? 'stat-card-success' : 'stat-card-warning' ?>">
                <div class="stat-icon">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
                        <polyline points="22 4 12 14.01 9 11.01"/>
                    </svg>
                </div>
                <div class="stat-content">
                    <span class="stat-value">~<?= number_format($successRate) ?>%</span>
                    <span class="stat-label">Est. Success</span>
                </div>
            </div>
        </div>

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

            <div class="form-grid">
                <!-- Left Column: Domain Breakdown -->
                <div class="form-main">
                    <div class="section">
                        <div class="section-header">
                            <h2 class="section-title">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <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>
                                Domain Breakdown
                            </h2>
                            <span class="badge badge-secondary"><?= count($domains) ?> domains</span>
                        </div>
                        <div class="section-body">
                            <?php if (empty($domains)): ?>
                            <div class="empty-state">
                                <p class="empty-state-title">No Domains Found</p>
                                <p class="empty-state-text">Add URLs to see domain breakdown.</p>
                            </div>
                            <?php else: ?>
                            <div class="domain-list">
                                <?php
                                $maxCount = max(array_column($domains, 'count') ?: [1]);
                                foreach ($domains as $domain):
                                    $barWidth = ($domain['count'] / $maxCount) * 100;
                                    $isSocial = $domain['is_social_media'] ?? false;
                                    $domainName = $domain['domain'] ?? 'unknown';
                                    $initials = strtoupper(substr($domainName, 0, 2));
                                    $domainSuccessRate = $domain['success_rate'] ?? null;
                                ?>
                                <div class="domain-item">
                                    <div class="domain-icon <?= $isSocial ? 'social' : '' ?>">
                                        <?= $initials ?>
                                    </div>
                                    <div class="domain-info">
                                        <div class="domain-name"><?= htmlspecialchars($domainName) ?></div>
                                        <div class="domain-meta">
                                            <?php if ($isSocial): ?>
                                            <span class="tag tag-info">Social</span>
                                            <?php endif; ?>
                                            <?php if ($domainSuccessRate !== null): ?>
                                            <span><?= number_format($domainSuccessRate, 0) ?>% success</span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <div class="domain-count"><?= number_format($domain['count'] ?? 0) ?></div>
                                    <div class="domain-bar">
                                        <div class="domain-bar-fill" style="width: <?= $barWidth ?>%"></div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <?php endif; ?>

                            <!-- Warnings Section -->
                            <?php if (!empty($warnings)): ?>
                            <div class="warnings-section mt-lg">
                                <h4 class="subsection-title">
                                    <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>
                                    Warnings
                                </h4>
                                <div class="warnings-list">
                                    <?php foreach ($warnings as $warning): ?>
                                    <div class="warning-item <?= ($warning['type'] ?? '') === 'blocked' ? 'error' : '' ?>">
                                        <div class="warning-icon">
                                            <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>
                                        </div>
                                        <div class="warning-content">
                                            <div class="warning-title"><?= ucfirst(str_replace('_', ' ', $warning['type'] ?? 'Warning')) ?></div>
                                            <div class="warning-desc"><?= htmlspecialchars($warning['message'] ?? '') ?></div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php endif; ?>

                            <!-- Invalid URLs Section -->
                            <?php if ($invalidCount > 0): ?>
                            <div class="invalid-urls-section mt-lg">
                                <button type="button" class="invalid-toggle" id="invalidToggle">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="12" height="12">
                                        <polyline points="9 18 15 12 9 6"/>
                                    </svg>
                                    <?= $invalidCount ?> invalid URLs (excluded)
                                </button>
                                <div class="invalid-list" id="invalidList">
                                    <?php foreach (array_slice($invalidUrls, 0, 10) as $invalid): ?>
                                    <div class="invalid-url-item">
                                        <span class="invalid-url"><?= htmlspecialchars($invalid['url'] ?? '') ?></span>
                                        <span class="invalid-reason"><?= htmlspecialchars($invalid['reason'] ?? 'Invalid') ?></span>
                                    </div>
                                    <?php endforeach; ?>
                                    <?php if ($invalidCount > 10): ?>
                                    <div class="invalid-url-item">
                                        <span class="invalid-url text-muted">...and <?= $invalidCount - 10 ?> more</span>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Right Column: Options -->
                <div class="form-sidebar">
                    <!-- Processing Mode -->
                    <div class="section">
                        <div class="section-header">
                            <h2 class="section-title">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <circle cx="12" cy="12" r="3"/>
                                    <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>
                                </svg>
                                Processing Mode
                            </h2>
                        </div>
                        <div class="section-body">
                            <div class="mode-options">
                                <label class="mode-option" data-mode="fast">
                                    <input type="radio" name="mode" value="fast">
                                    <div class="mode-option-header">
                                        <span class="mode-option-radio"></span>
                                        <span class="mode-option-title">Fast Mode</span>
                                    </div>
                                    <div class="mode-option-desc">Single pass, minimal retries</div>
                                    <div class="mode-option-stats">
                                        <span>2x faster</span>
                                        <span>~70% success</span>
                                    </div>
                                </label>

                                <label class="mode-option selected" data-mode="standard">
                                    <input type="radio" name="mode" value="standard" checked>
                                    <div class="mode-option-header">
                                        <span class="mode-option-radio"></span>
                                        <span class="mode-option-title">Standard Mode</span>
                                        <span class="badge badge-primary">Recommended</span>
                                    </div>
                                    <div class="mode-option-desc">4-phase processing with retry</div>
                                    <div class="mode-option-stats">
                                        <span>Balanced</span>
                                        <span>~85% success</span>
                                    </div>
                                </label>

                                <label class="mode-option" data-mode="thorough">
                                    <input type="radio" name="mode" value="thorough">
                                    <div class="mode-option-header">
                                        <span class="mode-option-radio"></span>
                                        <span class="mode-option-title">Thorough Mode</span>
                                    </div>
                                    <div class="mode-option-desc">Extended retries, longer delays</div>
                                    <div class="mode-option-stats">
                                        <span>2x slower</span>
                                        <span>~95% success</span>
                                    </div>
                                </label>
                            </div>
                        </div>
                    </div>

                    <!-- Options -->
                    <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="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                                    <polyline points="7 10 12 15 17 10"/>
                                    <line x1="12" y1="15" x2="12" y2="3"/>
                                </svg>
                                Options
                            </h2>
                        </div>
                        <div class="section-body">
                            <div class="checkbox-group">
                                <label class="checkbox-item">
                                    <input type="checkbox" name="auto_export" value="1" checked>
                                    <span>Auto-export results when complete</span>
                                </label>
                                <label class="checkbox-item">
                                    <input type="checkbox" id="notifications" name="notifications" value="1" checked>
                                    <span>Send browser notification when done</span>
                                </label>
                                <label class="checkbox-item">
                                    <input type="checkbox" name="include_failed" value="1">
                                    <span>Include failed URLs in export</span>
                                </label>
                            </div>
                        </div>
                    </div>

                    <!-- Success Rate Indicator -->
                    <div class="section">
                        <div class="section-body">
                            <div class="success-indicator">
                                <div class="success-circle" style="--percent: <?= $successRate ?>">
                                    <span class="success-value"><?= $successRate ?>%</span>
                                </div>
                                <div class="success-info">
                                    <div class="success-label">Estimated Success Rate</div>
                                    <div class="success-desc">Based on domain history</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Action Buttons -->
                    <div class="action-buttons">
                        <a href="<?= $baseUrl ?>/new<?= $processId ? '?process_id=' . htmlspecialchars($processId) : '' ?>" class="btn btn-secondary">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                                <line x1="19" y1="12" x2="5" y2="12"/>
                                <polyline points="12 19 5 12 12 5"/>
                            </svg>
                            Back
                        </a>
                        <button type="submit" class="btn btn-primary btn-lg">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                                <polygon points="5 3 19 12 5 21 5 3"/>
                            </svg>
                            Start Processing
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </main>

    <!-- Toast Container -->
    <div id="toastContainer" class="toast-container"></div>

    <script src="<?= $baseUrl ?>/assets/js/app.js?v=<?= time() ?>"></script>
    <script>
    (function() {
        'use strict';

        // Mode selection
        const modeOptions = document.querySelectorAll('.mode-option');
        modeOptions.forEach(option => {
            option.addEventListener('click', () => {
                modeOptions.forEach(o => o.classList.remove('selected'));
                option.classList.add('selected');
                option.querySelector('input').checked = true;
            });
        });

        // Invalid URLs toggle
        const invalidToggle = document.getElementById('invalidToggle');
        const invalidList = document.getElementById('invalidList');
        if (invalidToggle && invalidList) {
            invalidToggle.addEventListener('click', () => {
                invalidToggle.classList.toggle('open');
                invalidList.classList.toggle('open');
            });
        }

        // Request notification permission
        if ('Notification' in window && Notification.permission === 'default') {
            const notifCheckbox = document.getElementById('notifications');
            if (notifCheckbox) {
                notifCheckbox.addEventListener('change', function() {
                    if (this.checked) {
                        Notification.requestPermission();
                    }
                });
            }
        }

        // Form submission
        const form = document.getElementById('analysisForm');
        if (form) {
            form.addEventListener('submit', function(e) {
                const submitBtn = form.querySelector('button[type="submit"]');
                if (submitBtn) {
                    submitBtn.disabled = true;
                    submitBtn.innerHTML = '<span class="loading-spinner"></span> Starting...';
                }
            });
        }
    })();
    </script>
</body>
</html>
