// DeadlinesCalendarWidget - Monthly calendar showing project deadlines and Google events
function DeadlinesCalendarWidget({ projects, onViewChange, googleEvents = [], onMonthChange }) {
    const [currentDate, setCurrentDate] = React.useState(new Date());
    const [selectedDay, setSelectedDay] = React.useState(null);

    // Italian month names
    const monthNames = [
        'Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno',
        'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre'
    ];

    // Italian weekday abbreviations (starting Monday)
    const weekDays = ['Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab', 'Dom'];

    // Generate calendar days for current month
    const calendarDays = React.useMemo(() => {
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth();

        const firstDay = new Date(year, month, 1);
        const lastDay = new Date(year, month + 1, 0);

        // Get day of week (0=Sun, adjust for Monday start)
        let startPadding = firstDay.getDay() - 1;
        if (startPadding < 0) startPadding = 6; // Sunday becomes 6

        const daysInMonth = lastDay.getDate();
        const days = [];

        // Add padding for previous month
        for (let i = startPadding - 1; i >= 0; i--) {
            const prevDate = new Date(year, month, -i);
            days.push({ date: prevDate, isCurrentMonth: false });
        }

        // Current month days
        for (let d = 1; d <= daysInMonth; d++) {
            days.push({ date: new Date(year, month, d), isCurrentMonth: true });
        }

        // Pad to complete grid (6 rows x 7 days = 42)
        const remaining = 42 - days.length;
        for (let i = 1; i <= remaining; i++) {
            days.push({ date: new Date(year, month + 1, i), isCurrentMonth: false });
        }

        return days;
    }, [currentDate]);

    // Get projects for a specific date
    const getProjectsForDate = React.useCallback((date) => {
        const dateStr = date.toISOString().split('T')[0];
        return projects.filter(p =>
            p.due_date === dateStr &&
            p.status !== 'completato' &&
            !p.is_archived
        );
    }, [projects]);

    // Get Google events for a specific date
    const getGoogleEventsForDate = React.useCallback((date) => {
        const dateStr = date.toISOString().split('T')[0];
        return googleEvents.filter(event => {
            // Handle all-day events (start is just a date)
            if (event.all_day) {
                return event.start === dateStr;
            }
            // Handle timed events (start is a datetime string)
            const eventDate = event.start?.split('T')[0];
            return eventDate === dateStr;
        });
    }, [googleEvents]);

    // Check if date is today
    const isToday = (date) => {
        const today = new Date();
        return date.getDate() === today.getDate() &&
               date.getMonth() === today.getMonth() &&
               date.getFullYear() === today.getFullYear();
    };

    // Navigate months
    const goToPrevMonth = () => {
        const newDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 1);
        setCurrentDate(newDate);
        setSelectedDay(null);
        if (onMonthChange) {
            onMonthChange(newDate.getMonth() + 1, newDate.getFullYear());
        }
    };

    const goToNextMonth = () => {
        const newDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1);
        setCurrentDate(newDate);
        setSelectedDay(null);
        if (onMonthChange) {
            onMonthChange(newDate.getMonth() + 1, newDate.getFullYear());
        }
    };

    const goToToday = () => {
        const newDate = new Date();
        setCurrentDate(newDate);
        setSelectedDay(null);
        if (onMonthChange) {
            onMonthChange(newDate.getMonth() + 1, newDate.getFullYear());
        }
    };

    // Get dot color based on priority
    const getDotColor = (priority) => {
        switch (priority) {
            case 'high': return 'bg-red-500';
            case 'medium': return 'bg-amber-500';
            case 'low': return 'bg-blue-500';
            default: return 'bg-slate-400';
        }
    };

    // Render dots for projects and Google events on a day
    const renderDots = (dayProjects, dayGoogleEvents) => {
        const totalItems = dayProjects.length + dayGoogleEvents.length;
        if (totalItems === 0) return null;

        const maxDots = 3;
        const dots = [];

        // Add project dots first
        dayProjects.slice(0, maxDots).forEach((p, i) => {
            dots.push(
                <span key={`p-${i}`} className={`w-1.5 h-1.5 rounded-full ${getDotColor(p.priority)}`} />
            );
        });

        // Add Google event dots (blue-400 color)
        const remainingSlots = maxDots - dots.length;
        dayGoogleEvents.slice(0, remainingSlots).forEach((e, i) => {
            dots.push(
                <span key={`g-${i}`} className="w-1.5 h-1.5 rounded-full bg-blue-400" />
            );
        });

        const extraCount = totalItems - maxDots;

        return (
            <div className="flex justify-center gap-0.5 mt-0.5">
                {dots}
                {extraCount > 0 && (
                    <span className="text-[8px] text-slate-400 ml-0.5">+{extraCount}</span>
                )}
            </div>
        );
    };

    // Handle day click
    const handleDayClick = (day, hasItems) => {
        if (hasItems) {
            setSelectedDay(selectedDay?.getTime() === day.date.getTime() ? null : day.date);
        }
    };

    // Get items for selected day
    const selectedDayProjects = selectedDay ? getProjectsForDate(selectedDay) : [];
    const selectedDayGoogleEvents = selectedDay ? getGoogleEventsForDate(selectedDay) : [];

    return (
        <Card className="p-4">
            {/* Header */}
            <div className="flex items-center justify-between mb-4">
                <h3 className="font-semibold text-slate-900 flex items-center gap-2">
                    <svg className="w-5 h-5 text-brand-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                              d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                    </svg>
                    Calendario Scadenze
                </h3>
            </div>

            {/* Month Navigation */}
            <div className="flex items-center justify-between mb-4">
                <button
                    onClick={goToPrevMonth}
                    className="p-1.5 rounded hover:bg-slate-100 transition-colors"
                >
                    <svg className="w-5 h-5 text-slate-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                    </svg>
                </button>

                <div className="flex items-center gap-2">
                    <span className="font-medium text-slate-800">
                        {monthNames[currentDate.getMonth()]} {currentDate.getFullYear()}
                    </span>
                    <button
                        onClick={goToToday}
                        className="text-xs px-2 py-0.5 rounded bg-slate-100 text-slate-600 hover:bg-slate-200 transition-colors"
                    >
                        Oggi
                    </button>
                </div>

                <button
                    onClick={goToNextMonth}
                    className="p-1.5 rounded hover:bg-slate-100 transition-colors"
                >
                    <svg className="w-5 h-5 text-slate-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                    </svg>
                </button>
            </div>

            {/* Weekday Headers */}
            <div className="grid grid-cols-7 mb-1">
                {weekDays.map(day => (
                    <div key={day} className="text-center text-xs font-medium text-slate-500 py-1">
                        {day}
                    </div>
                ))}
            </div>

            {/* Calendar Grid */}
            <div className="grid grid-cols-7 gap-px bg-slate-100 rounded-lg overflow-hidden">
                {calendarDays.map((day, index) => {
                    const dayProjects = getProjectsForDate(day.date);
                    const dayGoogleEvents = getGoogleEventsForDate(day.date);
                    const hasItems = dayProjects.length > 0 || dayGoogleEvents.length > 0;
                    const isSelected = selectedDay?.getTime() === day.date.getTime();

                    return (
                        <div
                            key={index}
                            className={`
                                bg-white p-1 min-h-[44px] text-center transition-colors
                                ${!day.isCurrentMonth ? 'text-slate-300' : 'text-slate-700'}
                                ${hasItems ? 'cursor-pointer hover:bg-slate-50' : ''}
                                ${isSelected ? 'bg-brand-50 ring-1 ring-brand-300' : ''}
                                ${isToday(day.date) ? 'font-bold' : ''}
                            `}
                            onClick={() => handleDayClick(day, hasItems)}
                        >
                            <span className={`
                                inline-flex items-center justify-center w-6 h-6 text-sm rounded-full
                                ${isToday(day.date) ? 'bg-brand-500 text-white' : ''}
                            `}>
                                {day.date.getDate()}
                            </span>
                            {day.isCurrentMonth && renderDots(dayProjects, dayGoogleEvents)}
                        </div>
                    );
                })}
            </div>

            {/* Selected Day Details */}
            {selectedDay && (selectedDayProjects.length > 0 || selectedDayGoogleEvents.length > 0) && (
                <div className="mt-4 p-3 bg-slate-50 rounded-lg">
                    <div className="text-sm font-medium text-slate-700 mb-2">
                        {selectedDay.getDate()} {monthNames[selectedDay.getMonth()]}
                    </div>
                    <div className="space-y-2">
                        {/* Project deadlines */}
                        {selectedDayProjects.map(project => (
                            <div
                                key={project.id}
                                className="flex items-center gap-2 p-2 bg-white rounded border border-slate-200
                                          cursor-pointer hover:border-brand-300 transition-colors"
                                onClick={() => onViewChange('projects')}
                            >
                                <span className={`w-2 h-2 rounded-full ${getDotColor(project.priority)}`} />
                                <span className="text-sm text-slate-800 truncate flex-1">{project.name}</span>
                                <svg className="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                                </svg>
                            </div>
                        ))}
                        {/* Google Calendar events */}
                        {selectedDayGoogleEvents.map(event => (
                            <a
                                key={event.id}
                                href={event.html_link}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="flex items-center gap-2 p-2 bg-white rounded border border-slate-200
                                          hover:border-blue-300 transition-colors"
                            >
                                <span className="w-2 h-2 rounded-full bg-blue-400" />
                                <div className="flex-1 min-w-0">
                                    <span className="text-sm text-slate-800 truncate block">{event.summary}</span>
                                    {!event.all_day && event.start && (
                                        <span className="text-xs text-slate-400">
                                            {new Date(event.start).toLocaleTimeString('it-IT', { hour: '2-digit', minute: '2-digit' })}
                                            {event.end && ` - ${new Date(event.end).toLocaleTimeString('it-IT', { hour: '2-digit', minute: '2-digit' })}`}
                                        </span>
                                    )}
                                </div>
                                <svg className="w-4 h-4 text-slate-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                                </svg>
                            </a>
                        ))}
                    </div>
                </div>
            )}

            {/* Legend */}
            <div className="mt-4 flex items-center justify-center gap-4 text-xs text-slate-500 flex-wrap">
                <div className="flex items-center gap-1">
                    <span className="w-2 h-2 rounded-full bg-red-500" />
                    <span>Alta</span>
                </div>
                <div className="flex items-center gap-1">
                    <span className="w-2 h-2 rounded-full bg-amber-500" />
                    <span>Media</span>
                </div>
                <div className="flex items-center gap-1">
                    <span className="w-2 h-2 rounded-full bg-blue-500" />
                    <span>Bassa</span>
                </div>
                {googleEvents.length > 0 && (
                    <div className="flex items-center gap-1">
                        <span className="w-2 h-2 rounded-full bg-blue-400" />
                        <span>Google Calendar</span>
                    </div>
                )}
            </div>
        </Card>
    );
}

window.DeadlinesCalendarWidget = DeadlinesCalendarWidget;
