import React, { useState, useMemo, useEffect } from 'react';
import ReactDOM from 'react-dom/client';

// --- TYPES ---
interface WeekData {
  label: string;
  startDate: Date;
  endDate: Date;
  days: Date[];
}

interface ShowInfo {
  title: string;
  presenter: string;
}

interface ActiveRecording {
  filename: string;
  label: string;
  date: Date;
  hour: number;
}

// --- FULL 7-DAY SCHEDULE DATA ---
// Day 0 = Sunday, 1 = Monday, ..., 6 = Saturday
const FULL_SCHEDULE: Record<number, Record<number, ShowInfo>> = {
  // SUNDAY
  0: {
    6: { title: "Sunday Sunrise", presenter: "Pete & Baz" },
    7: { title: "Sunday Sunrise", presenter: "Pete & Baz" },
    8: { title: "Sunday Sunrise", presenter: "Pete & Baz" },
    9: { title: "Sunday Sunrise", presenter: "Pete & Baz" },
    10: { title: "The Sunday Chart", presenter: "DJ Spark" },
    11: { title: "The Sunday Chart", presenter: "DJ Spark" },
    12: { title: "The Sunday Chart", presenter: "DJ Spark" },
    13: { title: "The Sunday Chart", presenter: "DJ Spark" },
    14: { title: "Sunday Afternoon", presenter: "Sarah Jenkins" },
    15: { title: "Sunday Afternoon", presenter: "Sarah Jenkins" },
    16: { title: "Sunday Afternoon", presenter: "Sarah Jenkins" },
    17: { title: "Sunday Afternoon", presenter: "Sarah Jenkins" },
    18: { title: "Chilled Sunday", presenter: "Anna Taylor" },
    19: { title: "Chilled Sunday", presenter: "Anna Taylor" },
    20: { title: "Sunday Night Owl", presenter: "Marcus Blue" },
    21: { title: "Sunday Night Owl", presenter: "Marcus Blue" },
    22: { title: "Sunday Night Owl", presenter: "Marcus Blue" },
  },
  // MONDAY - FRIDAY (Logic can be expanded per day, showing Monday here)
  1: {
    6: { title: "The Breakfast Club", presenter: "Mike Evans" },
    7: { title: "The Breakfast Club", presenter: "Mike Evans" },
    8: { title: "The Breakfast Club", presenter: "Mike Evans" },
    9: { title: "Monday Morning Mix", presenter: "Sarah Jenkins" },
    10: { title: "Monday Morning Mix", presenter: "Sarah Jenkins" },
    11: { title: "Monday Morning Mix", presenter: "Sarah Jenkins" },
    12: { title: "Lunchtime Live", presenter: "David Chen" },
    13: { title: "Lunchtime Live", presenter: "David Chen" },
    14: { title: "Afternoon Delight", presenter: "Chloe Smith" },
    15: { title: "Afternoon Delight", presenter: "Chloe Smith" },
    16: { title: "Afternoon Delight", presenter: "Chloe Smith" },
    17: { title: "The Drive Home", presenter: "James Wilson" },
    18: { title: "The Drive Home", presenter: "James Wilson" },
    19: { title: "Monday Sessions", presenter: "Anna Taylor" },
    20: { title: "Monday Sessions", presenter: "Anna Taylor" },
    21: { title: "The Night Owl", presenter: "Marcus Blue" },
    22: { title: "The Night Owl", presenter: "Marcus Blue" },
  },
	4: {
    6: { title: "The Breakfast Club", presenter: "Mike Evans" },
    7: { title: "The Breakfast Club", presenter: "Mike Evans" },
    8: { title: "The Breakfast Club", presenter: "Mike Evans" },
    9: { title: "Monday Morning Mix", presenter: "Sarah Jenkins" },
    10: { title: "Monday Morning Mix", presenter: "Sarah Jenkins" },
    11: { title: "Monday Morning Mix", presenter: "Sarah Jenkins" },
    12: { title: "Peter in de ether", presenter: "Peter Mulder" },
    13: { title: "Lunchtime Live", presenter: "David Chen" },
    14: { title: "Afternoon Delight", presenter: "Chloe Smith" },
    15: { title: "Afternoon Delight", presenter: "Chloe Smith" },
    16: { title: "Afternoon Delight", presenter: "Chloe Smith" },
    17: { title: "The Drive Home", presenter: "James Wilson" },
    18: { title: "The Drive Home", presenter: "James Wilson" },
    19: { title: "Monday Sessions", presenter: "Anna Taylor" },
    20: { title: "Monday Sessions", presenter: "Anna Taylor" },
    21: { title: "The Night Owl", presenter: "Marcus Blue" },
    22: { title: "The Night Owl", presenter: "Marcus Blue" },
  },
  // You can add 2, 3, 4, 5, 6 here for unique Tuesday-Saturday schedules
};

