// Calendar.jsx — Monthly calendar with tasks
(function () {
  const { useState } = React;

  const MONTHS = ['Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec','Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień'];
  const DOW = ['Pn','Wt','Śr','Cz','Pt','Sb','Nd'];
  const priorityColor = { high:'#EF4444', medium:'#F59E0B', low:'#22C55E' };

  window.Calendar = function Calendar({ tasks, setTasks }) {
    const [year,  setYear]  = useState(2026);
    const [month, setMonth] = useState(6); // lipiec
    const [selDay, setSelDay] = useState(21);
    const [gcalConnected, setGcalConnected] = useState(false);
    const [gcalSyncing, setGcalSyncing] = useState(false);

    const connectGcal = () => {
      if (gcalConnected) { setGcalConnected(false); return; }
      setGcalSyncing(true);
      setTimeout(() => { setGcalSyncing(false); setGcalConnected(true); }, 1200);
    };

    const firstDow  = (new Date(year, month, 1).getDay() + 6) % 7; // Mon=0
    const daysInMon = new Date(year, month + 1, 0).getDate();
    const today     = { y:2026, m:6, d:21 };

    const prevMonth = () => { if (month===0){setYear(y=>y-1);setMonth(11);}else setMonth(m=>m-1); };
    const nextMonth = () => { if (month===11){setYear(y=>y+1);setMonth(0);}else setMonth(m=>m+1); };

    const pad = n => String(n).padStart(2,'0');
    const dateStr = d => `${year}-${pad(month+1)}-${pad(d)}`;
    const tasksForDay = d => tasks.filter(t => t.due === dateStr(d));

    const selDateStr = dateStr(selDay);
    const selTasks   = tasks.filter(t => t.due === selDateStr);
    const toggle = id => setTasks(p => p.map(t => t.id===id ? {...t,done:!t.done} : t));

    const monthPrefix = `${year}-${pad(month+1)}`;
    const todayStr    = `${today.y}-${pad(today.m+1)}-${pad(today.d)}`;

    const cells = [...Array(firstDow).fill(null), ...Array.from({length:daysInMon},(_,i)=>i+1)];

    return (
      <div style={{ display:'grid', gridTemplateColumns:'1fr 300px', gap:20, alignItems:'start' }}>

        {/* ── Calendar grid ── */}
        <div className="glass-card" style={{ padding:28 }}>
          {/* Google Calendar sync bar */}
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:20, padding:'10px 14px', borderRadius:12, background: gcalConnected ? 'rgba(34,197,94,.1)' : 'var(--bg1)', border:`1px solid ${gcalConnected ? 'rgba(34,197,94,.3)' : 'var(--bdr)'}` }}>
            <div style={{ display:'flex', alignItems:'center', gap:10 }}>
              <div style={{ width:8, height:8, borderRadius:'50%', background: gcalConnected ? '#22C55E' : 'var(--t3)', boxShadow: gcalConnected ? '0 0 8px #22C55E99' : 'none' }} />
              <span style={{ fontSize:12, color:'var(--t2)' }}>
                {gcalSyncing ? 'Łączenie z Kalendarzem Google…' : gcalConnected ? 'Zsynchronizowano z Kalendarzem Google' : 'Kalendarz Google niepołączony'}
              </span>
            </div>
            <button onClick={connectGcal} disabled={gcalSyncing} style={{
              padding:'6px 14px', borderRadius:9, border: gcalConnected ? '1px solid var(--bdr)' : 'none',
              background: gcalConnected ? 'var(--bg1)' : 'linear-gradient(135deg,#7C5CFF,#4DA3FF)',
              color: gcalConnected ? 'var(--t1)' : '#fff', fontWeight:600, fontSize:12,
              cursor: gcalSyncing ? 'wait' : 'pointer', opacity: gcalSyncing ? .6 : 1,
            }}>{gcalConnected ? 'Rozłącz' : 'Połącz z Google'}</button>
          </div>
          {/* Nav */}
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:28 }}>
            <button onClick={prevMonth} style={{ width:34,height:34,borderRadius:9,border:'1px solid var(--bdr)',background:'var(--bg1)',color:'var(--t2)',cursor:'pointer',fontSize:18,display:'flex',alignItems:'center',justifyContent:'center',outline:'none' }}
              onMouseEnter={e=>e.currentTarget.style.background='var(--bg2)'}
              onMouseLeave={e=>e.currentTarget.style.background='var(--bg1)'}
            >‹</button>
            <div>
              <div style={{ fontSize:18,fontWeight:800,color:'var(--t1)',textAlign:'center',letterSpacing:-0.5 }}>{MONTHS[month]}</div>
              <div style={{ fontSize:12,color:'var(--t3)',textAlign:'center' }}>{year}</div>
            </div>
            <button onClick={nextMonth} style={{ width:34,height:34,borderRadius:9,border:'1px solid var(--bdr)',background:'var(--bg1)',color:'var(--t2)',cursor:'pointer',fontSize:18,display:'flex',alignItems:'center',justifyContent:'center',outline:'none' }}
              onMouseEnter={e=>e.currentTarget.style.background='var(--bg2)'}
              onMouseLeave={e=>e.currentTarget.style.background='var(--bg1)'}
            >›</button>
          </div>

          {/* DOW headers */}
          <div style={{ display:'grid', gridTemplateColumns:'repeat(7,1fr)', gap:4, marginBottom:8 }}>
            {DOW.map(d => (
              <div key={d} style={{ textAlign:'center',fontSize:11,fontWeight:700,color:'var(--t3)',padding:'4px 0',letterSpacing:0.8,textTransform:'uppercase' }}>{d}</div>
            ))}
          </div>

          {/* Day cells */}
          <div style={{ display:'grid', gridTemplateColumns:'repeat(7,1fr)', gap:4 }}>
            {cells.map((day, i) => {
              if (!day) return <div key={i} />;
              const dt = tasksForDay(day);
              const isToday = day===today.d && month===today.m && year===today.y;
              const isSel   = day===selDay;
              const hasTasks = dt.length > 0;
              return (
                <div key={i} onClick={() => setSelDay(day)} style={{
                  aspectRatio:'1',borderRadius:12,cursor:'pointer',
                  display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',gap:4,
                  background: isSel ? 'linear-gradient(135deg,rgba(124,92,255,.3),rgba(77,163,255,.2))' : isToday ? 'rgba(124,92,255,.12)' : 'transparent',
                  border: isSel ? '1.5px solid rgba(124,92,255,.55)' : isToday ? '1.5px solid rgba(124,92,255,.28)' : '1.5px solid transparent',
                  boxShadow: isSel ? '0 0 16px rgba(124,92,255,.2)' : 'none',
                  transition:'all .15s',
                }}
                onMouseEnter={e=>{ if(!isSel) e.currentTarget.style.background='var(--bg-hover)'; }}
                onMouseLeave={e=>{ if(!isSel) e.currentTarget.style.background=isToday?'rgba(124,92,255,.12)':'transparent'; }}
                >
                  <span style={{ fontSize:13,fontWeight:isSel||isToday?700:400, color:isSel?'#c4acff':isToday?'var(--t1)':'var(--t2)', lineHeight:1 }}>{day}</span>
                  {hasTasks && (
                    <div style={{ display:'flex',gap:2 }}>
                      {dt.slice(0,3).map((t,ti) => (
                        <div key={ti} style={{ width:5,height:5,borderRadius:'50%', background:priorityColor[t.priority]||'#7C5CFF', opacity:t.done?0.25:1 }} />
                      ))}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* ── Right panel ── */}
        <div style={{ display:'flex',flexDirection:'column',gap:12 }}>

          {/* Selected day header */}
          <div className="glass-card" style={{ padding:20 }}>
            <div style={{ fontSize:15,fontWeight:700,color:'var(--t1)',marginBottom:2, display:'flex', alignItems:'center', gap:8 }}>
              {selDay} {MONTHS[month]} {year}
              {gcalConnected && <span style={{ fontSize:10, fontWeight:600, color:'#22C55E', background:'rgba(34,197,94,.12)', padding:'2px 7px', borderRadius:99 }}>Google ✓</span>}
            </div>
            <div style={{ fontSize:12,color:'var(--t3)',marginBottom:16 }}>
              {selTasks.length===0 ? 'Brak zadań tego dnia' : `${selTasks.length} ${selTasks.length===1?'zadanie':selTasks.length<5?'zadania':'zadań'}`}
            </div>

            {selTasks.length===0 ? (
              <div style={{ textAlign:'center',padding:'24px 0',color:'var(--t3)',fontSize:13 }}>
                <div style={{ fontSize:36,marginBottom:8 }}>📅</div>
                Wolny dzień!
              </div>
            ) : (
              <div style={{ display:'flex',flexDirection:'column',gap:8 }}>
                {selTasks.map(t => {
                  const pc = priorityColor[t.priority];
                  return (
                    <div key={t.id} onClick={() => toggle(t.id)} style={{
                      display:'flex',alignItems:'flex-start',gap:10,padding:'10px 12px',
                      borderRadius:10,cursor:'pointer',transition:'background .15s',
                      background:'var(--bg1)',border:'1px solid var(--bdr)',
                      borderLeft:`3px solid ${t.done?'var(--bdr)':pc}`,
                      opacity:t.done?0.5:1,
                    }}
                    onMouseEnter={e=>e.currentTarget.style.background='var(--bg2)'}
                    onMouseLeave={e=>e.currentTarget.style.background='var(--bg1)'}
                    >
                      <div style={{ width:16,height:16,borderRadius:5,flexShrink:0,marginTop:1, border:t.done?'none':`1.5px solid ${pc}`, background:t.done?'#22C55E':'transparent', display:'flex',alignItems:'center',justifyContent:'center',transition:'all .15s' }}>
                        {t.done && <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3.5" strokeLinecap="round"><path d="M20 6L9 17l-5-5"/></svg>}
                      </div>
                      <span style={{ fontSize:13,color:'var(--t1)',flex:1,textDecoration:t.done?'line-through':'none',lineHeight:1.45 }}>{t.text}</span>
                    </div>
                  );
                })}
              </div>
            )}
          </div>

          {/* Month summary */}
          <div className="glass-card" style={{ padding:20 }}>
            <div style={{ fontSize:13,fontWeight:700,color:'var(--t1)',marginBottom:14 }}>Podsumowanie miesiąca</div>
            {[
              { label:'Zaplanowane', val: tasks.filter(t=>t.due.startsWith(monthPrefix)).length, color:'#7C5CFF' },
              { label:'Ukończone',   val: tasks.filter(t=>t.due.startsWith(monthPrefix)&&t.done).length, color:'#22C55E' },
              { label:'Zaległe',     val: tasks.filter(t=>t.due<todayStr&&!t.done).length, color:'#EF4444' },
            ].map((s,i,a) => (
              <div key={s.label} style={{ display:'flex',justifyContent:'space-between',alignItems:'center',padding:'8px 0',borderBottom:i<a.length-1?'1px solid var(--bdr)':'none' }}>
                <div style={{ display:'flex',alignItems:'center',gap:8 }}>
                  <div style={{ width:6,height:6,borderRadius:'50%',background:s.color }} />
                  <span style={{ fontSize:12,color:'var(--t2)' }}>{s.label}</span>
                </div>
                <span style={{ fontSize:15,fontWeight:800,color:s.color }}>{s.val}</span>
              </div>
            ))}
          </div>

          {/* Upcoming this week */}
          <div className="glass-card" style={{ padding:20 }}>
            <div style={{ fontSize:13,fontWeight:700,color:'var(--t1)',marginBottom:12 }}>Najbliższe 7 dni</div>
            {tasks.filter(t => {
              const d = new Date(t.due); const today7 = new Date('2026-07-21'); today7.setDate(today7.getDate()+7);
              return d >= new Date('2026-07-21') && d <= today7 && !t.done;
            }).slice(0,4).map((t,i,a) => (
              <div key={t.id} style={{ display:'flex',alignItems:'center',gap:8,padding:'7px 0',borderBottom:i<a.length-1?'1px solid var(--bdr)':'none' }}>
                <div style={{ width:6,height:6,borderRadius:2,background:priorityColor[t.priority],flexShrink:0 }} />
                <span style={{ fontSize:12,color:'var(--t1)',flex:1,lineHeight:1.4 }}>{t.text}</span>
                <span style={{ fontSize:10,color:'var(--t3)',whiteSpace:'nowrap' }}>{t.due.slice(8)}.{t.due.slice(5,7)}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  };
})();
