<?php
include '../includes/auth.php';
include '../includes/db.php';

$id = $_GET['id'] ?? null;
$event_id = $_GET['event_id'] ?? null;

if (!$id || !$event_id) {
    die('Invalid request');
}

// Fetch current series data
$stmt = $pdo->prepare("SELECT * FROM bib_series WHERE id = ? AND event_id = ?");
$stmt->execute([$id, $event_id]);
$series = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$series) {
    die('Series not found');
}

// Calculate analytics for the series
$current_range = range($series['start_number'], $series['end_number']);
$missing_numbers = array_filter(array_map('trim', explode(',', $series['missing_numbers'])), 'is_numeric');
$additional_numbers = array_filter(array_map('trim', explode(',', $series['additional_numbers'])), 'is_numeric');

// Available numbers calculation
$available_in_range = array_diff($current_range, $missing_numbers);
$all_available = array_unique(array_merge($available_in_range, $additional_numbers));
$total_available = count($all_available);
$total_in_range = count($current_range);

// Check for assigned BIBs in this series
$assigned_stmt = $pdo->prepare("
    SELECT COUNT(*) as assigned_count,
           GROUP_CONCAT(DISTINCT ep.bib_number ORDER BY ep.bib_number) as assigned_numbers
    FROM event_participants ep 
    WHERE ep.event_id = ? 
    AND ep.bib_number IS NOT NULL 
    AND (ep.bib_number BETWEEN ? AND ? OR ep.bib_number IN (" . 
    (empty($additional_numbers) ? "0" : implode(',', array_map('intval', $additional_numbers))) . "))
    AND ep.bib_number NOT IN (" . 
    (empty($missing_numbers) ? "0" : implode(',', array_map('intval', $missing_numbers))) . ")
");
$assigned_stmt->execute([$event_id, $series['start_number'], $series['end_number']]);
$assignment_data = $assigned_stmt->fetch(PDO::FETCH_ASSOC);
$assigned_count = $assignment_data['assigned_count'];
$assigned_numbers = $assignment_data['assigned_numbers'] ? explode(',', $assignment_data['assigned_numbers']) : [];
$free_count = $total_available - $assigned_count;
$usage_percentage = $total_available > 0 ? round(($assigned_count / $total_available) * 100, 1) : 0;

// Check for conflicts with other series
$conflict_check = $pdo->prepare("SELECT * FROM bib_series WHERE event_id = ? AND id != ?");
$conflict_check->execute([$event_id, $id]);
$potential_conflicts = 0;
$conflicting_series = [];

foreach ($conflict_check as $other_series) {
    $other_range = range($other_series['start_number'], $other_series['end_number']);
    $other_missing = array_filter(array_map('trim', explode(',', $other_series['missing_numbers'])), 'is_numeric');
    $other_additional = array_filter(array_map('trim', explode(',', $other_series['additional_numbers'])), 'is_numeric');
    $other_available = array_unique(array_merge(array_diff($other_range, $other_missing), $other_additional));
    
    $overlap = array_intersect($all_available, $other_available);
    if (count($overlap) > 0) {
        $potential_conflicts += count($overlap);
        $conflicting_series[] = [
            'name' => $other_series['name'],
            'color' => $other_series['color'],
            'conflicts' => $overlap
        ];
    }
}

// Handle update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_series'])) {
    $name = $_POST['name'];
    $color = $_POST['color'];
    $start = (int)$_POST['start_number'];
    $end = (int)$_POST['end_number'];
    $missing = trim($_POST['missing_numbers']);
    $additional = trim($_POST['additional_numbers']);

    // Build new number set
    $new_range = range($start, $end);
    $new_missing = array_filter(array_map('trim', explode(',', $missing)), 'is_numeric');
    $new_additional = array_filter(array_map('trim', explode(',', $additional)), 'is_numeric');
    $all_new = array_unique(array_merge($new_range, $new_additional));
    $all_new = array_diff($all_new, $new_missing);

    // Fetch all other series
    $conflict_series = $pdo->prepare("SELECT * FROM bib_series WHERE event_id = ? AND id != ?");
    $conflict_series->execute([$event_id, $id]);

    $has_conflict = false;
    foreach ($conflict_series as $existing) {
        $existing_range = range($existing['start_number'], $existing['end_number']);
        $existing_missing = array_filter(array_map('trim', explode(',', $existing['missing_numbers'])), 'is_numeric');
        $existing_additional = array_filter(array_map('trim', explode(',', $existing['additional_numbers'])), 'is_numeric');
        $existing_all = array_unique(array_merge($existing_range, $existing_additional));
        $existing_all = array_diff($existing_all, $existing_missing);

        $overlap = array_intersect($all_new, $existing_all);
        if (count($overlap) > 0) {
            $conflict_details = [
                'series_name' => $existing['name'],
                'conflicts' => implode(', ', $overlap)
            ];
            $has_conflict = true;
            break;
        }
    }

    if ($has_conflict && !isset($_POST['force_update'])) {
        echo "<div class='container mt-3'>
            <div class='alert alert-danger'>
                <strong>⚠️ Conflict Detected:</strong> BIB numbers overlap with series <strong>" . htmlspecialchars($conflict_details['series_name']) . "</strong>.<br>
                Conflicting numbers: <code>" . htmlspecialchars($conflict_details['conflicts']) . "</code><br>
                <form method='post'>";
        foreach ($_POST as $key => $value) {
            echo "<input type='hidden' name='" . htmlspecialchars($key) . "' value='" . htmlspecialchars($value) . "'>";
        }
        echo "<input type='hidden' name='force_update' value='1'>
                <button type='submit' class='btn btn-sm btn-danger mt-2'>Ignore and Save Anyway</button>
                </form>
            </div>
        </div>";
        return;
    }

    $stmt = $pdo->prepare("UPDATE bib_series SET name = ?, color = ?, start_number = ?, end_number = ?, missing_numbers = ?, additional_numbers = ? WHERE id = ?");
    $stmt->execute([$name, $color, $start, $end, $missing, $additional, $id]);

    header("Location: bib_assign.php?event_id=" . $event_id);
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Edit BIB Series - <?= htmlspecialchars($series['name']) ?></title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- style skin holder -->
<link id="bootswatch-theme"
      href="/v2/assets/bootswatch/<?= btTheme('nameCode') ?>/bootstrap.min.css"
      rel="stylesheet">
<link rel="stylesheet" href="/v2/assets/css/backgrounds.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">

</head>
<body class="body-bg-aurora-bright">
<?php include '../menu.php'; ?>

<div class="container-fluid container-StyleScore p-4">
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-1">
                <i class="fas fa-edit text-warning me-2"></i>Edit BIB Series
            </h1>
            <p class="text-muted mb-0">Modify settings for "<strong style="color: <?= htmlspecialchars($series['color']) ?>;"><?= htmlspecialchars($series['name']) ?></strong>" series</p>
        </div>
        <div class="d-flex gap-2">
            <a href="bib_assign.php?event_id=<?= $event_id ?>" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left me-1"></i>Back to Manager
            </a>
            <a href="bib_distribute.php?event_id=<?= $event_id ?>" class="btn btn-outline-primary">
                <i class="fas fa-share-alt me-1"></i>Distribution
            </a>
        </div>
    </div>

    <!-- Analytics Cards -->
    <div class="row g-4 mb-4">
        <!-- Series Overview -->
        <div class="col-lg-3 col-md-6">
            <div class="border-0 shadow-none card border-start border-4" style="border-left-color: <?= $series['color'] ?>;">
                <div class="border-0 shadow-none card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="text-muted mb-1">Series Overview</h6>
                            <h4 class="mb-0" style="color: <?= $series['color'] ?>;">
                                <?= $series['start_number'] ?> - <?= $series['end_number'] ?>
                            </h4>
                            <small class="text-muted"><?= $total_in_range ?> numbers in range</small>
                        </div>
                        <div class="text-end">
                            <i class="fas fa-tag fa-2x" style="color: <?= $series['color'] ?>; opacity: 0.3;"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Usage Statistics -->
        <div class="col-lg-3 col-md-6">
            <div class="border-0 shadow-none card border-start border-4 border-primary">
                <div class="border-0 shadow-none card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="text-muted mb-1">Usage Statistics</h6>
                            <h4 class="mb-0 text-primary"><?= $usage_percentage ?>%</h4>
                            <small class="text-muted"><?= $assigned_count ?> of <?= $total_available ?> assigned</small>
                        </div>
                        <div class="text-end">
                            <i class="fas fa-chart-pie fa-2x text-primary" style="opacity: 0.3;"></i>
                        </div>
                    </div>
                    <div class="progress mt-2" style="height: 4px;">
                        <div class="progress-bar" role="progressbar" 
                             style="width: <?= $usage_percentage ?>%; background-color: <?= $series['color'] ?>;" 
                             aria-valuenow="<?= $usage_percentage ?>" aria-valuemin="0" aria-valuemax="100">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Available Numbers -->
        <div class="col-lg-3 col-md-6">
            <div class="border-0 shadow-none card border-start border-4 border-success">
                <div class="border-0 shadow-none card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="text-muted mb-1">Available Numbers</h6>
                            <h4 class="mb-0 text-success"><?= $free_count ?></h4>
                            <small class="text-muted">Ready for assignment</small>
                        </div>
                        <div class="text-end">
                            <i class="fas fa-check-circle fa-2x text-success" style="opacity: 0.3;"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Potential Issues -->
        <div class="col-lg-3 col-md-6">
            <div class="border-0 shadow-none card border-start border-4 <?= $potential_conflicts > 0 ? 'border-warning' : 'border-info' ?>">
                <div class="border-0 shadow-none card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="text-muted mb-1">Potential Issues</h6>
                            <h4 class="mb-0 <?= $potential_conflicts > 0 ? 'text-warning' : 'text-info' ?>">
                                <?= $potential_conflicts ?>
                            </h4>
                            <small class="text-muted">
                                <?= $potential_conflicts > 0 ? 'Conflicting numbers' : 'No conflicts detected' ?>
                            </small>
                        </div>
                        <div class="text-end">
                            <i class="fas <?= $potential_conflicts > 0 ? 'fa-exclamation-triangle text-warning' : 'fa-shield-alt text-info' ?> fa-2x" style="opacity: 0.3;"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Detailed Analytics -->
    <div class="row g-4 mb-4">
        <!-- Number Distribution -->
        <div class="col-lg-6">
            <div class="border-0 shadow-none card">
                <div class="border-0 shadow-none card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-chart-bar text-info me-2"></i>Number Distribution
                    </h6>
                </div>
                <div class="border-0 shadow-none card-body">
                    <div class="row text-center">
                        <div class="col-4">
                            <div class="border-end">
                                <h5 class="text-primary mb-1"><?= $total_in_range ?></h5>
                                <small class="text-muted">In Range</small>
                            </div>
                        </div>
                        <div class="col-4">
                            <div class="border-end">
                                <h5 class="text-warning mb-1"><?= count($missing_numbers) ?></h5>
                                <small class="text-muted">Missing</small>
                            </div>
                        </div>
                        <div class="col-4">
                            <h5 class="text-info mb-1"><?= count($additional_numbers) ?></h5>
                            <small class="text-muted">Additional</small>
                        </div>
                    </div>
                    
                    <?php if (!empty($missing_numbers)): ?>
                    <div class="mt-3">
                        <h6 class="text-warning mb-2">Missing Numbers:</h6>
                        <div class="d-flex flex-wrap gap-1">
                            <?php foreach ($missing_numbers as $num): ?>
                                <span class="badge bg-warning text-dark"><?= $num ?></span>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($additional_numbers)): ?>
                    <div class="mt-3">
                        <h6 class="text-info mb-2">Additional Numbers:</h6>
                        <div class="d-flex flex-wrap gap-1">
                            <?php foreach ($additional_numbers as $num): ?>
                                <span class="badge bg-info"><?= $num ?></span>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Assignment Status -->
        <div class="col-lg-6">
            <div class="border-0 shadow-none card">
                <div class="border-0 shadow-none card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-users text-success me-2"></i>Assignment Status
                    </h6>
                </div>
                <div class="border-0 shadow-none card-body">
                    <?php if ($assigned_count > 0): ?>
                        <div class="mb-3">
                            <h6 class="text-success mb-2">Assigned Numbers (<?= $assigned_count ?>):</h6>
                            <div class="d-flex flex-wrap gap-1" style="max-height: 120px; overflow-y: auto;">
                                <?php foreach ($assigned_numbers as $num): ?>
                                    <span class="badge text-white" style="background-color: <?= $series['color'] ?>;"><?= $num ?></span>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="text-center py-3">
                            <i class="fas fa-user-plus fa-2x text-muted mb-2"></i>
                            <p class="text-muted mb-0">No assignments yet</p>
                            <small class="text-muted">All numbers are available for assignment</small>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($potential_conflicts > 0): ?>
                        <div class="mt-3">
                            <h6 class="text-warning mb-2">Potential Conflicts:</h6>
                            <?php foreach ($conflicting_series as $conflict): ?>
                                <div class="alert alert-warning py-2 mb-2">
                                    <small>
                                        <strong style="color: <?= $conflict['color'] ?>;"><?= htmlspecialchars($conflict['name']) ?></strong>: 
                                        <?php foreach ($conflict['conflicts'] as $i => $num): ?>
                                            <?= $num ?><?= $i < count($conflict['conflicts']) - 1 ? ', ' : '' ?>
                                        <?php endforeach; ?>
                                    </small>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Form -->
    <!-- Edit Form -->
    <div class="row">
        <div class="col-lg-8">
            <div class="border-0 shadow-none card">
                <div class="border-0 shadow-none card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-cog text-primary me-2"></i>Series Configuration
                    </h6>
                </div>
                <div class="border-0 shadow-none card-body">
                    <form method="post">
                        <input type="hidden" name="update_series" value="1">
                        
                        <!-- Series Name -->
                        <div class="mb-4">
                            <label class="form-label fw-bold">
                                <i class="fas fa-tag me-1"></i>Series Name
                            </label>
                            <input type="text" name="name" class="form-control form-control-lg" 
                                   value="<?= htmlspecialchars($series['name']) ?>" 
                                   placeholder="e.g., Youth, Adults, Masters" required>
                            <div class="form-text">Choose a descriptive name for this BIB series</div>
                        </div>

                        <!-- Color Selection -->
                        <div class="mb-4">
                            <label class="form-label fw-bold">
                                <i class="fas fa-palette me-1"></i>Series Color
                            </label>
                            
                            <!-- Predefined Color Picker -->
                            <div class="mb-3">
                                <label class="form-label small text-muted">Quick Select Colors:</label>
                                <div class="d-flex gap-2 flex-wrap">
                                    <button type="button" class="btn color-pick" data-color="#000000" 
                                            style="width: 45px; height: 45px; background-color: #000000; border: 3px solid #dee2e6; border-radius: 10px;" 
                                            title="Black"></button>
                                    <button type="button" class="btn color-pick" data-color="#007BFF" 
                                            style="width: 45px; height: 45px; background-color: #007BFF; border: 3px solid #dee2e6; border-radius: 10px;" 
                                            title="Blue"></button>
                                    <button type="button" class="btn color-pick" data-color="#DC3545" 
                                            style="width: 45px; height: 45px; background-color: #DC3545; border: 3px solid #dee2e6; border-radius: 10px;" 
                                            title="Red"></button>
                                    <button type="button" class="btn color-pick" data-color="#FD7E14" 
                                            style="width: 45px; height: 45px; background-color: #FD7E14; border: 3px solid #dee2e6; border-radius: 10px;" 
                                            title="Orange"></button>
                                    <button type="button" class="btn color-pick" data-color="#28A745" 
                                            style="width: 45px; height: 45px; background-color: #28A745; border: 3px solid #dee2e6; border-radius: 10px;" 
                                            title="Green"></button>
                                    <button type="button" class="btn color-pick" data-color="#6F42C1" 
                                            style="width: 45px; height: 45px; background-color: #6F42C1; border: 3px solid #dee2e6; border-radius: 10px;" 
                                            title="Purple"></button>
                                    <button type="button" class="btn color-pick" data-color="#FFC107" 
                                            style="width: 45px; height: 45px; background-color: #FFC107; border: 3px solid #dee2e6; border-radius: 10px;" 
                                            title="Yellow"></button>
                                    <button type="button" class="btn color-pick" data-color="#003366" 
                                            style="width: 45px; height: 45px; background-color: #003366; border: 3px solid #dee2e6; border-radius: 10px;" 
                                            title="Navy"></button>
                                </div>
                            </div>
                            
                            <!-- Manual Color Input -->
                            <div class="row">
                                <div class="col-md-8">
                                    <div class="input-group">
                                        <span class="input-group-text d-flex align-items-center justify-content-center" 
                                              id="colorPreview" 
                                              style="background-color: <?= htmlspecialchars($series['color']) ?>; width: 60px; border-radius: 6px 0 0 6px;">
                                            <i class="fas fa-eye text-white" style="text-shadow: 1px 1px 2px rgba(0,0,0,0.5);"></i>
                                        </span>
                                        <input type="text" name="color" id="colorInput" class="form-control" 
                                               value="<?= htmlspecialchars($series['color']) ?>" 
                                               placeholder="#ffffff" pattern="^#[0-9A-Fa-f]{6}$" 
                                               title="Enter a valid hex color (e.g., #ff0000)">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <input type="color" id="colorPicker" class="form-control form-control-color h-100" 
                                           value="<?= htmlspecialchars($series['color']) ?>" 
                                           title="Advanced color picker">
                                </div>
                            </div>
                            <div class="form-text">Click a color above, use the color picker, or enter a custom hex color code</div>
                        </div>

                        <!-- Number Range -->
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <label class="form-label fw-bold">
                                    <i class="fas fa-play me-1"></i>Start Number
                                </label>
                                <input type="number" name="start_number" class="form-control form-control-lg" 
                                       value="<?= (int)$series['start_number'] ?>" min="1" required>
                                <div class="form-text">First number in the series</div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-bold">
                                    <i class="fas fa-stop me-1"></i>End Number
                                </label>
                                <input type="number" name="end_number" class="form-control form-control-lg" 
                                       value="<?= (int)$series['end_number'] ?>" min="1" required>
                                <div class="form-text">Last number in the series</div>
                            </div>
                        </div>

                        <!-- Advanced Options -->
                        <div class="border-0 shadow-none card bg-light border-0 mb-4">
                            <div class="border-0 shadow-none card-header bg-transparent border-0 pb-0">
                                <h6 class="text-muted mb-0">
                                    <i class="fas fa-cogs me-1"></i>Advanced Options
                                </h6>
                            </div>
                            <div class="border-0 shadow-none card-body pt-3">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">
                                        <i class="fas fa-minus-circle text-warning me-1"></i>Missing Numbers
                                    </label>
                                    <input type="text" name="missing_numbers" class="form-control" 
                                           value="<?= htmlspecialchars($series['missing_numbers']) ?>"
                                           placeholder="e.g., 13, 17, 25">
                                    <div class="form-text">Numbers to exclude from the range (comma-separated)</div>
                                </div>

                                <div class="mb-0">
                                    <label class="form-label fw-bold">
                                        <i class="fas fa-plus-circle text-info me-1"></i>Additional Numbers
                                    </label>
                                    <input type="text" name="additional_numbers" class="form-control" 
                                           value="<?= htmlspecialchars($series['additional_numbers']) ?>"
                                           placeholder="e.g., 500, 501, 502">
                                    <div class="form-text">Extra numbers outside the main range (comma-separated)</div>
                                </div>
                            </div>
                        </div>

                        <!-- Action Buttons -->
                        <div class="d-flex gap-2 justify-content-between">
                            <div>
                                <button type="submit" class="btn btn-primary btn-lg">
                                    <i class="fas fa-save me-2"></i>Update Series
                                </button>
                                <button type="button" class="btn btn-outline-info" onclick="previewChanges()">
                                    <i class="fas fa-eye me-1"></i>Preview
                                </button>
                            </div>
                            <div>
                                <a href="bib_assign.php?event_id=<?= $event_id ?>" class="btn btn-outline-secondary">
                                    <i class="fas fa-times me-1"></i>Cancel
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Preview Panel -->
        <div class="col-lg-4">
            <div class="border-0 shadow-none card sticky-top" style="top: 20px;">
                <div class="border-0 shadow-none card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-eye text-info me-2"></i>Live Preview
                    </h6>
                </div>
                <div class="border-0 shadow-none card-body">
                    <div id="seriesPreview">
                        <div class="text-center">
                            <div class="badge text-white p-3 mb-3" 
                                 style="background-color: <?= $series['color'] ?>; font-size: 16px;">
                                <?= htmlspecialchars($series['name']) ?>
                            </div>
                            <p class="text-muted mb-2">Range: <?= $series['start_number'] ?> - <?= $series['end_number'] ?></p>
                            <p class="text-muted mb-0">Total: <?= $total_available ?> numbers</p>
                        </div>
                    </div>
                    
                    <hr>
                    
                    <div class="text-center">
                        <h6 class="text-muted mb-3">Current Status</h6>
                        <div class="row text-center">
                            <div class="col-6">
                                <h5 class="text-success mb-1"><?= $free_count ?></h5>
                                <small class="text-muted">Available</small>
                            </div>
                            <div class="col-6">
                                <h5 class="text-primary mb-1"><?= $assigned_count ?></h5>
                                <small class="text-muted">Assigned</small>
                            </div>
                        </div>
                        
                        <div class="progress mt-3" style="height: 8px;">
                            <div class="progress-bar" role="progressbar" 
                                 style="width: <?= $usage_percentage ?>%; background-color: <?= $series['color'] ?>;" 
                                 aria-valuenow="<?= $usage_percentage ?>" aria-valuemin="0" aria-valuemax="100">
                            </div>
                        </div>
                        <small class="text-muted"><?= $usage_percentage ?>% utilized</small>
                    </div>
                    
                    <hr>
                    
                    <div class="d-grid gap-2">
                        <a href="bib_distribute.php?event_id=<?= $event_id ?>" class="btn btn-outline-primary btn-sm">
                            <i class="fas fa-share-alt me-1"></i>Distribute BIBs
                        </a>
                        <button type="button" class="btn btn-outline-info btn-sm" onclick="viewDetailedStats()">
                            <i class="fas fa-chart-line me-1"></i>Detailed Stats
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const colorInput = document.getElementById('colorInput');
    const colorPreview = document.getElementById('colorPreview');
    const colorPicker = document.getElementById('colorPicker');
    const colorPicks = document.querySelectorAll('.color-pick');
    const nameInput = document.querySelector('input[name="name"]');
    const startInput = document.querySelector('input[name="start_number"]');
    const endInput = document.querySelector('input[name="end_number"]');
    
    // Handle predefined color selection
    colorPicks.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const color = this.getAttribute('data-color');
            setColor(color);
            updateActiveColorButton(this);
        });
    });
    
    // Handle color picker input
    colorPicker.addEventListener('input', function() {
        const color = this.value.toUpperCase();
        setColor(color);
        updateActiveColorFromValue(color);
    });
    
    // Handle manual color input
    colorInput.addEventListener('input', function() {
        const color = this.value.toUpperCase();
        if (isValidHexColor(color)) {
            colorPicker.value = color;
            updateColorPreview(color);
            updateActiveColorFromValue(color);
            updateLivePreview();
        }
    });
    
    // Handle form inputs for live preview
    [nameInput, startInput, endInput].forEach(input => {
        if (input) {
            input.addEventListener('input', updateLivePreview);
        }
    });
    
    // Set color and update all related elements
    function setColor(color) {
        colorInput.value = color;
        colorPicker.value = color;
        updateColorPreview(color);
        updateLivePreview();
    }
    
    // Update active color button
    function updateActiveColorButton(activeButton) {
        colorPicks.forEach(btn => {
            btn.classList.remove('active');
            btn.style.borderColor = '#dee2e6';
            btn.style.borderWidth = '3px';
            btn.style.transform = 'scale(1)';
        });
        activeButton.classList.add('active');
        activeButton.style.borderColor = '#0d6efd';
        activeButton.style.borderWidth = '4px';
        activeButton.style.transform = 'scale(1.1)';
    }
    
    // Update active color from value
    function updateActiveColorFromValue(color) {
        colorPicks.forEach(button => {
            if (button.getAttribute('data-color').toLowerCase() === color.toLowerCase()) {
                updateActiveColorButton(button);
            }
        });
    }
    
    // Update color preview
    function updateColorPreview(color) {
        if (isValidHexColor(color)) {
            colorPreview.style.backgroundColor = color;
            const rgb = hexToRgb(color);
            const brightness = (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
            const iconColor = brightness > 128 ? '#000000' : '#ffffff';
            const icon = colorPreview.querySelector('i');
            if (icon) {
                icon.style.color = iconColor;
            }
        }
    }
    
    // Update live preview
    function updateLivePreview() {
        const name = nameInput.value || 'Unnamed Series';
        const color = colorInput.value || '#007bff';
        const start = parseInt(startInput.value) || 0;
        const end = parseInt(endInput.value) || 0;
        
        const previewElement = document.querySelector('#seriesPreview .badge');
        const rangeElement = document.querySelector('#seriesPreview p');
        
        if (previewElement) {
            previewElement.textContent = name;
            previewElement.style.backgroundColor = color;
        }
        
        if (rangeElement && start > 0 && end > 0) {
            const total = Math.max(0, end - start + 1);
            rangeElement.innerHTML = `Range: ${start} - ${end}<br><small>Total: ${total} numbers</small>`;
        }
    }
    
    // Validate hex color
    function isValidHexColor(color) {
        return /^#[0-9A-F]{6}$/i.test(color);
    }
    
    // Convert hex to RGB for brightness calculation
    function hexToRgb(hex) {
        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;
    }
    
    // Initialize on page load
    const currentColor = colorInput.value;
    if (currentColor) {
        updateColorPreview(currentColor);
        updateActiveColorFromValue(currentColor);
    }
});

