import re
import sys

def patch():
    with open('app/modules/sag/templates/detail.html', 'r', encoding='utf-8') as f:
        text = f.read()

    css_start = text.find('.time-v1-user-section {')
    css_end = text.find('</style>', css_start)

    css_new = """
        .time-v1-calendar-container {
            background: var(--bg-surface, #fff);
            border: 1px solid var(--border-color, #e0e0e0);
            border-radius: 12px;
            margin-bottom: 2rem;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0,0,0,0.03);
        }
        .time-v1-calendar-header {
            background: var(--bg-element, #f8f9fa);
            border-bottom: 1px solid var(--border-color, #e0e0e0);
            padding: 12px 20px;
            font-weight: 600;
            font-size: 1rem;
            display: flex;
            align-items: center;
            gap: 8px;
            color: var(--text-color);
        }
        .time-v1-calendar-grid {
            display: flex;
            position: relative;
            overflow-x: auto;
        }
        .time-v1-time-axis {
            width: 60px;
            flex-shrink: 0;
            border-right: 1px solid var(--border-color, #f0f0f0);
            position: relative;
            background: var(--bg-element, #fafafa);
            padding-top: 40px; 
        }
        .time-v1-hour-marker {
            position: absolute;
            width: 100%;
            text-align: center;
            font-size: 0.75rem;
            color: var(--text-secondary);
            transform: translateY(-50%);
        }
        .time-v1-tech-col {
            flex: 1;
            min-width: 250px;
            border-right: 1px solid var(--border-color, #f0f0f0);
            position: relative;
        }
        .time-v1-tech-col:last-child {
            border-right: none;
        }
        .time-v1-tech-header {
            text-align: center;
            padding: 8px;
            height: 40px;
            font-weight: 600;
            font-size: 0.85rem;
            border-bottom: 1px solid var(--border-color, #e0e0e0);
            background: var(--bg-element, #f8f9fa);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            position: sticky;
            top: 0;
            z-index: 50;
            color: var(--text-color);
        }
        .time-v1-tech-body {
            position: relative;
            height: 600px; /* 10h * 60Px = 600px */
            background-image: linear-gradient(to bottom, transparent 59px, var(--border-color, #f0f0f0) 60px);
            background-size: 100% 60px; 
        }
        .time-v1-entry-block {
            position: absolute;
            left: 4px;
            right: 4px;
            border-radius: 6px;
            padding: 6px 8px;
            font-size: 0.8rem;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            transition: transform 0.2s, box-shadow 0.2s, z-index 0.2s;
            border-left: 4px solid var(--bs-secondary);
            background: var(--bg-surface, #fff);
            cursor: grab;
            z-index: 10;
        }
        .time-v1-entry-block:active { cursor: grabbing; opacity: 0.9; }
        .time-v1-entry-block:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
            z-index: 20;
        }
        .time-v1-entry-pending { border-left-color: #f59e0b; background: rgba(245, 158, 11, 0.05) !important; }
        .time-v1-entry-godkendt { border-left-color: #2fb344; background: rgba(47, 179, 68, 0.05) !important; }
        .time-v1-entry-kladde { border-left-color: #6c757d; background: rgba(108, 117, 125, 0.05) !important; }

        .time-v1-entry-time {
            font-weight: 600;
            font-size: 0.75rem;
            margin-bottom: 2px;
            color: var(--text-color);
        }
        .time-v1-entry-desc {
            color: var(--text-secondary);
            font-size: 0.75rem;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .time-v1-unplaced-container {
            padding: 12px 20px;
            border-top: 1px solid var(--border-color);
            background: var(--bg-element);
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            align-items: center;
        }
        .time-v1-unplaced-item {
            background: var(--bg-surface);
            border: 1px solid var(--border-color);
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            color: var(--text-color);
        }
"""
    if css_start != -1 and css_end != -1:
        text = text[:css_start] + css_new + text[css_end:]
        print("Replaced CSS.")

    js_start = text.find('function renderTimeV1Timeline(entries) {')
    js_end = text.find('async function loadTimeTrackingTab() {', js_start)

    js_new = """function renderTimeV1Timeline(entries) {
            const timeline = document.getElementById('timeTimelineColumns');
            if (!timeline) return;

            if (!entries || entries.length === 0) {
                timeline.innerHTML = '<div class="text-muted text-center p-4">Ingen tidsregistreringer endnu</div>';
                return;
            }

            const START_HOUR = 7;
            const TOTAL_HOURS = 10; // 07:00 to 17:00
            const HOUR_HEIGHT = 60; // px

            const groupedByDate = {};
            entries.forEach((entry) => {
                let dateKey = 'Ukendt dato';
                if (entry.start_tid) {
                    dateKey = entry.start_tid.split('T')[0];
                } else if (entry.worked_date) {
                    dateKey = entry.worked_date;
                } else if (entry.created_at) {
                    dateKey = entry.created_at.split('T')[0];
                }
                
                // Keep only first 10 chars for proper grouping if it's an ISO timestamp
                if (dateKey.length > 10) dateKey = dateKey.substring(0, 10);
                
                if (!groupedByDate[dateKey]) groupedByDate[dateKey] = [];
                groupedByDate[dateKey].push(entry);
            });

            const sortedDates = Object.keys(groupedByDate).sort((a, b) => new Date(b) - new Date(a));
            let html = '';

            sortedDates.forEach(dateStr => {
                const dayEntries = groupedByDate[dateStr];
                
                let formattedDateLab = dateStr;
                try {
                    const d = new Date(dateStr);
                    if (!isNaN(d.getTime())) {
                        formattedDateLab = d.toLocaleDateString('da-DK', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
                        formattedDateLab = formattedDateLab.charAt(0).toUpperCase() + formattedDateLab.slice(1);
                    }
                } catch(e){}

                const techs = {};
                const unplaced = [];

                dayEntries.forEach(entry => {
                    const tech = entry.bruger_navn || entry.user_name || 'Ukendt';
                    if (!techs[tech]) techs[tech] = [];
                    
                    if (!entry.start_tid || entry.start_tid === null) {
                        unplaced.push(entry);
                    } else {
                        techs[tech].push(entry);
                    }
                });

                const techNames = Object.keys(techs).sort();

                html += `
                <div class="time-v1-calendar-container">
                    <div class="time-v1-calendar-header">
                        <i class="bi bi-calendar3 text-primary"></i> ${formattedDateLab}
                    </div>
                    <div class="time-v1-calendar-grid">
                        <div class="time-v1-time-axis">
                `;

                for (let i = 0; i <= TOTAL_HOURS; i++) {
                    const h = START_HOUR + i;
                    const top = i * HOUR_HEIGHT;
                    html += `<div class="time-v1-hour-marker" style="top: ${top}px">${h.toString().padStart(2, '0')}:00</div>`;
                }

                html += `</div>`;

                techNames.forEach(tech => {
                    html += `
                        <div class="time-v1-tech-col" data-tech="${escapeHtml(tech)}" data-date="${dateStr}">
                            <div class="time-v1-tech-header">
                                <i class="bi bi-person-circle text-secondary"></i> ${escapeHtml(tech)}
                            </div>
                            <div class="time-v1-tech-body">
                    `;

                    techs[tech].forEach(entry => {
                         const desc = escapeHtml(entry.beskrivelse || entry.description || 'Ingen beskrivelse');
                         const status = entry.entry_status || entry.status || 'kladde';
                         let cssClass = 'time-v1-entry-kladde';
                         if (status === 'afventer' || status === 'pending') cssClass = 'time-v1-entry-pending';
                         if (status === 'godkendt' || status === 'billed' || status === 'approved' || entry.fakturerbar_tid_min > 0) cssClass = 'time-v1-entry-godkendt';

                         const startObj = new Date(entry.start_tid);
                         let durationMin = 30; // default length
                         if (entry.faktisk_tid_min) {
                             durationMin = parseInt(entry.faktisk_tid_min);
                         } else if (entry.original_hours || entry.timer) {
                             durationMin = Math.round(parseFloat(entry.original_hours || entry.timer) * 60);
                         }
                         
                         let startH = startObj.getHours();
                         let startM = startObj.getMinutes();

                         if (startH < START_HOUR) {
                             durationMin -= ((START_HOUR * 60) - (startH * 60 + startM));
                             startH = START_HOUR;
                             startM = 0;
                         }

                         let topPx = ((startH - START_HOUR) + (startM / 60)) * HOUR_HEIGHT;
                         let heightPx = (durationMin / 60) * HOUR_HEIGHT;

                         if (topPx < 0) topPx = 0;
                         if (topPx + heightPx > TOTAL_HOURS * HOUR_HEIGHT) {
                             heightPx = (TOTAL_HOURS * HOUR_HEIGHT) - topPx;
                         }

                         if (heightPx > 5 && topPx < TOTAL_HOURS * HOUR_HEIGHT) {
                             const endObj = new Date(startObj.getTime() + durationMin * 60000);
                             const timeStr = `${startObj.getHours().toString().padStart(2,'0')}:${startObj.getMinutes().toString().padStart(2,'0')} - ${endObj.getHours().toString().padStart(2,'0')}:${endObj.getMinutes().toString().padStart(2,'0')}`;

                             html += `
                                 <div class="time-v1-entry-block ${cssClass}" style="top: ${topPx}px; height: ${heightPx}px;" title="${desc}">
                                     <div class="time-v1-entry-time">${timeStr}</div>
                                     <div class="time-v1-entry-desc text-wrap">${desc}</div>
                                 </div>
                             `;
                         }
                    });

                    html += `
                            </div>
                        </div>
                    `;
                });

                html += `</div>`;

                if (unplaced.length > 0) {
                    html += `<div class="time-v1-unplaced-container">
                        <span class="text-muted small fw-semibold"><i class="bi bi-clock-history"></i> Uden tidsrum:</span>
                    `;
                    unplaced.forEach(u => {
                        const userName = escapeHtml(u.bruger_navn || u.user_name || 'Ukendt');
                        const hrs = u.original_hours || u.timer || 0;
                        html += `<div class="time-v1-unplaced-item">
                            <i class="bi bi-person text-secondary"></i> ${userName} &bull; ${hrs}t
                        </div>`;
                    });
                    html += `</div>`;
                }

                html += `</div>`;
            });

            timeline.innerHTML = html;
        }

        """
    
    if js_start != -1 and js_end != -1:
        text = text[:js_start] + js_new + text[js_end:]
        with open('app/modules/sag/templates/detail.html', 'w', encoding='utf-8') as f:
            f.write(text)
        print("Replaced JS and saved detail.html.")
    else:
        print("JS function not found or end not found.")

patch()
