// ============================================================
// MOORE AI v13 — CALENDAR TAB
// Month view + Week view with time slots (like GHL/Google Cal)
// ============================================================

const CalendarView = ({ calEvents, calView, setCalView, calDate, setCalDate, loadingTabs, fetchCalendar, calendars, selectedCalendarId, setSelectedCalendarId }) => {
  const getDaysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();
  const getFirstDayOfMonth = (year, month) => new Date(year, month, 1).getDay();

  const year = calDate.getFullYear();
  const month = calDate.getMonth();
  const daysInMonth = getDaysInMonth(year, month);
  const firstDay = getFirstDayOfMonth(year, month);
  const today = new Date();

  // Current time indicator
  const [nowMinutes, setNowMinutes] = React.useState(() => today.getHours() * 60 + today.getMinutes());
  React.useEffect(() => {
    const t = setInterval(() => setNowMinutes(new Date().getHours() * 60 + new Date().getMinutes()), 60000);
    return () => clearInterval(t);
  }, []);

  // Week view: get the Sunday-starting week that contains calDate
  const getWeekStart = (d) => {
    const s = new Date(d);
    s.setDate(s.getDate() - s.getDay());
    s.setHours(0, 0, 0, 0);
    return s;
  };
  const weekStart = getWeekStart(calDate);
  const weekDays = Array.from({ length: 7 }, (_, i) => {
    const d = new Date(weekStart);
    d.setDate(weekStart.getDate() + i);
    return d;
  });

  // Hours to display (6am – 9pm)
  const HOURS = Array.from({ length: 16 }, (_, i) => i + 6);
  const gridStart = HOURS[0];
  const totalHours = HOURS.length;
  const PX_PER_HOUR = 64;
  const totalHeight = totalHours * PX_PER_HOUR;

  // Current time position in px
  const nowPx = ((nowMinutes / 60) - gridStart) / totalHours * totalHeight;
  const showNowLine = nowMinutes / 60 >= gridStart && nowMinutes / 60 <= gridStart + totalHours;

  // Which day column is today (for the red line)
  const todayColIndex = weekDays.findIndex(d => d.toDateString() === today.toDateString());

  const eventsOnDay = (day) => calEvents.filter(e => {
    if (!e.startTime) return false;
    const d = new Date(e.startTime);
    return d.getFullYear() === year && d.getMonth() === month && d.getDate() === day;
  });

  const eventsOnDate = (date) => calEvents.filter(e => {
    if (!e.startTime) return false;
    const d = new Date(e.startTime);
    return d.getFullYear() === date.getFullYear() && d.getMonth() === date.getMonth() && d.getDate() === date.getDate();
  });

  const monthName = calDate.toLocaleString('default', { month: 'long', year: 'numeric' });
  const weekLabel = `${weekDays[0].toLocaleDateString('en-US', { month: 'short', day: 'numeric' })} – ${weekDays[6].toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}`;
  const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

  const handleCalendarChange = async (id) => {
    setSelectedCalendarId(id);
    await API.saveSettings({ calendarId: id });
    fetchCalendar(id);
  };

  const prevPeriod = () => {
    const d = new Date(calDate);
    if (calView === 'week') d.setDate(d.getDate() - 7);
    else d.setMonth(d.getMonth() - 1);
    setCalDate(d);
  };
  const nextPeriod = () => {
    const d = new Date(calDate);
    if (calView === 'week') d.setDate(d.getDate() + 7);
    else d.setMonth(d.getMonth() + 1);
    setCalDate(d);
  };

  const fmtHour = (h) => h === 12 ? '12 PM' : h > 12 ? `${h - 12} PM` : `${h} AM`;

  return (
    <div className="p-6 space-y-5">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <div className="text-xs mono text-slate-500 uppercase tracking-widest mb-1">Schedule</div>
          <h2 className="font-black text-white text-2xl italic tracking-tight">Calendar</h2>
        </div>
        <div className="flex items-center gap-2 flex-wrap justify-end">
          {/* Calendar picker — always show; "All" shows every calendar's events */}
          <select
            value={selectedCalendarId || 'all'}
            onChange={e => handleCalendarChange(e.target.value)}
            className="bg-slate-900/60 border border-slate-700/60 rounded-xl px-3 py-2 text-xs text-white outline-none focus:border-blue-500/50 cursor-pointer">
            <option value="all">All Calendars</option>
            {(calendars || []).map(c => (
              <option key={c.id} value={c.id}>{c.name}</option>
            ))}
          </select>
          {/* View toggle */}
          <div className="flex bg-slate-900/60 border border-slate-800 rounded-xl overflow-hidden">
            {['month', 'week'].map(v => (
              <button key={v} onClick={() => setCalView(v)}
                className={`px-3 py-2 text-xs font-bold mono uppercase tracking-wider transition-colors ${calView === v ? 'bg-blue-600/30 text-blue-400' : 'text-slate-500 hover:text-slate-300'}`}>
                {v}
              </button>
            ))}
          </div>
          {/* Nav */}
          <button onClick={prevPeriod} className="p-2 bg-slate-900/60 border border-slate-800 rounded-xl text-slate-400 hover:text-white transition-colors">
            <Icon name="chevron-left" size={14} />
          </button>
          <span className="font-bold text-white text-sm min-w-48 text-center">{calView === 'week' ? weekLabel : monthName}</span>
          <button onClick={nextPeriod} className="p-2 bg-slate-900/60 border border-slate-800 rounded-xl text-slate-400 hover:text-white transition-colors">
            <Icon name="chevron-right" size={14} />
          </button>
          <button onClick={() => setCalDate(new Date())} className="px-3 py-2 text-xs mono text-slate-400 hover:text-white bg-slate-900/60 border border-slate-800 rounded-xl transition-colors">Today</button>
          <button onClick={() => fetchCalendar(selectedCalendarId)} className="p-2 bg-slate-900/60 border border-slate-800 rounded-xl text-slate-400 hover:text-white transition-colors">
            <Icon name="refresh-cw" size={14} />
          </button>
        </div>
      </div>

      {loadingTabs.calendar ? (
        <div className="flex justify-center py-20"><div className="w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" /></div>
      ) : calView === 'week' ? (
        /* ===== WEEK VIEW ===== */
        <div className="bg-slate-900/40 border border-slate-800/60 rounded-2xl overflow-hidden">
          {/* Day headers */}
          <div className="grid border-b border-slate-800/50" style={{ gridTemplateColumns: '56px repeat(7, 1fr)' }}>
            <div className="py-3 border-r border-slate-800/40 text-[10px] mono text-slate-600 text-center pt-4">GMT</div>
            {weekDays.map((d, i) => {
              const isToday = d.toDateString() === today.toDateString();
              return (
                <div key={i} className={`py-3 text-center border-r border-slate-800/30 last:border-r-0 ${isToday ? 'bg-blue-950/20' : ''}`}>
                  <div className="text-[10px] mono font-bold text-slate-500 uppercase tracking-wider">{dayNames[d.getDay()]}</div>
                  <div className={`text-sm font-black mx-auto mt-1 w-7 h-7 flex items-center justify-center rounded-full ${isToday ? 'bg-blue-600 text-white' : 'text-slate-300'}`}>
                    {d.getDate()}
                  </div>
                </div>
              );
            })}
          </div>
          {/* Time grid */}
          <div className="overflow-y-auto" style={{ maxHeight: '620px' }}>
            <div className="relative" style={{ display: 'grid', gridTemplateColumns: '56px repeat(7, 1fr)', height: `${totalHeight}px` }}>
              {/* Hour lines + labels */}
              {HOURS.map((hour, hi) => (
                <React.Fragment key={hour}>
                  <div className="border-r border-slate-800/40 flex items-start justify-end pr-2 relative" style={{ gridColumn: 1, gridRow: hi + 1, height: `${PX_PER_HOUR}px` }}>
                    <span className="text-[10px] mono text-slate-600 -mt-2">{hi > 0 ? fmtHour(hour) : ''}</span>
                  </div>
                  {weekDays.map((d, di) => {
                    const isToday = d.toDateString() === today.toDateString();
                    return (
                      <div key={di} className={`border-r border-b border-slate-800/20 last:border-r-0 ${isToday ? 'bg-blue-950/10' : ''}`}
                        style={{ gridColumn: di + 2, gridRow: hi + 1, height: `${PX_PER_HOUR}px` }} />
                    );
                  })}
                </React.Fragment>
              ))}

              {/* Current time red line */}
              {showNowLine && (
                <div className="absolute left-0 right-0 pointer-events-none z-20 flex items-center"
                  style={{ top: `${nowPx}px`, left: '56px' }}>
                  {todayColIndex >= 0 && (
                    <div className="absolute flex items-center"
                      style={{
                        left: `calc(${todayColIndex} * (100% / 7) - 6px)`,
                        width: `calc(100% / 7 + 6px)`
                      }}>
                      <div className="w-3 h-3 rounded-full bg-red-500 shrink-0 -ml-1.5" />
                      <div className="h-px bg-red-500 flex-1" />
                    </div>
                  )}
                </div>
              )}

              {/* Events — absolutely positioned per column */}
              {weekDays.map((d, di) => {
                const dayEvs = eventsOnDate(d);
                if (!dayEvs.length) return null;
                return (
                  <React.Fragment key={`evts-${di}`}>
                    {dayEvs.map((ev, ei) => {
                      const start = new Date(ev.startTime);
                      const end = ev.endTime ? new Date(ev.endTime) : new Date(start.getTime() + 60 * 60 * 1000);
                      const startH = start.getHours() + start.getMinutes() / 60;
                      const endH = end.getHours() + end.getMinutes() / 60;
                      const topPx = Math.max(0, (startH - gridStart) / totalHours * totalHeight);
                      const heightPx = Math.max(20, (endH - startH) / totalHours * totalHeight);
                      const isBusy = !ev.contactId;
                      // Calculate left/width based on grid column
                      const colWidth = `calc((100% - 56px) / 7)`;
                      const colLeft = `calc(56px + ${di} * (100% - 56px) / 7)`;
                      return (
                        <div key={ei} className={`absolute pointer-events-auto rounded-lg px-1.5 py-1 overflow-hidden z-10 ${isBusy ? 'bg-slate-600/50 border border-slate-500/30' : 'bg-blue-600 border border-blue-400/50 shadow-lg shadow-blue-900/30'}`}
                          style={{ top: `${topPx}px`, height: `${heightPx}px`, left: `calc(56px + ${di} * (100% - 56px) / 7 + 2px)`, width: `calc((100% - 56px) / 7 - 4px)` }}>
                          <div className={`text-[10px] font-bold leading-tight truncate ${isBusy ? 'text-slate-400' : 'text-white'}`}>
                            {isBusy ? ev.title || 'Busy' : ev.title}
                          </div>
                          {heightPx > 28 && (
                            <div className={`text-[9px] truncate ${isBusy ? 'text-slate-500' : 'text-blue-200'}`}>
                              {isBusy ? `${fmtTime(ev.startTime)} – ${ev.endTime ? fmtTime(ev.endTime) : ''}` : `${fmtTime(ev.startTime)}${ev.endTime ? ' – ' + fmtTime(ev.endTime) : ''}`}
                            </div>
                          )}
                          {heightPx > 44 && !isBusy && ev.contactName && (
                            <div className="text-[9px] text-blue-200 truncate">{ev.contactName}</div>
                          )}
                        </div>
                      );
                    })}
                  </React.Fragment>
                );
              })}
            </div>
          </div>
        </div>
      ) : (
        /* ===== MONTH VIEW ===== */
        <div className="bg-slate-900/40 border border-slate-800/60 rounded-2xl overflow-hidden">
          <div className="grid grid-cols-7 border-b border-slate-800/50">
            {dayNames.map(d => (
              <div key={d} className="py-3 text-center text-[10px] mono font-bold text-slate-600 uppercase tracking-wider">{d}</div>
            ))}
          </div>
          <div className="grid grid-cols-7">
            {Array.from({ length: firstDay }).map((_, i) => (
              <div key={`empty-${i}`} className="h-28 border-b border-r border-slate-800/30" />
            ))}
            {Array.from({ length: daysInMonth }).map((_, i) => {
              const day = i + 1;
              const dayEvents = eventsOnDay(day);
              const isToday = today.getDate() === day && today.getMonth() === month && today.getFullYear() === year;
              return (
                <div key={day} className={`h-28 border-b border-r border-slate-800/30 p-2 cal-day transition-colors ${isToday ? 'today' : ''} ${dayEvents.length > 0 ? 'has-event' : ''}`}>
                  <div className={`text-xs font-bold mb-1.5 w-6 h-6 flex items-center justify-center rounded-full mono
                    ${isToday ? 'bg-blue-600 text-white' : 'text-slate-500'}`}>{day}</div>
                  {dayEvents.slice(0, 3).map((ev, ei) => {
                    const isBusy = !ev.contactId;
                    return (
                      <div key={ei} className={`text-[10px] font-bold rounded px-1.5 py-0.5 mb-0.5 truncate leading-snug ${isBusy ? 'bg-slate-700/60 text-slate-400' : 'bg-blue-600 text-white'}`}>
                        {isBusy ? (ev.title || 'Busy') : `${fmtTime(ev.startTime)} ${ev.title}`}
                      </div>
                    );
                  })}
                  {dayEvents.length > 3 && <div className="text-[9px] mono text-slate-500 pl-1">+{dayEvents.length - 3} more</div>}
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Upcoming Appointments list — real appointments only */}
      {calEvents.filter(e => e.contactId).length > 0 && (
        <div className="bg-slate-900/40 border border-slate-800/60 rounded-2xl overflow-hidden">
          <div className="px-6 py-4 border-b border-slate-800/50 font-bold text-white text-sm flex items-center justify-between">
            <span>Upcoming Appointments</span>
            <span className="text-xs mono text-slate-500">{calEvents.filter(e => e.contactId).length} booked</span>
          </div>
          <div className="divide-y divide-slate-800/40">
            {calEvents
              .filter(ev => ev.contactId && new Date(ev.startTime) >= new Date(today.setHours(0,0,0,0)))
              .sort((a, b) => new Date(a.startTime) - new Date(b.startTime))
              .slice(0, 10)
              .map(ev => (
                <div key={ev.id} className="flex items-center gap-4 px-6 py-4">
                  <div className="p-2.5 bg-blue-600/10 border border-blue-500/20 rounded-xl shrink-0">
                    <Icon name="calendar-check" size={15} className="text-blue-400" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="font-bold text-white text-sm truncate">{ev.title}</div>
                    <div className="text-xs text-slate-500 truncate">{ev.contactName}</div>
                  </div>
                  <div className="text-right shrink-0">
                    <div className="text-xs font-bold text-white">{fmtDate(ev.startTime)}</div>
                    <div className="text-[10px] mono text-slate-500">{fmtTime(ev.startTime)}{ev.endTime ? ` – ${fmtTime(ev.endTime)}` : ''}</div>
                  </div>
                  <span className={`text-[10px] mono uppercase px-2 py-0.5 rounded-lg font-bold shrink-0 ${ev.status === 'confirmed' ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-slate-800 text-slate-500'}`}>{ev.status || 'scheduled'}</span>
                </div>
              ))}
          </div>
        </div>
      )}
    </div>
  );
};
