// app/schedule/page.tsx

"use client"

import React, { useRef } from 'react';
import scheduleData from '../data/schedule.json';
import { Clock, CalendarRange } from 'lucide-react';

// --- Helper Functions ---

// Bulletproof parser: Finds the times regardless of spaces or dashes!
const parseTimeBlock = (timeStr: string) => {
    if (!timeStr || timeStr === 'Ledig') return null;

    // Scans the string and extracts any "HH:MM" patterns
    const matches = timeStr.match(/(\d{1,2}):(\d{2})/g);
    if (!matches || matches.length < 2) return null;

    const parse = (t: string) => {
        const [h, m] = t.split(':').map(Number);
        return h + (m / 60);
    };

    return { start: parse(matches[0]), end: parse(matches[1]) };
};

// Checks if the two time blocks actually collide
const checkOverlap = (time1?: string, time2?: string) => {
    const t1 = time1 ? parseTimeBlock(time1) : null;
    const t2 = time2 ? parseTimeBlock(time2) : null;
    if (!t1 || !t2) return false;

    return t1.start < t2.end && t1.end > t2.start;
};


// --- Types & Components ---

interface ShiftData {
    time: string;
    title?: string;
    notes?: string;
}

interface ShiftBlockProps {
    team: 'PF' | 'TU';
    data: ShiftData;
    pos: { top: number; height: number };
    isOverlapping: boolean;
}

// Reusable Component for the Event Cards
const ShiftBlock: React.FC<ShiftBlockProps> = ({ team, data, pos, isOverlapping }) => {
    const isPF = team === 'PF';

    // Calculate layout based on overlap
    const widthClasses = isOverlapping
        ? isPF ? "left-1 right-1/2 mr-0.5" : "left-1/2 right-1 ml-0.5"
        : "left-1 right-1";

    // Team-specific styling
    const bgClasses = isPF
        ? "bg-gradient-to-br from-gold to-goldenrod border-goldenrod"
        : "bg-gradient-to-br from-seafoam to-slate-teal border-slate-teal";

    const textMain = isPF ? "text-ebony" : "text-eggshell";
    const textMuted = isPF ? "text-ebony/90" : "text-eggshell/90";
    const notesBg = isPF ? "bg-eggshell/30 border-seafoam/5" : "bg-gold/20 border-eggshell/10";
    const fallbackTitle = isPF ? "PF" : "TU";

    return (
        <div
            // Removed scale on hover! Added brightness-105 for a safe, non-clipping hover effect.
            className={`absolute ${widthClasses} ${bgClasses} rounded-lg p-1.5 flex flex-col overflow-hidden shadow-sm border cursor-pointer transition-all hover:brightness-105 hover:shadow-md`}
            style={{ top: `${pos.top}px`, height: `${pos.height}px` }}
        >
            <p className={`text-[10px] font-black ${textMain} uppercase tracking-wide leading-tight truncate`}>
                {data.title || fallbackTitle}
            </p>
            <p className={`text-[9px] font-bold ${textMuted} flex items-center mt-0.5 whitespace-nowrap`}>
                <Clock size={8} className="mr-0.5 shrink-0" />
                <span className="truncate">{data.time}</span>
            </p>
            {data.notes && pos.height > 50 && (
                <div className={`mt-1 ${notesBg} p-1 rounded-md border`}>
                    <p className={`text-[9px] font-medium ${textMain} leading-tight truncate pb-1`}>
                        {data.notes}
                    </p>
                </div>
            )}
        </div>
    );
};


// --- Main Schedule View ---