// Preview changes function
function previewChanges() {
    const formData = new FormData(document.querySelector('form'));
    const name = formData.get('name');
    const color = formData.get('color');
    const start = parseInt(formData.get('start_number'));
    const end = parseInt(formData.get('end_number'));
    const missing = formData.get('missing_numbers');
    const additional = formData.get('additional_numbers');
    
    let content = `
        <div class="text-center mb-3">
            <div class="badge text-white p-3" style="background-color: ${color}; font-size: 18px;">
                ${name}
            </div>
        </div>
        <table class="table table-sm">
            <tr><td><strong>Range:</strong></td><td>${start} - ${end}</td></tr>
            <tr><td><strong>Total in Range:</strong></td><td>${end - start + 1}</td></tr>
    `;
    
    if (missing) {
        const missingCount = missing.split(',').filter(n => n.trim()).length;
        content += `<tr><td><strong>Missing:</strong></td><td>${missingCount} numbers</td></tr>`;
    }
    
    if (additional) {
        const additionalCount = additional.split(',').filter(n => n.trim()).length;
        content += `<tr><td><strong>Additional:</strong></td><td>${additionalCount} numbers</td></tr>`;
    }
    
    content += '</table>';
    
    // Show in modal
    const modal = `
        <div class="modal fade" id="previewModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Series Preview</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">${content}</div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    document.body.insertAdjacentHTML('beforeend', modal);
    const previewModal = new bootstrap.Modal(document.getElementById('previewModal'));
    previewModal.show();
    
    // Clean up when modal is hidden
    document.getElementById('previewModal').addEventListener('hidden.bs.modal', function() {
        this.remove();
    });
}

// View detailed stats function
function viewDetailedStats() {
    // This could be expanded to show more detailed analytics
    alert('Detailed statistics feature coming soon!');
}

// Form validation
document.querySelector('form').addEventListener('submit', function(e) {
    const start = parseInt(document.querySelector('input[name="start_number"]').value);
    const end = parseInt(document.querySelector('input[name="end_number"]').value);
    
    if (start >= end) {
        e.preventDefault();
        alert('End number must be greater than start number.');
        return false;
    }
    
    const color = document.querySelector('input[name="color"]').value;
    if (!/^#[0-9A-F]{6}$/i.test(color)) {
        e.preventDefault();
        alert('Please enter a valid hex color code (e.g., #ff0000).');
        return false;
    }
});
</script>
</body>
</html>