// --- SCHEDULE HELPER ---
const getShowInfo = (hour: number, date: Date): ShowInfo => {
  const dayIndex = date.getDay();
  // Try to get specific day/hour, fallback to Monday (1) if not defined for other weekdays
  const scheduleForDay = FULL_SCHEDULE[dayIndex] || FULL_SCHEDULE[1];
  return scheduleForDay[hour] || { title: "REF-FM Jukebox", presenter: "Auto-DJ" };
};

// --- UTILS ---
const getFilenameForHour = (date: Date, hour: number): string => {
  const dd = String(date.getDate()).padStart(2, '0');
  const mm = String(date.getMonth() + 1).padStart(2, '0');
  const yyyy = date.getFullYear();
  const hh = String(hour).padStart(2, '0');
  return `${hh}_${dd}-${mm}-${yyyy}.mp3`;
};

const getWeeks = (): WeekData[] => {
  const weeks: WeekData[] = [];
  const now = new Date();
  const currentDay = now.getDay();
  const diff = now.getDate() - currentDay + (currentDay === 0 ? -6 : 1);
  const startOfCurrentWeek = new Date(now.getTime());
  startOfCurrentWeek.setDate(diff);
  startOfCurrentWeek.setHours(0, 0, 0, 0);

  for (let i = 0; i < 4; i++) {
    const weekStart = new Date(startOfCurrentWeek.getTime());
    weekStart.setDate(weekStart.getDate() - (i * 7));
    const weekEnd = new Date(weekStart.getTime());
    weekEnd.setDate(weekEnd.getDate() + 6);

    const days: Date[] = [];
    for (let d = 0; d < 7; d++) {
      const day = new Date(weekStart.getTime());
      day.setDate(day.getDate() + d);
      days.push(day);
    }
    const label = i === 0 ? "Current Week" : `${i} week${i > 1 ? 's' : ''} ago`;
    weeks.push({ label, startDate: weekStart, endDate: weekEnd, days });
  }
  return weeks;
};

const formatTime = (hour: number): string => {
  const suffix = hour >= 12 ? 'PM' : 'AM';
  const displayHour = hour % 12 || 12;
  return `${displayHour}:00 ${suffix}`;
};

const isFuture = (date: Date, hour: number): boolean => {
  const now = new Date();
  const checkDate = new Date(date.getTime());
  checkDate.setHours(hour, 0, 0, 0);
  return checkDate > now;
};

const isToday = (date: Date): boolean => {
  const now = new Date();
  return date.getDate() === now.getDate() &&
    date.getMonth() === now.getMonth() &&
    date.getFullYear() === now.getFullYear();
};

const isSameDay = (d1: Date, d2: Date): boolean => {
  return d1.getDate() === d2.getDate() &&
         d1.getMonth() === d2.getMonth() &&
         d1.getFullYear() === d2.getFullYear();
};

// --- COMPONENTS ---

const Header: React.FC = () => (
  <header className="bg-slate-900 border-b border-slate-800 sticky top-0 z-40">
    <div className="max-w-[1600px] mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">
      <div className="flex items-center gap-3">
        <div className="bg-amber-500 p-1.5 rounded-lg shadow-lg shadow-amber-500/20">
          <svg className="w-6 h-6 text-slate-950" fill="currentColor" viewBox="0 0 24 24">
            <path d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z" />
          </svg>
        </div>
        <span className="text-xl font-black text-white uppercase tracking-tighter">REF-FM <span className="text-amber-500 italic">ARCHIVE</span></span>
      </div>
      <div className="hidden sm:block text-slate-500 text-[10px] font-black uppercase tracking-[0.3em]">
        Play from our high quality servers
      </div>
    </div>
  </header>
);

