// Calendar view: month grid with task pills colored by project.
const CALIcons = window.Icons;
const { toDateKey: calDateKey } = window.PMStore;

const DAY_NAMES = ['Pzt','Sal','Çar','Per','Cum','Cmt','Paz'];
const MONTH_NAMES = ['Ocak','Şubat','Mart','Nisan','Mayıs','Haziran','Temmuz','Ağustos','Eylül','Ekim','Kasım','Aralık'];

function CalendarView({ state, onSelectTask, query }) {
  const [cursor, setCursor] = React.useState(() => {
    const d = new Date(); d.setDate(1);
    return d;
  });

  const projById = Object.fromEntries(state.projects.map(p => [p.id, p]));
  const tagById = Object.fromEntries(state.tags.map(t => [t.id, t]));

  const tasks = state.tasks.filter(t => {
    if (!t.due) return false;
    if (!query) return true;
    const q = query.toLowerCase();
    return t.title.toLowerCase().includes(q) || t.tags.some(tid => (tagById[tid]?.name || '').toLowerCase().includes(q));
  });

  const year = cursor.getFullYear();
  const month = cursor.getMonth();
  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  // Monday-start grid
  let startWeekday = firstDay.getDay(); // 0=Sun
  startWeekday = (startWeekday + 6) % 7; // 0=Mon
  const daysInMonth = lastDay.getDate();
  const totalCells = Math.ceil((startWeekday + daysInMonth) / 7) * 7;

  const today = new Date(); today.setHours(0,0,0,0);

  const cells = [];
  for (let i = 0; i < totalCells; i++) {
    const dayOffset = i - startWeekday;
    const date = new Date(year, month, 1 + dayOffset);
    const inMonth = date.getMonth() === month;
    const isoStr = calDateKey(date);
    const dayTasks = tasks.filter(t => t.due === isoStr);
    cells.push({ date, inMonth, isToday: date.getTime() === today.getTime(), tasks: dayTasks });
  }

  const goToToday = () => {
    const d = new Date(); d.setDate(1);
    setCursor(d);
  };

  return (
    <div className="cal-wrap">
      <div className="cal-header">
        <div className="cal-title">{MONTH_NAMES[month]} {year}</div>
        <div className="cal-nav">
          <button className="icon-btn" onClick={() => setCursor(new Date(year, month - 1, 1))}>
            <CALIcons.ChevronLeft size={16} />
          </button>
          <button className="icon-btn" onClick={() => setCursor(new Date(year, month + 1, 1))}>
            <CALIcons.ChevronRight size={16} />
          </button>
        </div>
        <button className="btn btn-ghost btn-sm" onClick={goToToday}>Bugün</button>
        <div style={{ flex: 1 }} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: 12, color: 'var(--text-muted)' }}>
          <span>Proje renkleri:</span>
          {state.projects.map(p => (
            <span key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
              <span className="project-dot" style={{ background: p.color }} />
              <span>{p.name}</span>
            </span>
          ))}
        </div>
      </div>

      <div className="cal-grid">
        {DAY_NAMES.map(n => <div key={n} className="cal-day-name">{n}</div>)}
        {cells.map((c, i) => (
          <div key={i} className={`cal-cell ${!c.inMonth ? 'muted' : ''} ${c.isToday ? 'today' : ''}`}>
            <div className="cal-date">{c.date.getDate()}</div>
            {c.tasks.slice(0, 4).map(t => {
              const proj = projById[t.projectId];
              return (
                <div
                  key={t.id}
                  className="cal-event"
                  style={{
                    background: (proj?.color || '#10b981') + '1f',
                    color: proj?.color || 'var(--text)',
                    borderLeftColor: proj?.color || 'var(--accent)',
                    textDecoration: t.status === 'done' ? 'line-through' : 'none',
                    opacity: t.status === 'done' ? 0.55 : 1,
                  }}
                  onClick={() => onSelectTask(t.id)}
                  title={t.title}
                >
                  {t.title}
                </div>
              );
            })}
            {c.tasks.length > 4 && (
              <div style={{ fontSize: 10.5, color: 'var(--text-faint)', fontWeight: 600, padding: '0 6px' }}>
                +{c.tasks.length - 4} daha
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

window.CalendarView = CalendarView;
