<?php
include '../includes/auth.php';
include '../includes/db.php';
include '../includes/bib_helpers.php'; // Modularized BIB logic

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

// Check for success/error messages
$success_message = $_GET['success'] ?? null;
$error_message = $_GET['error'] ?? null;

// Fetch event list
$events = $pdo->query("SELECT id, name FROM events ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);

$bib_series = [];
$participants = [];

if ($event_id) {
    $bib_series = get_bib_series_for_event($pdo, $event_id);
    $participants = get_event_participants_for_bib_distribution($pdo, $event_id);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BIB Distribution Manager</title>
<?php include_once '../includes/stylesheets.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
</head>
<body class="body-bg-aurora-bright">
<?php include '../menu.php'; ?>

<div class="container-fluid container-StyleScore p-4">
        <!-- Event Actions Menu -->
    <div class="row mb-4">
        <div class="col-12">
            <?php       
            $use_localStorage = true;
            $show_header = false;
            include 'event_actions_menu.php'; 
            ?>
        </div>
    </div>
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-1">
                <i class="fas fa-share-alt text-primary me-2"></i>BIB Distribution Manager
            </h1>
            <p class="text-muted mb-0">Distribute and manage BIB numbers for event participants</p>
        </div>
        <div class="d-flex align-items-center gap-3">
            <button type="button" class="btn btn-outline-info" onclick="showHelpModal()">
                <i class="fas fa-question-circle me-1"></i>Help & Manual
            </button>
            <div class="text-end">
                <small class="text-muted">
                    <i class="fas fa-users me-1"></i>Participant Assignment System
                </small>
            </div>
        </div>
    </div>

    <!-- Success/Error Messages -->
    <?php if ($success_message): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i><?= htmlspecialchars($success_message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    
    <?php if ($error_message): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i><?= htmlspecialchars($error_message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Event Selection -->
    <div class="border-0 shadow-none card bg-primary text-white mb-4">
        <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center border-0">
            <h5 class="mb-0">
                <i class="fas fa-calendar-alt me-2"></i>Event Selection
            </h5>
        </div>
        <div class="border-0 shadow-none card-body">
            <form method="get">
                <div class="row g-3 align-items-end">
                    <div class="col-md-8">
                        <label for="event_id" class="form-label text-white">Select Event:</label>
                        <select name="event_id" id="event_id" class="form-select" onchange="this.form.submit()" required>
                            <option value="">-- Choose Event --</option>
                            <?php foreach ($events as $event): ?>
                                <option value="<?= $event['id'] ?>" <?= $event_id == $event['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($event['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <button type="submit" class="btn btn-light">
                            <i class="fas fa-search me-2"></i>Load Event
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <?php if ($event_id): ?>
    
    <?php
    // Enhanced data processing for series preview
    $series_stats = [];
    $participant_assignments = [];
    
    foreach ($bib_series as $series) {
        // Calculate all available numbers for this series
        $range_numbers = 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');
        $all_available = array_unique(array_merge($range_numbers, $additional_numbers));
        $all_available = array_diff($all_available, $missing_numbers);
        sort($all_available);
        
        // Find which participants are using numbers from this series
        $used_numbers = [];
        $assigned_participants = [];
        
        foreach ($participants as $participant) {
            if ($participant['bib_number'] && in_array($participant['bib_number'], $all_available)) {
                $used_numbers[] = $participant['bib_number'];
                $assigned_participants[] = [
                    'id' => $participant['id'],
                    'name' => $participant['first_name'] . ' ' . $participant['last_name'],
                    'bib_number' => $participant['bib_number']
                ];
            }
        }
        
        $series_stats[$series['id']] = [
            'series' => $series,
            'available_numbers' => $all_available,
            'used_numbers' => $used_numbers,
            'free_numbers' => array_diff($all_available, $used_numbers),
            'assigned_participants' => $assigned_participants,
            'total_available' => count($all_available),
            'total_used' => count($used_numbers),
            'usage_percentage' => count($all_available) > 0 ? round((count($used_numbers) / count($all_available)) * 100, 1) : 0
        ];
    }
    ?>
    
    <!-- BIB Series Overview -->
    <div class="row g-4 mb-4">
        <div class="col-12">
            <div class="border-0 shadow-none card">
                <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">
                        <i class="fas fa-chart-pie text-info me-2"></i>BIB Series Overview
                    </h6>
                    <div class="d-flex align-items-center gap-2">
                        <span class="badge bg-secondary"><?= count($bib_series) ?> series</span>
                        <div class="btn-group" role="group">
                            <button type="button" class="btn btn-sm btn-outline-primary" onclick="createNewSeries()">
                                <i class="fas fa-plus me-1"></i>New Series
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="manageAllSeries()">
                                <i class="fas fa-cog me-1"></i>Manage All
                            </button>
                        </div>
                    </div>
                </div>
                <div class="border-0 shadow-none card-body">
                    <?php if (empty($bib_series)): ?>
                        <div class="text-center py-4">
                            <i class="fas fa-tags fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">No BIB Series Found</h5>
                            <p class="text-muted">Create BIB series first in the BIB Series Manager</p>
                            <a href="bib_assign.php?event_id=<?= $event_id ?>" class="btn btn-primary">
                                <i class="fas fa-plus me-2"></i>Create BIB Series
                            </a>
                        </div>
                    <?php else: ?>
                        <div class="row g-3">
                            <?php foreach ($series_stats as $stat): ?>
                                <div class="col-lg-4 col-md-6">
                                    <div class="border-0 shadow-none card border-start border-4" style="border-left-color: <?= $stat['series']['color'] ?>;">
                                        <div class="border-0 shadow-none card-body">
                                            <div class="d-flex justify-content-between align-items-start mb-3">
                                                <div>
                                                    <h6 class="fw-bold mb-1" style="color: <?= $stat['series']['color'] ?>;">
                                                        <i class="fas fa-tag me-1"></i>
                                                        <?= htmlspecialchars($stat['series']['name']) ?>
                                                    </h6>
                                                    <small class="text-muted">
                                                        Range: <?= $stat['series']['start_number'] ?> - <?= $stat['series']['end_number'] ?>
                                                    </small>
                                                </div>
                                                <span class="badge text-white px-2 py-1" style="background-color: <?= $stat['series']['color'] ?>;">
                                                    BIB
                                                </span>
                                            </div>
                                            
                                            <!-- Usage Statistics -->
                                            <div class="row g-2 mb-3">
                                                <div class="col-4 text-center">
                                                    <div class="h5 mb-0 text-primary"><?= $stat['total_available'] ?></div>
                                                    <small class="text-muted">Available</small>
                                                </div>
                                                <div class="col-4 text-center">
                                                    <div class="h5 mb-0 text-success"><?= $stat['total_used'] ?></div>
                                                    <small class="text-muted">Used</small>
                                                </div>
                                                <div class="col-4 text-center">
                                                    <div class="h5 mb-0 text-secondary"><?= count($stat['free_numbers']) ?></div>
                                                    <small class="text-muted">Free</small>
                                                </div>
                                            </div>
                                            
                                            <!-- Usage Progress -->
                                            <div class="mb-3">
                                                <div class="d-flex justify-content-between mb-1">
                                                    <small class="text-muted">Usage</small>
                                                    <small class="fw-bold"><?= $stat['usage_percentage'] ?>%</small>
                                                </div>
                                                <div class="progress" style="height: 8px;">
                                                    <div class="progress-bar" 
                                                         style="width: <?= $stat['usage_percentage'] ?>%; background-color: <?= $stat['series']['color'] ?>;">
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <!-- Quick Actions -->
                                            <div class="d-flex gap-2">
                                                <button class="btn btn-sm btn-outline-primary flex-fill" 
                                                        onclick="showSeriesDetails('<?= $stat['series']['id'] ?>')">
                                                    <i class="fas fa-eye me-1"></i>View Details
                                                </button>
                                                <button class="btn btn-sm btn-outline-secondary" 
                                                        onclick="showAvailableNumbers('<?= $stat['series']['id'] ?>')">
                                                    <i class="fas fa-list me-1"></i>Numbers
                                                </button>
                                                <button class="btn btn-sm btn-outline-warning" 
                                                        onclick="editSeries('<?= $stat['series']['id'] ?>')">
                                                    <i class="fas fa-edit me-1"></i>Edit
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <!-- Participant Assignment -->
    <div class="row g-4 mb-4">
        <!-- Assignment Form -->
        <div class="col-lg-8">
            <div class="border-0 shadow-none card">
                <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">
                        <i class="fas fa-users text-success me-2"></i>Participant BIB Assignment
                    </h6>
                    <div>
                        <span class="badge bg-info me-2"><?= count($participants) ?> participants</span>
                        <button class="btn btn-sm btn-outline-secondary" onclick="autoAssignBIBs()">
                            <i class="fas fa-magic me-1"></i>Auto Assign
                        </button>
                    </div>
                </div>
                <div class="border-0 shadow-none card-body p-0">
                    <form method="post" action="bib_distribute_process.php" id="bibAssignForm">
                        <input type="hidden" name="event_id" value="<?= htmlspecialchars($event_id) ?>">
                        
                        <?php if (empty($participants)): ?>
                            <div class="text-center py-5">
                                <i class="fas fa-user-plus fa-3x text-muted mb-3"></i>
                                <h5 class="text-muted">No Participants Found</h5>
                                <p class="text-muted">Add participants to this event first</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover mb-0" id="participantTable">
                                    <thead class="table-light">
                                        <tr>
                                            <th scope="col" class="sortable" data-sort="name" style="cursor: pointer;">
                                                <i class="fas fa-user me-1"></i>Participant
                                                <i class="fas fa-sort ms-1 text-muted sort-icon"></i>
                                            </th>
                                            <th scope="col" class="text-center sortable" data-sort="current-bib" style="cursor: pointer;">
                                                <i class="fas fa-tag me-1"></i>Current BIB
                                                <i class="fas fa-sort ms-1 text-muted sort-icon"></i>
                                            </th>
                                            <th scope="col" class="text-center sortable" data-sort="new-bib" style="cursor: pointer;">
                                                <i class="fas fa-edit me-1"></i>New BIB
                                                <i class="fas fa-sort ms-1 text-muted sort-icon"></i>
                                            </th>
                                            <th scope="col" class="text-center">
                                                <i class="fas fa-palette me-1"></i>Series
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    <?php foreach ($participants as $p): ?>
                                        <?php
                                        // Find which series this participant's current BIB belongs to
                                        $current_series = null;
                                        if ($p['bib_number']) {
                                            foreach ($series_stats as $stat) {
                                                if (in_array($p['bib_number'], $stat['available_numbers'])) {
                                                    $current_series = $stat['series'];
                                                    break;
                                                }
                                            }
                                        }
                                        ?>
                                        <tr data-participant-name="<?= htmlspecialchars(strtolower($p['last_name'] . ' ' . $p['first_name'])) ?>" 
                                            data-current-bib="<?= $p['bib_number'] ?? 0 ?>" 
                                            data-new-bib="<?= $p['bib_number'] ?? 0 ?>">
                                            <td>
                                                <div class="d-flex align-items-center">
                                                    <div class="me-2">
                                                        <div class="bg-secondary rounded-circle d-flex align-items-center justify-content-center" style="width: 32px; height: 32px;">
                                                            <span class="text-white fw-bold small"><?= strtoupper(substr($p['first_name'], 0, 1) . substr($p['last_name'], 0, 1)) ?></span>
                                                        </div>
                                                    </div>
                                                    <div>
                                                        <div class="fw-medium"><?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?></div>
                                                        <small class="text-muted">
                                                            ID: <?= $p['id'] ?> | 
                                                            Heats: <?= htmlspecialchars($p['heat_numbers'] ?? 'N/A') ?>
                                                        </small>
                                                    </div>
                                                </div>
                                            </td>
                                            <td class="text-center">
                                                <?php if ($p['bib_number']): ?>
                                                    <span class="badge text-white px-3 py-2" 
                                                          style="background-color: <?= $current_series['color'] ?? '#6c757d' ?>;">
                                                        <?= htmlspecialchars($p['bib_number']) ?>
                                                    </span>
                                                <?php else: ?>
                                                    <span class="text-muted">Not assigned</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-center">
                                                <input type="number" 
                                                       name="bib_assign[<?= $p['id'] ?>]" 
                                                       class="form-control text-center bib-input" 
                                                       style="max-width: 100px; margin: 0 auto;"
                                                       value="<?= htmlspecialchars($p['bib_number'] ?? '') ?>"
                                                       placeholder="Enter BIB"
                                                       data-participant-id="<?= $p['id'] ?>"
                                                       onchange="updateBIBPreview(this)">
                                            </td>
                                            <td class="text-center">
                                                <span class="series-indicator" id="series-indicator-<?= $p['id'] ?>">
                                                    <?php if ($current_series): ?>
                                                        <span class="badge" style="background-color: <?= $current_series['color'] ?>; color: white;">
                                                            <?= htmlspecialchars($current_series['name']) ?>
                                                        </span>
                                                    <?php else: ?>
                                                        <span class="text-muted small">No series</span>
                                                    <?php endif; ?>
                                                </span>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            
                            <div class="border-0 shadow-none card-footer">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <button type="button" class="btn btn-outline-warning me-2" onclick="clearAllBIBs()">
                                            <i class="fas fa-eraser me-1"></i>Clear All
                                        </button>
                                        <button type="button" class="btn btn-outline-info" onclick="validateBIBs()">
                                            <i class="fas fa-check-circle me-1"></i>Validate
                                        </button>
                                        <button type="button" class="btn btn-outline-secondary" onclick="generatePrintReport()">
                                            <i class="fas fa-print me-1"></i>Print Report
                                        </button>
                                        <button type="button" class="btn btn-outline-primary" onclick="showDetailedReport()">
                                            <i class="fas fa-list-alt me-1"></i>Detailed Report
                                        </button>
                                    </div>
                                    <div>
                                        <button type="submit" class="btn btn-success btn-lg">
                                            <i class="fas fa-save me-2"></i>Save BIB Assignments
                                        </button>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- Quick Assignment Tools -->
        <div class="col-lg-4">
            <div class="border-0 shadow-none card">
                <div class="border-0 shadow-none card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-tools text-warning me-2"></i>Assignment Tools
                    </h6>
                </div>
                <div class="border-0 shadow-none card-body">
                    <!-- Quick Series Assignment -->
                    <div class="mb-4">
                        <label class="form-label small fw-medium">Quick Series Assignment:</label>
                        <?php foreach ($bib_series as $series): ?>
                            <div class="d-flex align-items-center justify-content-between mb-2 p-2 border rounded">
                                <div class="d-flex align-items-center">
                                    <span class="badge text-white me-2" style="background-color: <?= $series['color'] ?>;">
                                        <?= substr($series['name'], 0, 3) ?>
                                    </span>
                                    <small><?= htmlspecialchars($series['name']) ?></small>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-primary" 
                                        onclick="assignNextAvailable('<?= $series['id'] ?>')">
                                    <i class="fas fa-arrow-right me-1"></i>Assign
                                </button>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <!-- Assignment Statistics -->
                    <div class="border-top pt-3">
                        <label class="form-label small fw-medium">Assignment Status:</label>
                        <div class="row g-2 text-center">
                            <div class="col-4">
                                <div class="h6 mb-0 text-success" id="assignedCount">
                                    <?= count(array_filter($participants, function($p) { return !empty($p['bib_number']); })) ?>
                                </div>
                                <small class="text-muted">Assigned</small>
                            </div>
                            <div class="col-4">
                                <div class="h6 mb-0 text-warning" id="unassignedCount">
                                    <?= count(array_filter($participants, function($p) { return empty($p['bib_number']); })) ?>
                                </div>
                                <small class="text-muted">Unassigned</small>
                            </div>
                            <div class="col-4">
                                <div class="h6 mb-0 text-info" id="conflictCount">0</div>
                                <small class="text-muted">Conflicts</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <?php endif; ?>
</div>

<!-- Detailed BIB Report Modal -->
<div class="modal fade" id="detailedReportModal" tabindex="-1" aria-labelledby="detailedReportModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="detailedReportModalLabel">
                    <i class="fas fa-chart-bar me-2"></i>Detailed BIB Report
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- Tab Navigation -->
                <ul class="nav nav-tabs" id="reportTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="assignments-tab" data-bs-toggle="tab" data-bs-target="#assignments-pane" type="button" role="tab">
                            <i class="fas fa-users me-1"></i>Assignments
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="free-tab" data-bs-toggle="tab" data-bs-target="#free-pane" type="button" role="tab">
                            <i class="fas fa-tags me-1"></i>Free Numbers
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="combined-tab" data-bs-toggle="tab" data-bs-target="#combined-pane" type="button" role="tab">
                            <i class="fas fa-list me-1"></i>Combined View
                        </button>
                    </li>
                </ul>
                
                <!-- Tab Content -->
                <div class="tab-content mt-3" id="reportTabContent">
                    <!-- Assignments Tab -->
                    <div class="tab-pane fade show active" id="assignments-pane" role="tabpanel">
                        <div id="assignmentsContent">
                            <!-- Content will be populated by JavaScript -->
                        </div>
                    </div>
                    
                    <!-- Free Numbers Tab -->
                    <div class="tab-pane fade" id="free-pane" role="tabpanel">
                        <div id="freeNumbersContent">
                            <!-- Content will be populated by JavaScript -->
                        </div>
                    </div>
                    
                    <!-- Combined Tab -->
                    <div class="tab-pane fade" id="combined-pane" role="tabpanel">
                        <div id="combinedContent">
                            <!-- Content will be populated by JavaScript -->
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" onclick="printModalContent()">
                    <i class="fas fa-print me-1"></i>Print Report
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Series Details Modal -->
<div class="modal fade" id="seriesDetailsModal" tabindex="-1" aria-labelledby="seriesDetailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="seriesDetailsModalLabel">Series Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="seriesDetailsContent">
                <!-- Content will be populated by JavaScript -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Available Numbers Modal -->
<div class="modal fade" id="availableNumbersModal" tabindex="-1" aria-labelledby="availableNumbersModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="availableNumbersModalLabel">Available Numbers</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="availableNumbersContent">
                <!-- Content will be populated by JavaScript -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" onclick="printAvailableNumbers()">
                    <i class="fas fa-print me-1"></i>Print List
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Series Management Modal -->
<div class="modal fade" id="seriesManagementModal" tabindex="-1" aria-labelledby="seriesManagementModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="seriesManagementModalLabel">Create New BIB Series</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="seriesForm">
                    <input type="hidden" id="seriesId" name="series_id">
                    <input type="hidden" name="event_id" value="<?= $event_id ?>">
                    
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label for="seriesName" class="form-label">Series Name *</label>
                            <input type="text" class="form-control" id="seriesName" name="series_name" required>
                            <div class="form-text">e.g., "Youth", "Adults", "Masters"</div>
                        </div>
                        <div class="col-md-6">
                            <label for="seriesColor" class="form-label">Series Color *</label>
                            <div class="input-group">
                                <input type="color" class="form-control form-control-color" id="seriesColor" name="series_color" value="#007bff" required>
                                <input type="text" class="form-control" id="seriesColorText" placeholder="#007bff">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <label for="startNumber" class="form-label">Start Number *</label>
                            <input type="number" class="form-control" id="startNumber" name="start_number" min="1" required>
                        </div>
                        <div class="col-md-6">
                            <label for="endNumber" class="form-label">End Number *</label>
                            <input type="number" class="form-control" id="endNumber" name="end_number" min="1" required>
                        </div>
                        <div class="col-12">
                            <label for="missingNumbers" class="form-label">Missing Numbers (Optional)</label>
                            <input type="text" class="form-control" id="missingNumbers" name="missing_numbers" placeholder="e.g., 13, 17, 25">
                            <div class="form-text">Numbers to exclude from the range (comma-separated)</div>
                        </div>
                        <div class="col-12">
                            <label for="additionalNumbers" class="form-label">Additional Numbers (Optional)</label>
                            <input type="text" class="form-control" id="additionalNumbers" name="additional_numbers" placeholder="e.g., 500, 501, 502">
                            <div class="form-text">Extra numbers outside the main range (comma-separated)</div>
                        </div>
                        <div class="col-12">
                            <label for="seriesDescription" class="form-label">Description (Optional)</label>
                            <textarea class="form-control" id="seriesDescription" name="description" rows="2" placeholder="Brief description of this series..."></textarea>
                        </div>
                    </div>
                    
                    <div class="mt-3">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            <strong>Preview:</strong> <span id="seriesPreview">Enter details to see preview</span>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="saveSeries()">
                    <i class="fas fa-save me-1"></i><span id="saveButtonText">Create Series</span>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Help Manual Modal -->
<div class="modal fade" id="helpModal" tabindex="-1" aria-labelledby="helpModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="helpModalLabel">
                    <i class="fas fa-question-circle text-info me-2"></i>BIB Distribution Manager - User Manual
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" style="max-height: 70vh; overflow-y: auto;">
                <div id="helpContent">
                    <div class="text-center py-4">
                        <i class="fas fa-spinner fa-spin fa-2x text-primary"></i>
                        <p class="mt-2">Loading manual content...</p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-primary" onclick="printManual()">
                    <i class="fas fa-print me-1"></i>Print Manual
                </button>
                <button type="button" class="btn btn-outline-success" onclick="downloadManual()">
                    <i class="fas fa-download me-1"></i>Download PDF
                </button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
// Table sorting functionality - Define early for global access
let currentSort = { column: null, direction: 'asc' };

function sortTable(column) {
    const tbody = document.querySelector('#participantTable tbody');
    if (!tbody) return;
    
    const rows = Array.from(tbody.querySelectorAll('tr'));
    if (rows.length === 0) return;
    
    // Determine sort direction
    if (currentSort.column === column) {
        currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
    } else {
        currentSort.direction = 'asc';
    }
    currentSort.column = column;
    
    // Sort rows
    rows.sort((a, b) => {
        let aValue, bValue;
        
        switch (column) {
            case 'name':
                aValue = (a.dataset.participantName || '').toLowerCase();
                bValue = (b.dataset.participantName || '').toLowerCase();
                break;
            case 'current-bib':
                aValue = parseInt(a.dataset.currentBib) || 0;
                bValue = parseInt(b.dataset.currentBib) || 0;
                break;
            case 'new-bib':
                const aInput = a.querySelector('.bib-input');
                const bInput = b.querySelector('.bib-input');
                aValue = parseInt(aInput?.value) || 0;
                bValue = parseInt(bInput?.value) || 0;
                break;
            default:
                return 0;
        }
        
        // Compare values
        let result;
        if (typeof aValue === 'string') {
            result = aValue.localeCompare(bValue);
        } else {
            result = aValue - bValue;
        }
        
        return currentSort.direction === 'asc' ? result : -result;
    });
    
    // Re-append sorted rows
    rows.forEach(row => tbody.appendChild(row));
    
    // Update sort icons
    updateSortIcons(column);
}

function updateSortIcons(activeColumn) {
    document.querySelectorAll('.sort-icon').forEach(icon => {
        icon.className = 'fas fa-sort ms-1 text-muted sort-icon';
    });
    
    const activeHeader = document.querySelector(`[data-sort="${activeColumn}"] .sort-icon`);
    if (activeHeader) {
        const iconClass = currentSort.direction === 'asc' ? 'fa-sort-up' : 'fa-sort-down';
        activeHeader.className = `fas ${iconClass} ms-1 text-primary sort-icon`;
    }
}

// Make functions available globally
window.sortTable = sortTable;

// Add click listeners to sortable headers
function initializeSorting() {
    // Add click listeners to sortable headers
    document.querySelectorAll('.sortable').forEach(header => {
        header.addEventListener('click', function(e) {
            e.preventDefault();
            const sortColumn = this.dataset.sort;
            sortTable(sortColumn);
        });
    });
    
    // Update new-bib data attributes when inputs change
    document.querySelectorAll('.bib-input').forEach(input => {
        input.addEventListener('input', function() {
            const row = this.closest('tr');
            if (row) {
                row.dataset.newBib = this.value || '0';
            }
        });
    });
}

// BIB series data for JavaScript - ensure it's always an array
const bibSeries = <?= isset($series_stats) && !empty($series_stats) ? json_encode(array_values($series_stats)) : '[]' ?>;
const availableNumbers = {};

// Create lookup for available numbers by series
if (Array.isArray(bibSeries)) {
    bibSeries.forEach(series => {
        if (series && series.series && series.series.id) {
            availableNumbers[series.series.id] = series.available_numbers || [];
        }
    });
}

// Update BIB preview when input changes
function updateBIBPreview(input) {
    const participantId = input.dataset.participantId;
    const bibNumber = parseInt(input.value);
    const indicator = document.getElementById(`series-indicator-${participantId}`);
    
    if (!bibNumber || isNaN(bibNumber)) {
        indicator.innerHTML = '<span class="text-muted small">No series</span>';
        return;
    }
    
    // Find which series this BIB belongs to
    let foundSeries = null;
    if (Array.isArray(bibSeries)) {
        for (const seriesData of bibSeries) {
            if (seriesData && seriesData.available_numbers && seriesData.available_numbers.includes(bibNumber)) {
                foundSeries = seriesData.series;
                break;
            }
        }
    }
    
    if (foundSeries) {
        indicator.innerHTML = `<span class="badge" style="background-color: ${foundSeries.color}; color: white;">${foundSeries.name}</span>`;
    } else {
        indicator.innerHTML = '<span class="badge bg-danger">Invalid BIB</span>';
    }
    
    updateAssignmentStats();
}

// Auto assign BIBs to unassigned participants
function autoAssignBIBs() {
    if (!Array.isArray(bibSeries) || bibSeries.length === 0) {
        showAlert('No BIB series available for assignment', 'warning');
        return;
    }
    
    const inputs = document.querySelectorAll('.bib-input');
    const usedNumbers = new Set();
    
    // Get currently used numbers
    inputs.forEach(input => {
        if (input.value && !isNaN(parseInt(input.value))) {
            usedNumbers.add(parseInt(input.value));
        }
    });
    
    // Create a pool of all available numbers
    let availablePool = [];
    bibSeries.forEach(seriesData => {
        if (seriesData && seriesData.available_numbers && Array.isArray(seriesData.available_numbers)) {
            seriesData.available_numbers.forEach(num => {
                if (!usedNumbers.has(num)) {
                    availablePool.push({
                        number: num,
                        seriesId: seriesData.series.id,
                        seriesColor: seriesData.series.color,
                        seriesName: seriesData.series.name
                    });
                }
            });
        }
    });
    
    // Sort by number for sequential assignment
    availablePool.sort((a, b) => a.number - b.number);
    
    let poolIndex = 0;
    inputs.forEach(input => {
        if (!input.value && poolIndex < availablePool.length) {
            const assignment = availablePool[poolIndex];
            input.value = assignment.number;
            updateBIBPreview(input);
            poolIndex++;
        }
    });
    
    if (poolIndex > 0) {
        showAlert(`Auto-assigned ${poolIndex} BIB numbers`, 'success');
    } else {
        showAlert('No available BIB numbers to assign', 'warning');
    }
}

// Assign next available number from specific series
function assignNextAvailable(seriesId) {
    if (!Array.isArray(bibSeries) || bibSeries.length === 0) {
        showAlert('No BIB series available', 'warning');
        return;
    }
    
    const inputs = document.querySelectorAll('.bib-input');
    const usedNumbers = new Set();
    
    // Get currently used numbers
    inputs.forEach(input => {
        if (input.value && !isNaN(parseInt(input.value))) {
            usedNumbers.add(parseInt(input.value));
        }
    });
    
    // Find series data
    const seriesData = bibSeries.find(s => s && s.series && s.series.id == seriesId);
    if (!seriesData || !seriesData.available_numbers) {
        showAlert('Series not found or no available numbers', 'warning');
        return;
    }
    
    // Find available numbers from this series
    const availableInSeries = seriesData.available_numbers.filter(num => !usedNumbers.has(num));
    availableInSeries.sort((a, b) => a - b);
    
    if (availableInSeries.length === 0) {
        showAlert(`No available numbers in ${seriesData.series.name} series`, 'warning');
        return;
    }
    
    // Find first unassigned participant
    const unassignedInput = Array.from(inputs).find(input => !input.value);
    if (!unassignedInput) {
        showAlert('All participants already have BIB numbers', 'info');
        return;
    }
    
    // Assign the first available number
    unassignedInput.value = availableInSeries[0];
    updateBIBPreview(unassignedInput);
    showAlert(`Assigned BIB ${availableInSeries[0]} from ${seriesData.series.name}`, 'success');
}

// Clear all BIB assignments
function clearAllBIBs() {
    if (confirm('Are you sure you want to clear all BIB assignments?')) {
        document.querySelectorAll('.bib-input').forEach(input => {
            input.value = '';
            updateBIBPreview(input);
        });
        showAlert('All BIB assignments cleared', 'info');
    }
}

// Validate BIB assignments
function validateBIBs() {
    const inputs = document.querySelectorAll('.bib-input');
    const bibToParticipant = new Map(); // Track which participant has which BIB
    const conflicts = [];
    const invalidNumbers = [];
    let totalAssignments = 0;
    
    inputs.forEach(input => {
        const bibNumber = parseInt(input.value);
        const participantId = input.dataset.participantId;
        
        if (!bibNumber || isNaN(bibNumber)) return;
        
        totalAssignments++;
        
        // Check for real conflicts (same BIB, different participants)
        if (bibToParticipant.has(bibNumber)) {
            const existingParticipant = bibToParticipant.get(bibNumber);
            if (existingParticipant !== participantId) {
                conflicts.push(`BIB ${bibNumber} assigned to multiple participants`);
            }
        } else {
            bibToParticipant.set(bibNumber, participantId);
        }
        
        // Check if number is valid (belongs to a series)
        let isValid = false;
        if (Array.isArray(bibSeries)) {
            for (const seriesData of bibSeries) {
                if (seriesData && seriesData.available_numbers && seriesData.available_numbers.includes(bibNumber)) {
                    isValid = true;
                    break;
                }
            }
        }
        
        if (!isValid) {
            invalidNumbers.push(bibNumber);
        }
    });
    
    let message = 'Validation Results:\\n';
    message += `✓ Total assignments: ${totalAssignments}\\n`;
    message += `✓ Unique BIBs: ${bibToParticipant.size}\\n`;
    
    if (conflicts.length > 0) {
        message += `⚠ Real conflicts: ${conflicts.length}\\n`;
    }
    
    if (invalidNumbers.length > 0) {
        message += `❌ Invalid numbers: ${[...new Set(invalidNumbers)].join(', ')}\\n`;
    }
    
    if (conflicts.length === 0 && invalidNumbers.length === 0) {
        message += '✅ All assignments are valid!';
        showAlert(message, 'success');
    } else {
        showAlert(message, 'warning');
    }
    
    updateAssignmentStats();
}

// Show series details
function showSeriesDetails(seriesId) {
    if (!Array.isArray(bibSeries) || bibSeries.length === 0) {
        showAlert('No series data available', 'warning');
        return;
    }
    
    const seriesData = bibSeries.find(s => s && s.series && s.series.id == seriesId);
    if (!seriesData) {
        showAlert('Series not found', 'error');
        return;
    }
    
    const series = seriesData.series;
    const totalRange = series.end_number - series.start_number + 1;
    const assignedCount = seriesData.used_numbers ? seriesData.used_numbers.length : 0;
    const availableCount = seriesData.available_numbers ? seriesData.available_numbers.length : 0;
    const usagePercentage = totalRange > 0 ? Math.round((assignedCount / totalRange) * 100) : 0;
    
    // Get missing and additional numbers
    const missingNumbers = series.missing_numbers ? 
        series.missing_numbers.split(',').map(n => parseInt(n.trim())).filter(n => !isNaN(n)) : [];
    const additionalNumbers = series.additional_numbers ? 
        series.additional_numbers.split(',').map(n => parseInt(n.trim())).filter(n => !isNaN(n)) : [];
    
    const modalContent = `
        <div class="row">
            <div class="col-md-6">
                <div class="border-0 shadow-none card border-primary">
                    <div class="border-0 shadow-none card-header" style="background-color: ${series.color}; color: white;">
                        <h6 class="mb-0">
                            <i class="fas fa-tag me-2"></i>${series.name}
                        </h6>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <table class="table table-sm">
                            <tr>
                                <td><strong>Range:</strong></td>
                                <td>${series.start_number} - ${series.end_number}</td>
                            </tr>
                            <tr>
                                <td><strong>Total in Range:</strong></td>
                                <td>${totalRange}</td>
                            </tr>
                            <tr>
                                <td><strong>Available Numbers:</strong></td>
                                <td><span class="badge bg-success">${availableCount}</span></td>
                            </tr>
                            <tr>
                                <td><strong>Assigned Numbers:</strong></td>
                                <td><span class="badge bg-primary">${assignedCount}</span></td>
                            </tr>
                            <tr>
                                <td><strong>Usage:</strong></td>
                                <td>
                                    <div class="progress" style="height: 20px;">
                                        <div class="progress-bar" role="progressbar" 
                                             style="width: ${usagePercentage}%; background-color: ${series.color};" 
                                             aria-valuenow="${usagePercentage}" aria-valuemin="0" aria-valuemax="100">
                                            ${usagePercentage}%
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="border-0 shadow-none card">
                    <div class="border-0 shadow-none card-header">
                        <h6 class="mb-0">Series Configuration</h6>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        ${missingNumbers.length > 0 ? `
                            <div class="mb-3">
                                <h6 class="text-warning">
                                    <i class="fas fa-exclamation-triangle me-1"></i>Missing from Range:
                                </h6>
                                <div class="d-flex flex-wrap gap-1">
                                    ${missingNumbers.map(num => 
                                        `<span class="badge bg-warning text-dark">${num}</span>`
                                    ).join('')}
                                </div>
                            </div>
                        ` : ''}
                        
                        ${additionalNumbers.length > 0 ? `
                            <div class="mb-3">
                                <h6 class="text-info">
                                    <i class="fas fa-plus-circle me-1"></i>Additional Numbers:
                                </h6>
                                <div class="d-flex flex-wrap gap-1">
                                    ${additionalNumbers.map(num => 
                                        `<span class="badge bg-info">${num}</span>`
                                    ).join('')}
                                </div>
                            </div>
                        ` : ''}
                        
                        <div class="d-grid gap-2">
                            <button class="btn btn-outline-primary btn-sm" onclick="showAvailableNumbers('${seriesId}')">
                                <i class="fas fa-list me-1"></i>View Available Numbers
                            </button>
                            <button class="btn btn-outline-success btn-sm" onclick="exportSeriesInfo('${seriesId}')">
                                <i class="fas fa-download me-1"></i>Export Series Info
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    document.getElementById('seriesDetailsContent').innerHTML = modalContent;
    document.getElementById('seriesDetailsModalLabel').textContent = `Series Details - ${series.name}`;
    
    const modal = new bootstrap.Modal(document.getElementById('seriesDetailsModal'));
    modal.show();
}

// Show available numbers
function showAvailableNumbers(seriesId) {
    if (!Array.isArray(bibSeries) || bibSeries.length === 0) {
        showAlert('No series data available', 'warning');
        return;
    }
    
    const seriesData = bibSeries.find(s => s && s.series && s.series.id == seriesId);
    if (!seriesData || !seriesData.available_numbers) {
        showAlert('Series not found or no available numbers', 'error');
        return;
    }
    
    const series = seriesData.series;
    const availableNumbers = seriesData.available_numbers.sort((a, b) => a - b);
    const usedNumbers = seriesData.used_numbers ? seriesData.used_numbers.sort((a, b) => a - b) : [];
    
    // Create columns for better display
    const itemsPerColumn = 15;
    const columns = [];
    for (let i = 0; i < availableNumbers.length; i += itemsPerColumn) {
        columns.push(availableNumbers.slice(i, i + itemsPerColumn));
    }
    
    const modalContent = `
        <div class="row">
            <div class="col-md-8">
                <div class="border-0 shadow-none card">
                    <div class="border-0 shadow-none card-header" style="background-color: ${series.color}; color: white;">
                        <h6 class="mb-0">
                            <i class="fas fa-list me-2"></i>Available Numbers - ${series.name}
                            <span class="badge bg-light text-dark ms-2">${availableNumbers.length} available</span>
                        </h6>
                        <small>Range: ${series.start_number} - ${series.end_number}</small>
                    </div>
                    <div class="border-0 shadow-none card-body" style="max-height: 400px; overflow-y: auto;">
                        <div class="row">
                            ${columns.map((column, index) => `
                                <div class="col-md-${Math.min(12, Math.ceil(12 / columns.length))} mb-3">
                                    <div class="d-flex flex-wrap gap-1">
                                        ${column.map(num => `
                                            <span class="badge text-white" style="background-color: ${series.color}; font-size: 12px; margin: 1px;">
                                                ${num}
                                            </span>
                                        `).join('')}
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="border-0 shadow-none card border-info">
                    <div class="border-0 shadow-none card-header bg-light">
                        <h6 class="mb-0">Statistics</h6>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <table class="table table-sm">
                            <tr>
                                <td><strong>Total Range:</strong></td>
                                <td>${series.end_number - series.start_number + 1}</td>
                            </tr>
                            <tr>
                                <td><strong>Available:</strong></td>
                                <td><span class="badge bg-success">${availableNumbers.length}</span></td>
                            </tr>
                            <tr>
                                <td><strong>Assigned:</strong></td>
                                <td><span class="badge bg-primary">${usedNumbers.length}</span></td>
                            </tr>
                        </table>
                        
                        ${usedNumbers.length > 0 ? `
                            <div class="mt-3">
                                <h6 class="text-primary">Assigned Numbers:</h6>
                                <div style="max-height: 150px; overflow-y: auto;">
                                    <div class="d-flex flex-wrap gap-1">
                                        ${usedNumbers.map(num => `
                                            <span class="badge bg-primary" style="font-size: 11px; margin: 1px;">
                                                ${num}
                                            </span>
                                        `).join('')}
                                    </div>
                                </div>
                            </div>
                        ` : ''}
                        
                        <div class="mt-3 d-grid gap-2">
                            <button class="btn btn-outline-primary btn-sm" onclick="copyAvailableNumbers('${seriesId}')">
                                <i class="fas fa-copy me-1"></i>Copy Numbers
                            </button>
                            <button class="btn btn-outline-success btn-sm" onclick="exportAvailableCSV('${seriesId}')">
                                <i class="fas fa-file-csv me-1"></i>Export CSV
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    document.getElementById('availableNumbersContent').innerHTML = modalContent;
    document.getElementById('availableNumbersModalLabel').textContent = `Available Numbers - ${series.name}`;
    
    const modal = new bootstrap.Modal(document.getElementById('availableNumbersModal'));
    modal.show();
}

// Update assignment statistics
function updateAssignmentStats() {
    const inputs = document.querySelectorAll('.bib-input');
    let assigned = 0;
    let unassigned = 0;
    let conflicts = 0;
    
    const bibToParticipant = new Map(); // Track which participant has which BIB
    
    inputs.forEach(input => {
        const bibNumber = parseInt(input.value);
        const participantId = input.dataset.participantId;
        
        if (bibNumber && !isNaN(bibNumber)) {
            // Check if this BIB is already assigned to a different participant
            if (bibToParticipant.has(bibNumber)) {
                const existingParticipant = bibToParticipant.get(bibNumber);
                if (existingParticipant !== participantId) {
                    conflicts++; // Real conflict: same BIB, different participants
                }
            } else {
                bibToParticipant.set(bibNumber, participantId);
                assigned++;
            }
        } else {
            unassigned++;
        }
    });
    
    const assignedEl = document.getElementById('assignedCount');
    const unassignedEl = document.getElementById('unassignedCount');
    const conflictEl = document.getElementById('conflictCount');
    
    if (assignedEl) assignedEl.textContent = assigned;
    if (unassignedEl) unassignedEl.textContent = unassigned;
    if (conflictEl) conflictEl.textContent = conflicts;
}

// Show alert message
function showAlert(message, type = 'info') {
    // Create alert element
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 1050; max-width: 400px;';
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(alertDiv);
    
    // Auto remove after 5 seconds
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.remove();
        }
    }, 5000);
}

// Form submission validation
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('bibAssignForm');
    if (form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const inputs = document.querySelectorAll('.bib-input');
            const bibToParticipant = new Map();
            let hasConflicts = false;
            
            inputs.forEach(input => {
                const bibNumber = parseInt(input.value);
                const participantId = input.dataset.participantId;
                
                if (bibNumber && !isNaN(bibNumber)) {
                    // Check if this BIB is already assigned to a different participant
                    if (bibToParticipant.has(bibNumber)) {
                        const existingParticipant = bibToParticipant.get(bibNumber);
                        if (existingParticipant !== participantId) {
                            hasConflicts = true;
                        }
                    } else {
                        bibToParticipant.set(bibNumber, participantId);
                    }
                }
            });
            
            if (hasConflicts) {
                showAlert('Please resolve BIB number conflicts before saving (same BIB assigned to different participants)', 'danger');
                return;
            }
            
            // If no conflicts, submit the form
            this.submit();
        });
    }
    
    // Initialize sorting functionality with a small delay to ensure DOM is ready
    setTimeout(() => {
        initializeSorting();
    }, 100);
    
    updateAssignmentStats();
});

// Debug function to test sorting from console
function testSort() {
    console.log('Testing sort...');
    sortTable('current-bib');
}

// Make all functions globally available
window.showSeriesDetails = showSeriesDetails;
window.showAvailableNumbers = showAvailableNumbers;
window.autoAssignBIBs = autoAssignBIBs;
window.clearAllBIBs = clearAllBIBs;
window.validateBIBs = validateBIBs;
window.assignNextAvailable = assignNextAvailable;
window.updateBIBPreview = updateBIBPreview;
window.generatePrintReport = generatePrintReport;
window.showDetailedReport = showDetailedReport;
window.exportSeriesInfo = exportSeriesInfo;
window.copyAvailableNumbers = copyAvailableNumbers;
window.exportAvailableCSV = exportAvailableCSV;
window.printAvailableNumbers = printAvailableNumbers;
window.createNewSeries = createNewSeries;
window.editSeries = editSeries;
window.manageAllSeries = manageAllSeries;
window.setupSeriesPreview = setupSeriesPreview;
window.updateSeriesPreview = updateSeriesPreview;
window.saveSeries = saveSeries;
window.showHelpModal = showHelpModal;
window.loadManualContent = loadManualContent;
window.convertMarkdownToHTML = convertMarkdownToHTML;
window.printManual = printManual;
window.downloadManual = downloadManual;
window.printModalContent = printModalContent;

// Show detailed BIB report in modal
function showDetailedReport() {
    if (!Array.isArray(bibSeries) || bibSeries.length === 0) {
        showAlert('No BIB series available for report generation', 'warning');
        return;
    }
    
    // Collect current assignments
    const assignments = [];
    const inputs = document.querySelectorAll('.bib-input');
    
    inputs.forEach(input => {
        const bibNumber = parseInt(input.value);
        if (bibNumber && !isNaN(bibNumber)) {
            const row = input.closest('tr');
            const participantName = row.querySelector('.fw-medium').textContent.trim();
            
            // Find series for this BIB
            let seriesInfo = null;
            for (const seriesData of bibSeries) {
                if (seriesData && seriesData.available_numbers && seriesData.available_numbers.includes(bibNumber)) {
                    seriesInfo = seriesData.series;
                    break;
                }
            }
            
            assignments.push({
                bibNumber: bibNumber,
                participantName: participantName,
                series: seriesInfo
            });
        }
    });
    
    // Sort assignments by BIB number
    assignments.sort((a, b) => a.bibNumber - b.bibNumber);
    
    // Generate content for each tab
    generateAssignmentsContent(assignments);
    generateFreeNumbersContent(assignments);
    generateCombinedContent(assignments);
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('detailedReportModal'));
    modal.show();
}

// Generate assignments content
function generateAssignmentsContent(assignments) {
    const content = document.getElementById('assignmentsContent');
    
    // Group assignments by series
    const assignmentsBySeries = {};
    assignments.forEach(assignment => {
        const seriesId = assignment.series ? assignment.series.id : 'unknown';
        const seriesName = assignment.series ? assignment.series.name : 'Unknown Series';
        const seriesColor = assignment.series ? assignment.series.color : '#6c757d';
        
        if (!assignmentsBySeries[seriesId]) {
            assignmentsBySeries[seriesId] = {
                name: seriesName,
                color: seriesColor,
                assignments: []
            };
        }
        assignmentsBySeries[seriesId].assignments.push(assignment);
    });
    
    let html = '<h5 class="mb-3">BIB Assignments by Series</h5>';
    
    Object.values(assignmentsBySeries).forEach(seriesGroup => {
        html += `
            <div class="border-0 shadow-none card mb-3">
                <div class="border-0 shadow-none card-header" style="background-color: ${seriesGroup.color}; color: white;">
                    <h6 class="mb-0">
                        <i class="fas fa-tag me-2"></i>${seriesGroup.name}
                        <span class="badge bg-light text-dark ms-2">${seriesGroup.assignments.length} assigned</span>
                    </h6>
                </div>
                <div class="border-0 shadow-none card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-sm mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>BIB #</th>
                                    <th>Participant</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${seriesGroup.assignments.map(assignment => `
                                    <tr>
                                        <td>
                                            <span class="badge text-white" style="background-color: ${seriesGroup.color};">
                                                ${assignment.bibNumber}
                                            </span>
                                        </td>
                                        <td>${assignment.participantName}</td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        `;
    });
    
    content.innerHTML = html;
}

// Generate free numbers content
function generateFreeNumbersContent(assignments) {
    const content = document.getElementById('freeNumbersContent');
    const assignedNumbers = new Set(assignments.map(a => a.bibNumber));
    
    let html = '<h5 class="mb-3">Free BIB Numbers by Series</h5>';
    
    bibSeries.forEach(seriesData => {
        if (seriesData && seriesData.series) {
            const series = seriesData.series;
            const freeNumbers = seriesData.available_numbers.filter(num => !assignedNumbers.has(num));
            freeNumbers.sort((a, b) => a - b); // Sort numerically
            
            // Get missing and additional numbers info
            const rangeNumbers = [];
            for (let i = series.start_number; i <= series.end_number; i++) {
                rangeNumbers.push(i);
            }
            
            const missingNumbers = series.missing_numbers ? 
                series.missing_numbers.split(',').map(n => parseInt(n.trim())).filter(n => !isNaN(n)) : [];
            const additionalNumbers = series.additional_numbers ? 
                series.additional_numbers.split(',').map(n => parseInt(n.trim())).filter(n => !isNaN(n)) : [];
            
            html += `
                <div class="border-0 shadow-none card mb-3">
                    <div class="border-0 shadow-none card-header" style="background-color: ${series.color}; color: white;">
                        <div class="d-flex justify-content-between align-items-center">
                            <h6 class="mb-0">
                                <i class="fas fa-tag me-2"></i>${series.name}
                                <span class="badge bg-light text-dark ms-2">${freeNumbers.length} free</span>
                            </h6>
                            <button class="btn btn-sm btn-light" onclick="copyTableToClipboard('free-table-${series.id}')">
                                <i class="fas fa-copy me-1"></i>Copy Table
                            </button>
                        </div>
                        <small>Range: ${series.start_number} - ${series.end_number}</small>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <!-- Free Numbers Table for Manual Assignment -->
                        <div class="row">
                            <div class="col-md-8">
                                <h6 class="text-success">Available BIB Numbers - Manual Assignment Table:</h6>
                                <div class="table-responsive" style="max-height: 400px;">
                                    <table class="table table-striped table-sm" id="free-table-${series.id}">
                                        <thead class="table-success sticky-top">
                                            <tr>
                                                <th style="width: 100px;">BIB Number</th>
                                                <th>Participant Name</th>
                                                <th>Notes</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            ${freeNumbers.map(num => `
                                                <tr>
                                                    <td>
                                                        <span class="badge text-white fw-bold" style="background-color: ${series.color}; font-size: 14px;">
                                                            ${num}
                                                        </span>
                                                    </td>
                                                    <td style="border-bottom: 1px dotted #ccc; height: 40px;">&nbsp;</td>
                                                    <td style="border-bottom: 1px dotted #ccc; height: 40px;">&nbsp;</td>
                                                </tr>
                                            `).join('')}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <h6 class="text-info">Series Information:</h6>
                                <div class="border-0 shadow-none card border-info">
                                    <div class="border-0 shadow-none card-body">
                                        <p><strong>Total in Range:</strong> ${series.end_number - series.start_number + 1}</p>
                                        <p><strong>Available Numbers:</strong> ${seriesData.available_numbers.length}</p>
                                        <p><strong>Free Numbers:</strong> ${freeNumbers.length}</p>
                                        <p><strong>Assigned Numbers:</strong> ${seriesData.used_numbers.length}</p>
                                        
                                        ${missingNumbers.length > 0 ? `
                                            <div class="mt-3">
                                                <h6 class="text-warning">Missing from Range:</h6>
                                                <div class="d-flex flex-wrap gap-1 mb-2">
                                                    ${missingNumbers.map(num => 
                                                        `<span class="badge bg-warning text-dark">${num}</span>`
                                                    ).join('')}
                                                </div>
                                            </div>
                                        ` : ''}
                                        
                                        ${additionalNumbers.length > 0 ? `
                                            <div class="mt-3">
                                                <h6 class="text-info">Additional Numbers:</h6>
                                                <div class="d-flex flex-wrap gap-1">
                                                    ${additionalNumbers.map(num => 
                                                        `<span class="badge bg-info">${num}</span>`
                                                    ).join('')}
                                                </div>
                                            </div>
                                        ` : ''}
                                        
                                        <div class="mt-3">
                                            <button class="btn btn-sm btn-outline-primary w-100" onclick="exportSeriesCSV('${series.id}', '${series.name}', ${JSON.stringify(freeNumbers).replace(/"/g, '&quot;')})">
                                                <i class="fas fa-file-csv me-1"></i>Export to CSV
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }
    });
    
    content.innerHTML = html;
}

// Generate combined content
function generateCombinedContent(assignments) {
    const content = document.getElementById('combinedContent');
    const assignedNumbers = new Set(assignments.map(a => a.bibNumber));
    
    let html = '<h5 class="mb-3">Complete BIB Overview by Series</h5>';
    
    bibSeries.forEach(seriesData => {
        if (seriesData && seriesData.series) {
            const series = seriesData.series;
            const assignedInSeries = assignments.filter(a => a.series && a.series.id === series.id);
            const freeNumbers = seriesData.available_numbers.filter(num => !assignedNumbers.has(num));
            
            // Get missing and additional numbers info
            const missingNumbers = series.missing_numbers ? 
                series.missing_numbers.split(',').map(n => parseInt(n.trim())).filter(n => !isNaN(n)) : [];
            const additionalNumbers = series.additional_numbers ? 
                series.additional_numbers.split(',').map(n => parseInt(n.trim())).filter(n => !isNaN(n)) : [];
            
            html += `
                <div class="border-0 shadow-none card mb-4">
                    <div class="border-0 shadow-none card-header" style="background-color: ${series.color}; color: white;">
                        <div class="d-flex justify-content-between align-items-center">
                            <h6 class="mb-0">
                                <i class="fas fa-tag me-2"></i>${series.name}
                            </h6>
                            <div>
                                <span class="badge bg-success me-1">${assignedInSeries.length} Assigned</span>
                                <span class="badge bg-secondary">${freeNumbers.length} Free</span>
                            </div>
                        </div>
                        <small>Range: ${series.start_number} - ${series.end_number}</small>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h6 class="text-success">Assigned Numbers:</h6>
                                <div class="table-responsive" style="max-height: 300px;">
                                    <table class="table table-sm">
                                        <thead class="table-success">
                                            <tr>
                                                <th>BIB #</th>
                                                <th>Participant</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            ${assignedInSeries.map(assignment => `
                                                <tr>
                                                    <td>
                                                        <span class="badge text-white" style="background-color: ${series.color};">
                                                            ${assignment.bibNumber}
                                                        </span>
                                                    </td>
                                                    <td>${assignment.participantName}</td>
                                                </tr>
                                            `).join('')}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <h6 class="text-secondary">Free Numbers:</h6>
                                <div class="d-flex flex-wrap gap-1 mb-3" style="max-height: 200px; overflow-y: auto;">
                                    ${freeNumbers.map(num => 
                                        `<span class="badge text-white" style="background-color: ${series.color};">${num}</span>`
                                    ).join('')}
                                </div>
                                
                                ${missingNumbers.length > 0 || additionalNumbers.length > 0 ? `
                                    <div class="border-top pt-2 mt-2">
                                        ${missingNumbers.length > 0 ? `
                                            <small class="text-warning fw-bold">Missing from Range:</small>
                                            <div class="d-flex flex-wrap gap-1 mb-2">
                                                ${missingNumbers.map(num => 
                                                    `<span class="badge bg-warning text-dark">${num}</span>`
                                                ).join('')}
                                            </div>
                                        ` : ''}
                                        ${additionalNumbers.length > 0 ? `
                                            <small class="text-info fw-bold">Additional Numbers:</small>
                                            <div class="d-flex flex-wrap gap-1">
                                                ${additionalNumbers.map(num => 
                                                    `<span class="badge bg-info">${num}</span>`
                                                ).join('')}
                                            </div>
                                        ` : ''}
                                    </div>
                                ` : ''}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }
    });
    
    content.innerHTML = html;
}

// Print modal content
function printModalContent() {
    const eventName = document.querySelector('#event_id option:checked').textContent;
    const currentDate = new Date().toLocaleDateString();
    
    // Get active tab content
    const activeTab = document.querySelector('#reportTabs .nav-link.active').textContent.trim();
    const activeContent = document.querySelector('#reportTabContent .tab-pane.active').innerHTML;
    
    const printHTML = `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>BIB Report - ${eventName} - ${activeTab}</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        @media print {
            body { margin: 0; font-size: 12px; }
            .card-header { -webkit-print-color-adjust: exact; color-adjust: exact; }
            .badge { -webkit-print-color-adjust: exact; color-adjust: exact; }
        }
        body { font-family: Arial, sans-serif; margin: 20px; }
        .badge { display: inline-block; padding: 0.25em 0.5em; }
    </style>
</head>
<body>
    <div class="container-fluid">
        <h2>BIB Report - ${activeTab}</h2>
        <p><strong>Event:</strong> ${eventName}</p>
        <p><strong>Generated:</strong> ${currentDate}</p>
        
        ${activeContent}
    </div>
</body>
</html>`;
    
    const printWindow = window.open('', '_blank', 'width=1200,height=800');
    printWindow.document.write(printHTML);
    printWindow.document.close();
    printWindow.print();
}

// Copy table to clipboard
function copyTableToClipboard(tableId) {
    const table = document.getElementById(tableId);
    if (!table) return;
    
    let csvContent = '';
    const rows = table.querySelectorAll('tr');
    
    rows.forEach(row => {
        const cells = row.querySelectorAll('th, td');
        const rowData = Array.from(cells).map(cell => {
            // Clean up the cell content for CSV
            let text = cell.textContent.trim();
            if (text === '\u00A0') text = ''; // Replace non-breaking space
            return `"${text}"`;
        });
        csvContent += rowData.join('\t') + '\n';
    });
    
    navigator.clipboard.writeText(csvContent).then(() => {
        // Show success message
        const originalBtn = event.target.closest('button');
        const originalText = originalBtn.innerHTML;
        originalBtn.innerHTML = '<i class="fas fa-check me-1"></i>Copied!';
        originalBtn.classList.remove('btn-light');
        originalBtn.classList.add('btn-success');
        
        setTimeout(() => {
            originalBtn.innerHTML = originalText;
            originalBtn.classList.remove('btn-success');
            originalBtn.classList.add('btn-light');
        }, 2000);
    }).catch(err => {
        alert('Failed to copy table. Please select and copy manually.');
    });
}

// Export series to CSV
function exportSeriesCSV(seriesId, seriesName, freeNumbers) {
    let csvContent = "BIB Number,Participant Name,Notes\n";
    
    freeNumbers.forEach(num => {
        csvContent += `${num},"",""\n`;
    });
    
    // Create download link
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement("a");
    const url = URL.createObjectURL(blob);
    link.setAttribute("href", url);
    link.setAttribute("download", `free_bibs_${seriesName.replace(/[^a-zA-Z0-9]/g, '_')}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// Export series information
function exportSeriesInfo(seriesId) {
    const seriesData = bibSeries.find(s => s && s.series && s.series.id == seriesId);
    if (!seriesData) return;
    
    const series = seriesData.series;
    const totalRange = series.end_number - series.start_number + 1;
    const assignedCount = seriesData.used_numbers ? seriesData.used_numbers.length : 0;
    const availableCount = seriesData.available_numbers ? seriesData.available_numbers.length : 0;
    
    let csvContent = "Series Information\n";
    csvContent += `Series Name,${series.name}\n`;
    csvContent += `Range,${series.start_number} - ${series.end_number}\n`;
    csvContent += `Total Numbers in Range,${totalRange}\n`;
    csvContent += `Available Numbers,${availableCount}\n`;
    csvContent += `Assigned Numbers,${assignedCount}\n`;
    csvContent += `Usage Percentage,${Math.round((assignedCount / totalRange) * 100)}%\n`;
    csvContent += `Color,${series.color}\n\n`;
    
    if (series.missing_numbers) {
        csvContent += "Missing Numbers\n";
        csvContent += `${series.missing_numbers}\n\n`;
    }
    
    if (series.additional_numbers) {
        csvContent += "Additional Numbers\n";
        csvContent += `${series.additional_numbers}\n\n`;
    }
    
    if (seriesData.available_numbers && seriesData.available_numbers.length > 0) {
        csvContent += "Available Numbers\n";
        csvContent += `${seriesData.available_numbers.join(',')}\n\n`;
    }
    
    if (seriesData.used_numbers && seriesData.used_numbers.length > 0) {
        csvContent += "Assigned Numbers\n";
        csvContent += `${seriesData.used_numbers.join(',')}\n`;
    }
    
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement("a");
    const url = URL.createObjectURL(blob);
    link.setAttribute("href", url);
    link.setAttribute("download", `series_info_${series.name.replace(/[^a-zA-Z0-9]/g, '_')}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// Copy available numbers to clipboard
function copyAvailableNumbers(seriesId) {
    const seriesData = bibSeries.find(s => s && s.series && s.series.id == seriesId);
    if (!seriesData || !seriesData.available_numbers) return;
    
    const numbersText = seriesData.available_numbers.sort((a, b) => a - b).join(', ');
    
    navigator.clipboard.writeText(numbersText).then(() => {
        showAlert('Available numbers copied to clipboard!', 'success');
    }).catch(err => {
        showAlert('Failed to copy numbers. Please select and copy manually.', 'error');
    });
}

// Export available numbers as CSV
function exportAvailableCSV(seriesId) {
    const seriesData = bibSeries.find(s => s && s.series && s.series.id == seriesId);
    if (!seriesData || !seriesData.available_numbers) return;
    
    const series = seriesData.series;
    const availableNumbers = seriesData.available_numbers.sort((a, b) => a - b);
    
    let csvContent = "Available BIB Numbers\n";
    csvContent += `Series: ${series.name}\n`;
    csvContent += `Range: ${series.start_number} - ${series.end_number}\n`;
    csvContent += `Total Available: ${availableNumbers.length}\n\n`;
    csvContent += "BIB Number,Participant Name,Notes\n";
    
    availableNumbers.forEach(num => {
        csvContent += `${num},"",""\n`;
    });
    
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement("a");
    const url = URL.createObjectURL(blob);
    link.setAttribute("href", url);
    link.setAttribute("download", `available_bibs_${series.name.replace(/[^a-zA-Z0-9]/g, '_')}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// Print available numbers
function printAvailableNumbers() {
    const modalContent = document.getElementById('availableNumbersContent');
    if (!modalContent) return;
    
    const seriesName = document.getElementById('availableNumbersModalLabel').textContent;
    
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>${seriesName}</title>
            <style>
                body { font-family: Arial, sans-serif; padding: 20px; }
                .card { border: 1px solid #ddd; margin-bottom: 15px; }
                .card-header { background-color: #f8f9fa; padding: 10px; font-weight: bold; }
                .card-body { padding: 10px; }
                .badge { padding: 2px 8px; border-radius: 3px; margin: 1px; }
                .text-white { color: white !important; }
                .table { width: 100%; border-collapse: collapse; }
                .table th, .table td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                @media print {
                    .btn, button { display: none !important; }
                }
            </style>
        </head>
        <body>
            <h2>${seriesName}</h2>
            <p>Generated on: ${new Date().toLocaleString()}</p>
            ${modalContent.innerHTML}
        </body>
        </html>
    `);
    printWindow.document.close();
    printWindow.print();
}

// Create new series
function createNewSeries() {
    // Reset form
    document.getElementById('seriesForm').reset();
    document.getElementById('seriesId').value = '';
    document.getElementById('seriesColor').value = '#007bff';
    document.getElementById('seriesColorText').value = '#007bff';
    
    // Update modal title and button
    document.getElementById('seriesManagementModalLabel').textContent = 'Create New BIB Series';
    document.getElementById('saveButtonText').textContent = 'Create Series';
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('seriesManagementModal'));
    modal.show();
    
    // Setup preview update
    setupSeriesPreview();
}

// Edit existing series
function editSeries(seriesId) {
    const seriesData = bibSeries.find(s => s && s.series && s.series.id == seriesId);
    if (!seriesData) {
        showAlert('Series not found', 'error');
        return;
    }
    
    const series = seriesData.series;
    
    // Populate form
    document.getElementById('seriesId').value = series.id;
    document.getElementById('seriesName').value = series.name;
    document.getElementById('seriesColor').value = series.color;
    document.getElementById('seriesColorText').value = series.color;
    document.getElementById('startNumber').value = series.start_number;
    document.getElementById('endNumber').value = series.end_number;
    document.getElementById('missingNumbers').value = series.missing_numbers || '';
    document.getElementById('additionalNumbers').value = series.additional_numbers || '';
    document.getElementById('seriesDescription').value = series.description || '';
    
    // Update modal title and button
    document.getElementById('seriesManagementModalLabel').textContent = `Edit Series - ${series.name}`;
    document.getElementById('saveButtonText').textContent = 'Update Series';
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('seriesManagementModal'));
    modal.show();
    
    // Setup preview update
    setupSeriesPreview();
}

// Manage all series (redirect to series manager)
function manageAllSeries() {
    window.location.href = `bib_assign.php?event_id=${document.getElementById('event_id').value}`;
}

// Setup series preview functionality
function setupSeriesPreview() {
    const inputs = ['seriesName', 'seriesColor', 'startNumber', 'endNumber', 'missingNumbers', 'additionalNumbers'];
    
    inputs.forEach(inputId => {
        const input = document.getElementById(inputId);
        if (input) {
            input.addEventListener('input', updateSeriesPreview);
        }
    });
    
    // Color picker sync
    document.getElementById('seriesColor').addEventListener('input', function() {
        document.getElementById('seriesColorText').value = this.value;
        updateSeriesPreview();
    });
    
    document.getElementById('seriesColorText').addEventListener('input', function() {
        if (/^#[0-9A-F]{6}$/i.test(this.value)) {
            document.getElementById('seriesColor').value = this.value;
            updateSeriesPreview();
        }
    });
    
    updateSeriesPreview();
}

// Update series preview
function updateSeriesPreview() {
    const name = document.getElementById('seriesName').value || 'Unnamed Series';
    const color = document.getElementById('seriesColor').value || '#007bff';
    const start = parseInt(document.getElementById('startNumber').value) || 0;
    const end = parseInt(document.getElementById('endNumber').value) || 0;
    const missing = document.getElementById('missingNumbers').value;
    const additional = document.getElementById('additionalNumbers').value;
    
    let preview = `<span class="badge text-white me-2" style="background-color: ${color};">${name}</span>`;
    
    if (start > 0 && end > 0) {
        const total = end - start + 1;
        preview += `Range: ${start}-${end} (${total} numbers)`;
        
        if (missing) {
            const missingCount = missing.split(',').filter(n => n.trim()).length;
            preview += `, Missing: ${missingCount}`;
        }
        
        if (additional) {
            const additionalCount = additional.split(',').filter(n => n.trim()).length;
            preview += `, Additional: ${additionalCount}`;
        }
    } else {
        preview += 'Enter start and end numbers';
    }
    
    document.getElementById('seriesPreview').innerHTML = preview;
}

// Save series (create or update)
function saveSeries() {
    const form = document.getElementById('seriesForm');
    const formData = new FormData(form);
    
    // Validate form
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    // Additional validation
    const start = parseInt(formData.get('start_number'));
    const end = parseInt(formData.get('end_number'));
    
    if (start >= end) {
        showAlert('End number must be greater than start number', 'error');
        return;
    }
    
    // Show loading state
    const saveBtn = document.querySelector('#seriesManagementModal .btn-primary');
    const originalText = saveBtn.innerHTML;
    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Saving...';
    saveBtn.disabled = true;
    
    // Prepare request
    const isEdit = formData.get('series_id');
    const action = isEdit ? 'update_series' : 'create_series';
    formData.append('action', action);
    
    // Submit via fetch
    fetch('series_management_api.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert(data.message || (isEdit ? 'Series updated successfully!' : 'Series created successfully!'), 'success');
            
            // Close modal
            const modal = bootstrap.Modal.getInstance(document.getElementById('seriesManagementModal'));
            modal.hide();
            
            // Reload page to show changes
            setTimeout(() => {
                window.location.reload();
            }, 1000);
        } else {
            showAlert(data.message || 'Failed to save series', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('Network error occurred', 'error');
    })
    .finally(() => {
        // Reset button state
        saveBtn.innerHTML = originalText;
        saveBtn.disabled = false;
    });
}

// Show help modal and load manual content
function showHelpModal() {
    const modal = new bootstrap.Modal(document.getElementById('helpModal'));
    modal.show();
    
    // Load manual content if not already loaded
    if (document.getElementById('helpContent').innerHTML.includes('Loading manual content')) {
        loadManualContent();
    }
}

// Load manual content from markdown file
function loadManualContent() {
    fetch('BIB_Distribution_Manager_Manual.md')
        .then(response => {
            if (!response.ok) {
                throw new Error('Failed to load manual');
            }
            return response.text();
        })
        .then(markdownContent => {
            // Convert markdown to HTML (basic conversion)
            const htmlContent = convertMarkdownToHTML(markdownContent);
            document.getElementById('helpContent').innerHTML = htmlContent;
        })
        .catch(error => {
            console.error('Error loading manual:', error);
            document.getElementById('helpContent').innerHTML = `
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>Manual Loading Error</strong><br>
                    Could not load the user manual. Please contact your system administrator.
                </div>
            `;
        });
}

// Basic markdown to HTML converter
function convertMarkdownToHTML(markdown) {
    let html = markdown;
    
    // Headers
    html = html.replace(/^### (.*$)/gim, '<h3 class="text-primary mt-4 mb-3">$1</h3>');
    html = html.replace(/^## (.*$)/gim, '<h2 class="text-primary border-bottom pb-2 mt-4 mb-3">$1</h2>');
    html = html.replace(/^# (.*$)/gim, '<h1 class="text-primary border-bottom pb-2 mt-4 mb-3">$1</h1>');
    
    // Bold text
    html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
    
    // Italic text
    html = html.replace(/\*(.*?)\*/g, '<em>$1</em>');
    
    // Code blocks with language
    html = html.replace(/```(\w+)?\n([\s\S]*?)```/g, '<pre class="bg-light p-3 rounded"><code>$2</code></pre>');
    
    // Inline code
    html = html.replace(/`([^`]+)`/g, '<code class="bg-light px-1 rounded">$1</code>');
    
    // Links
    html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" class="text-decoration-none">$1</a>');
    
    // Lists
    html = html.replace(/^\* (.*$)/gim, '<li>$1</li>');
    html = html.replace(/^\d+\. (.*$)/gim, '<li>$1</li>');
    
    // Wrap consecutive list items in ul/ol
    html = html.replace(/(<li>.*<\/li>\s*)+/g, function(match) {
        return '<ul class="list-group list-group-flush mb-3">' + 
               match.replace(/<li>/g, '<li class="list-group-item border-0 px-0">') + 
               '</ul>';
    });
    
    // Blockquotes
    html = html.replace(/^> (.*$)/gim, '<blockquote class="blockquote border-start border-primary border-4 ps-3 py-2 bg-light">$1</blockquote>');
    
    // Horizontal rules
    html = html.replace(/^---$/gim, '<hr class="my-4">');
    
    // Tables (basic support)
    html = html.replace(/\|(.+)\|/g, function(match, content) {
        const cells = content.split('|').map(cell => cell.trim());
        if (cells.some(cell => cell.includes('---'))) {
            return ''; // Skip separator rows
        }
        const cellsHtml = cells.map(cell => `<td class="px-3 py-2">${cell}</td>`).join('');
        return `<tr>${cellsHtml}</tr>`;
    });
    
    // Wrap table rows
    html = html.replace(/(<tr>.*<\/tr>\s*)+/g, function(match) {
        return '<div class="table-responsive"><table class="table table-striped table-hover">' + match + '</table></div>';
    });
    
    // Badges/buttons styling
    html = html.replace(/✅/g, '<span class="badge bg-success me-1">✅</span>');
    html = html.replace(/❌/g, '<span class="badge bg-danger me-1">❌</span>');
    html = html.replace(/⚠️/g, '<span class="badge bg-warning me-1">⚠️</span>');
    html = html.replace(/🎯|🚀|🏷️|👥|📊|📋|🔄|📱|👁️|📋|✏️|⚙️|↗️|🔧|📖|📋|🎯|🚀|🏷️|👥|📊|⚙️|🔧|💻|📖/g, function(emoji) {
        return `<span class="me-2">${emoji}</span>`;
    });
    
    // Paragraphs
    html = html.replace(/\n\n/g, '</p><p class="mb-3">');
    html = '<p class="mb-3">' + html + '</p>';
    
    // Clean up empty paragraphs
    html = html.replace(/<p class="mb-3"><\/p>/g, '');
    html = html.replace(/<p class="mb-3">\s*<h/g, '<h');
    html = html.replace(/<\/h(\d)>\s*<\/p>/g, '</h$1>');
    
    // Add Bootstrap classes to alerts
    html = html.replace(/> ⚠️ \*\*Note\*\*:/g, '<div class="alert alert-warning"><i class="fas fa-exclamation-triangle me-2"></i><strong>Note</strong>:');
    html = html.replace(/> 📝 \*\*Tip\*\*:/g, '<div class="alert alert-info"><i class="fas fa-lightbulb me-2"></i><strong>Tip</strong>:');
    
    return html;
}

// Print manual content
function printManual() {
    const manualContent = document.getElementById('helpContent').innerHTML;
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>BIB Distribution Manager - User Manual</title>
            <style>
                body { font-family: Arial, sans-serif; padding: 20px; line-height: 1.6; }
                h1, h2, h3 { color: #0066cc; page-break-after: avoid; }
                h1 { border-bottom: 2px solid #0066cc; padding-bottom: 10px; }
                h2 { border-bottom: 1px solid #0066cc; padding-bottom: 5px; margin-top: 30px; }
                h3 { margin-top: 25px; }
                .table { border-collapse: collapse; width: 100%; margin: 15px 0; }
                .table th, .table td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                .table-striped tr:nth-child(even) { background-color: #f2f2f2; }
                code { background-color: #f4f4f4; padding: 2px 4px; border-radius: 3px; }
                pre { background-color: #f4f4f4; padding: 15px; border-radius: 5px; overflow-x: auto; }
                .alert { padding: 10px; margin: 10px 0; border-radius: 5px; }
                .alert-warning { background-color: #fff3cd; border: 1px solid #ffeaa7; }
                .alert-info { background-color: #d1ecf1; border: 1px solid #bee5eb; }
                .badge { padding: 2px 6px; border-radius: 3px; font-size: 0.8em; }
                .bg-success { background-color: #28a745; color: white; }
                .bg-danger { background-color: #dc3545; color: white; }
                .bg-warning { background-color: #ffc107; color: black; }
                @media print {
                    body { margin: 0; }
                    h1, h2, h3 { page-break-after: avoid; }
                    .table { page-break-inside: avoid; }
                }
            </style>
        </head>
        <body>
            ${manualContent}
        </body>
        </html>
    `);
    printWindow.document.close();
    printWindow.print();
}

// Download manual as PDF (simplified - just opens print dialog)
function downloadManual() {
    // For now, just print - browser can save as PDF
    printManual();
    showAlert('Use your browser\'s "Save as PDF" option in the print dialog to download the manual.', 'info');
}

// Generate ready-to-print BIB report
function generatePrintReport() {
    if (!Array.isArray(bibSeries) || bibSeries.length === 0) {
        showAlert('No BIB series available for report generation', 'warning');
        return;
    }
    
    // Collect current assignments
    const assignments = [];
    const inputs = document.querySelectorAll('.bib-input');
    
    inputs.forEach(input => {
        const bibNumber = parseInt(input.value);
        if (bibNumber && !isNaN(bibNumber)) {
            const row = input.closest('tr');
            const participantName = row.querySelector('.fw-medium').textContent.trim();
            assignments.push({
                bibNumber: bibNumber,
                participantName: participantName
            });
        }
    });
    
    // Sort assignments by BIB number
    assignments.sort((a, b) => a.bibNumber - b.bibNumber);
    
    // Collect free numbers
    const assignedNumbers = new Set(assignments.map(a => a.bibNumber));
    const freeNumbers = [];
    
    bibSeries.forEach(seriesData => {
        if (seriesData && seriesData.available_numbers) {
            seriesData.available_numbers.forEach(num => {
                if (!assignedNumbers.has(num)) {
                    freeNumbers.push(num);
                }
            });
        }
    });
    
    freeNumbers.sort((a, b) => a - b);
    
    // Generate simple HTML report
    const eventName = document.querySelector('#event_id option:checked').textContent;
    const reportHTML = `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>BIB Report - ${eventName}</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        table { border-collapse: collapse; width: 100%; margin-bottom: 30px; }
        th, td { border: 1px solid #000; padding: 8px; text-align: left; }
        th { background-color: #f0f0f0; font-weight: bold; }
        h2 { color: #333; }
        .free-numbers { display: inline-block; margin: 2px; padding: 4px 8px; border: 1px solid #000; }
        @media print { body { margin: 0; } }
    </style>
</head>
<body>
    <h2>BIB Assignment Report</h2>
    <p><strong>Event:</strong> ${eventName}</p>
    <p><strong>Generated:</strong> ${new Date().toLocaleDateString()}</p>
    
    <h3>Assigned BIB Numbers (${assignments.length})</h3>
    <table>
        <thead>
            <tr>
                <th>BIB Number</th>
                <th>Participant Name</th>
            </tr>
        </thead>
        <tbody>
            ${assignments.map(a => `
                <tr>
                    <td>${a.bibNumber}</td>
                    <td>${a.participantName}</td>
                </tr>
            `).join('')}
        </tbody>
    </table>
    
    <h3>Free BIB Numbers (${freeNumbers.length})</h3>
    <div>
        ${freeNumbers.map(num => `<span class="free-numbers">${num}</span>`).join('')}
    </div>
    
   
</body>
</html>`;
    
    // Open in new window for printing
    const printWindow = window.open('', '_blank', 'width=800,height=600');
    printWindow.document.write(reportHTML);
    printWindow.document.close();
}
</script>

    <?php include '../admin/footer.php'; ?>
</body>
</html>