const PlayerOverlay: React.FC<{ filename: string, label: string, onClose: () => void }> = ({ filename, label, onClose }) => {
  const [error, setError] = useState(false);
  useEffect(() => setError(false), [filename]);

  return (
    <div className="fixed bottom-0 left-0 right-0 p-4 z-50 animate-in slide-in-from-bottom duration-300">
      <div className="max-w-4xl mx-auto bg-slate-900 border border-slate-700 rounded-2xl shadow-2xl p-4 sm:p-6 flex flex-col md:flex-row items-center gap-6">
        <div className="flex items-center gap-4 w-full md:w-auto">
          <div className="bg-amber-500 p-3 rounded-xl shadow-lg shadow-amber-500/20">
            <svg className="w-6 h-6 text-slate-950" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z" />
            </svg>
          </div>
          <div className="flex-1 min-w-0">
            <p className="text-[10px] font-black text-amber-500 uppercase tracking-widest">Now Playing</p>
            <h3 className="text-white font-bold truncate">{label}</h3>
            <p className="text-slate-500 text-[10px] font-mono mt-0.5">{filename}</p>
          </div>
        </div>
        <div className="flex-1 w-full">
          {error ? (
            <div className="bg-red-500/10 border border-red-500/30 rounded-lg p-3 text-red-400 text-xs font-bold">
              Recording not found or rotation error.
            </div>
          ) : (
            <audio autoPlay controls className="w-full h-10 filter invert opacity-80" onError={() => setError(true)} src={`podcasts/${filename}`}>
              Your browser does not support audio playback.
            </audio>
          )}
        </div>
        <button onClick={onClose} className="p-2 hover:bg-slate-800 rounded-full text-slate-400 hover:text-white transition-colors">
          <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /></svg>
        </button>
      </div>
    </div>
  );
};

// --- APP ---