export default function Schedule() {
    const startHour = 7;
    const endHour = 17;
    const hours = Array.from({ length: endHour - startHour + 1 }, (_, i) => startHour + i);
    const PIXELS_PER_HOUR = 60;

    const GRID_PADDING_TOP = 24;
    const TOTAL_GRID_HEIGHT = (hours.length * PIXELS_PER_HOUR) + GRID_PADDING_TOP;

    const containerRef = useRef<HTMLDivElement>(null);

    const calculatePosition = (timeStr: string) => {
        const t = parseTimeBlock(timeStr);
        if (!t) return null;

        const topOffset = (t.start - startHour) * PIXELS_PER_HOUR;
        const duration = (t.end - t.start) * PIXELS_PER_HOUR;

        return { top: topOffset + GRID_PADDING_TOP + 1, height: duration - 2 };
    };

    return (
        <div className="space-y-4 animate-fade-in w-full">
            <div>
                <h1 className="text-3xl font-black text-slate-teal tracking-tight flex items-center">
                    <CalendarRange className="mr-3 text-seafoam" size={32} />
                    Veckoschema
                </h1>
                <p className="text-moss font-medium mt-2 ml-11">Här hittar du när vi bemannar Kullaberg.</p>
            </div>

            <div className="bg-eggshell border-2 border-slate-teal/20 rounded-2xl shadow-sm overflow-hidden flex flex-col max-h-[65vh] h-max min-h-125">
                <div className="flex-1 overflow-auto scrollbar-hide" ref={containerRef}>
                    <div className="flex min-w-200 w-full">

                        {/* Sticky Time Column */}
                        <div className="sticky left-0 z-20 w-18 flex-none bg-eggshell border-r-2 border-slate-teal/10 shadow-[2px_0_5px_rgba(0,0,0,0.02)]">
                            <div className="sticky top-0 z-30 h-12 border-b-2 border-slate-teal/10 bg-eggshell"></div>
                            <div className="relative w-full" style={{ height: `${TOTAL_GRID_HEIGHT}px` }}>
                                {hours.map((hour, i) => (
                                    <div key={hour} className="absolute w-full flex justify-end pr-3" style={{ top: `${i * PIXELS_PER_HOUR + GRID_PADDING_TOP}px` }}>
                                        <span className="text-[11px] font-bold text-slate-teal -mt-2 bg-eggshell px-1">
                                            {hour.toString().padStart(2, '0')}:00
                                        </span>
                                    </div>
                                ))}
                            </div>
                        </div>

                        {/* Grid Area */}
                        <div className="flex-auto relative">
                            {/* Sticky Day Headers */}
                            <div className="sticky top-0 z-10 flex h-12 border-b-2 border-slate-teal/10 bg-eggshell">
                                {scheduleData.map((d) => (
                                    <div key={d.day} className="flex-1 flex items-center justify-center border-l-2 border-slate-teal/5 first:border-l-0 min-w-25">
                                        <span className="text-xs font-black text-ebony uppercase tracking-widest">{d.day.substring(0, 3)}</span>
                                    </div>
                                ))}
                            </div>

                            {/* Main Grid Canvas */}
                            <div className="relative w-full" style={{ height: `${TOTAL_GRID_HEIGHT}px` }}>
                                <div className="absolute inset-0 z-0">
                                    {hours.map((hour, i) => (
                                        <div key={hour} className="absolute w-full border-t border-slate-teal/10" style={{ top: `${i * PIXELS_PER_HOUR + GRID_PADDING_TOP}px`, height: `${PIXELS_PER_HOUR}px` }} />
                                    ))}
                                </div>

                                {/* Vertical Columns & Blocks */}
                                <div className="absolute inset-0 flex z-0">
                                    {scheduleData.map((d, colIndex) => {
                                        // Type casting here assumes scheduleData is typed loosely.
                                        const pfData = d.pilgrimsfalkarna as ShiftData | undefined;
                                        const tuData = d.tumlarna as ShiftData | undefined;

                                        const hasPF = !!(pfData && pfData.time && pfData.time !== 'Ledig');
                                        const hasTU = !!(tuData && tuData.time && tuData.time !== 'Ledig');
                                        const isOverlapping = hasPF && hasTU && checkOverlap(pfData.time, tuData.time);

                                        return (
                                            <div key={colIndex} className="flex-1 border-l border-slate-teal/10 relative min-w-25">
                                                {/* Pilgrimsfalkarna Component */}
                                                {hasPF && (() => {
                                                    const pos = calculatePosition(pfData.time);
                                                    return pos ? <ShiftBlock team="PF" data={pfData} pos={pos} isOverlapping={isOverlapping} /> : null;
                                                })()}

                                                {/* Tumlarna Component */}
                                                {hasTU && (() => {
                                                    const pos = calculatePosition(tuData.time);
                                                    return pos ? <ShiftBlock team="TU" data={tuData} pos={pos} isOverlapping={isOverlapping} /> : null;
                                                })()}
                                            </div>
                                        );
                                    })}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* Legend */}
            <div className="flex items-center justify-center space-x-6 py-2 text-xs font-bold text-slate-teal">
                <span className="flex items-center"><div className="w-3 h-3 bg-linear-to-br from-gold to-goldenrod rounded-full mr-2 shadow-sm"></div> Pilgrimsfalkarna</span>
                <span className="flex items-center"><div className="w-3 h-3 bg-linear-to-br from-seafoam to-slate-teal rounded-full mr-2 shadow-sm"></div> Tumlarna</span>
            </div>
        </div>
    );
};