const App: React.FC = () => {
  const weeks = useMemo(() => getWeeks(), []);
  const [selectedWeek, setSelectedWeek] = useState<WeekData>(weeks[0]);
  const [activeRecording, setActiveRecording] = useState<ActiveRecording | null>(null);
  const [availableFiles, setAvailableFiles] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);

  const hours = Array.from({ length: 17 }, (_, i) => i + 6); // 6 AM to 10 PM

  const fetchAvailablePodcasts = async () => {
    try {
      const response = await fetch('api/list-podcasts');
      if (response.ok) {
        const data = await response.json();
        setAvailableFiles(data);
      }
    } catch (err) {
      console.error("Failed to fetch podcasts:", err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchAvailablePodcasts();
    const interval = setInterval(fetchAvailablePodcasts, 60000);
    return () => clearInterval(interval);
  }, []);

  const handlePlay = (date: Date, hour: number) => {
    const filename = getFilenameForHour(date, hour);
    const showInfo = getShowInfo(hour, date);
    const dateStr = date.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
    const label = `${showInfo.title} with ${showInfo.presenter} (${dateStr})`;
    setActiveRecording({ filename, label, date, hour });
  };

  const isHighlighted = (date: Date, hour: number): boolean => {
    if (!activeRecording) return false;
    return isSameDay(activeRecording.date, date) && activeRecording.hour === hour;
  };

  return (
    <div className="min-h-screen bg-slate-950 text-slate-200">
      <Header />
      <main className="max-w-[1600px] mx-auto px-4 sm:px-6 lg:px-8 py-10 pb-32">
        <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-6 mb-10">
          <div>
            <h2 className="text-4xl font-black text-white tracking-tight uppercase">Program Archive</h2>
            <p className="text-slate-400 mt-1 font-medium italic opacity-70">Browse recordings from the last 28 days.</p>
          </div>
          
          <div className="flex items-center gap-2 bg-slate-900 p-1 rounded-xl border border-slate-800 shadow-xl overflow-x-auto max-w-full no-scrollbar">
            {weeks.map((week) => (
              <button
                key={week.label}
                onClick={() => setSelectedWeek(week)}
                className={`px-4 py-2 rounded-lg text-xs font-bold uppercase tracking-widest transition-all whitespace-nowrap ${
                  selectedWeek.label === week.label
                    ? 'bg-amber-500 text-slate-950 shadow-lg'
                    : 'text-slate-500 hover:text-white hover:bg-slate-800'
                }`}
              >
                {week.label}
              </button>
            ))}
          </div>
        </div>

        {loading ? (
          <div className="flex flex-col items-center justify-center py-24 bg-slate-900 rounded-3xl border border-slate-800 shadow-xl">
             <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-amber-500 mb-4"></div>
             <p className="text-slate-500 font-black uppercase tracking-widest text-[10px]">Syncing Archive...</p>
          </div>
        ) : (
          <div className="bg-slate-900 rounded-3xl border border-slate-800 overflow-hidden shadow-2xl">
            <div className="overflow-x-auto">
              <table className="w-full border-collapse">
                <thead>
                  <tr className="bg-slate-800/50">
                    <th className="p-4 text-left text-[10px] font-black text-slate-500 uppercase tracking-widest border-b border-slate-800 sticky left-0 bg-slate-900 z-10">Time</th>
                    {selectedWeek.days.map((day, i) => {
                      const today = isToday(day);
                      return (
                        <th key={i} className={`p-4 text-center border-b border-slate-800 min-w-[140px] relative ${today ? 'bg-amber-500/5' : ''}`}>
                          {today && <div className="absolute top-0 left-0 right-0 h-1 bg-amber-500"></div>}
                          <div className={`text-[10px] font-black uppercase tracking-widest mb-1 ${today ? 'text-amber-500' : 'text-slate-500'}`}>
                            {day.toLocaleDateString('en-GB', { weekday: 'short' })}
                          </div>
                          <div className={`text-xl font-black ${today ? 'text-white' : 'text-slate-300'}`}>
                            {day.getDate()} {day.toLocaleDateString('en-GB', { month: 'short' })}
                          </div>
                        </th>
                      );
                    })}
                  </tr>
                </thead>
                <tbody>
                  {hours.map((hour) => (
                    <tr key={hour} className="group hover:bg-slate-800/20 transition-colors">
                      <td className="p-4 text-xs font-black text-slate-500 border-b border-slate-800 sticky left-0 bg-slate-900 group-hover:bg-slate-800/50 z-10">
                        {formatTime(hour)}
                      </td>
                      {selectedWeek.days.map((day, i) => {
                        const future = isFuture(day, hour);
                        const playing = isHighlighted(day, hour);
                        const filename = getFilenameForHour(day, hour);
                        const isAvailable = availableFiles.includes(filename);
                        const today = isToday(day);
                        const show = getShowInfo(hour, day);

                        return (
                          <td key={i} className={`p-2 border-b border-slate-800 text-center ${today ? 'bg-amber-500/[0.01]' : ''}`}>
                            <div className={`flex flex-col gap-1.5 p-3 rounded-xl border transition-all duration-500 ${
                              playing 
                                ? 'bg-amber-500/15 border-amber-500 shadow-[0_0_20px_rgba(245,158,11,0.3)] ring-1 ring-amber-500/40' 
                                : 'border-transparent'
                            }`}>
                              <div className="flex flex-col min-h-[40px] justify-center">
                                <span className={`text-[10px] font-black uppercase tracking-tighter truncate leading-tight ${playing ? 'text-amber-500' : 'text-white'}`}>
                                  {show.title}
                                </span>
                                <span className="text-[9px] font-bold text-slate-500 uppercase tracking-tight truncate mt-0.5">
                                  {show.presenter}
                                </span>
                              </div>
                              
                              {future ? (
                                <div className="py-2 text-[8px] font-black text-slate-800 uppercase tracking-widest border border-dashed border-slate-800 rounded-lg">
                                  Upcoming
                                </div>
                              ) : isAvailable ? (
                                <button
                                  onClick={() => handlePlay(day, hour)}
                                  className={`w-full py-2 rounded-lg transition-all shadow-md active:scale-95 text-[9px] font-black uppercase tracking-[0.2em] ${
                                    playing 
                                      ? 'bg-amber-500 text-slate-950 hover:bg-amber-400' 
                                      : 'bg-slate-800 hover:bg-amber-500 text-white hover:text-slate-950 border border-slate-700 hover:border-amber-500'
                                  }`}
                                >
                                  {playing ? "Playing" : "Listen"}
                                </button>
                              ) : (
                                <div className="py-2 text-[8px] font-bold text-slate-700 uppercase tracking-widest border border-slate-800/50 rounded-lg opacity-40">
                                  Missing
                                </div>
                              )}
                            </div>
                          </td>
                        );
                      })}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </main>

      <footer className="max-w-[1600px] mx-auto px-4 sm:px-6 lg:px-8 py-12 text-center border-t border-slate-900">
        <p className="text-slate-600 font-bold uppercase tracking-[0.4em] text-[10px]">
          &copy; {new Date().getFullYear()} REF-FM Radio Station • Digital Log Engine
        </p>
      </footer>

      {activeRecording && (
        <PlayerOverlay 
          filename={activeRecording.filename} 
          label={activeRecording.label} 
          onClose={() => setActiveRecording(null)} 
        />
      )}
    </div>
  );
};

const rootElement = document.getElementById('root');
if (rootElement) {
  const root = ReactDOM.createRoot(rootElement);
  root.render(<App />);
}
