/* calendar.jsx — Community Events Calendar (live data from /api/events) */
const CAT_COLORS = {
  Festival:'#c4612e', Market:'#cf9521', Community:'#5c7461', Music:'#9a3b4f',
  Family:'#2f6f7e', Outdoors:'#3f7d54', Other:'#7a5a8a',
};

function Calendar() {
  const { go } = useFF();
  const [events, setEvents]  = React.useState(null); // null = loading
  const [cat,    setCat]     = React.useState('All');
  const [selDay, setSelDay]  = React.useState(null);
  const [viewMonth, setViewMonth] = React.useState(() => {
    const now = new Date();
    return { year: now.getFullYear(), month: now.getMonth() };
  });

  React.useEffect(() => {
    fetch('/api/events')
      .then(r => r.ok ? r.json() : [])
      .then(data => setEvents(Array.isArray(data) ? data : []))
      .catch(() => setEvents([]));
  }, []);

  if (events === null) {
    return (
      <div>
        <PageBanner eyebrow="What's on" title="Events Calendar"
          sub="Markets, music, and community gatherings — the rhythm of a Prince George summer." />
        <div className="page-wrap" style={{ padding:'40px 28px', color:'var(--ink-faint)', fontFamily:'var(--serif)', fontStyle:'italic', fontSize:18 }}>
          Loading events…
        </div>
      </div>
    );
  }

  const cats = ['All', ...Array.from(new Set(events.map(e => e.category).filter(Boolean)))];
  const evAll = cat === 'All' ? events : events.filter(e => e.category === cat);

  // build month calendar grid
  const { year, month } = viewMonth;
  const first = new Date(year, month, 1).getDay();
  const dim   = new Date(year, month + 1, 0).getDate();
  const cells = [];
  for (let i = 0; i < first; i++) cells.push(null);
  for (let d = 1; d <= dim; d++) cells.push(d);
  while (cells.length % 7 !== 0) cells.push(null);

  // index events by day-of-month for this view month
  const evByDay = {};
  evAll.forEach(e => {
    if (!e.date) return;
    const d = new Date(e.date);
    if (isNaN(d.getTime())) return;
    if (d.getFullYear() !== year || d.getMonth() !== month) return;
    const day = d.getDate();
    (evByDay[day] = evByDay[day] || []).push(e);
  });

  const listEvents = selDay ? (evByDay[selDay] || []) : evAll;
  const monthLabel = new Date(year, month, 1).toLocaleDateString('en-CA', { month:'long', year:'numeric' });

  const prevMonth = () => setViewMonth(v => {
    const d = new Date(v.year, v.month - 1, 1);
    return { year: d.getFullYear(), month: d.getMonth() };
  });
  const nextMonth = () => setViewMonth(v => {
    const d = new Date(v.year, v.month + 1, 1);
    return { year: d.getFullYear(), month: d.getMonth() };
  });

  return (
    <div>
      <PageBanner eyebrow="What's on" title="Events Calendar"
        sub="Markets, music, and community gatherings — the rhythm of a Prince George summer." />

      <div className="page-wrap" style={{ padding:'18px 28px 0', display:'flex', gap:8, flexWrap:'wrap' }}>
        {cats.map(c => (
          <button key={c} onClick={() => { setCat(c); setSelDay(null); }} className="chip"
            style={{ cursor:'pointer', fontSize:13.5, padding:'7px 14px',
              background: cat===c ? (CAT_COLORS[c]||'var(--spruce)') : 'var(--paper-3)',
              color: cat===c ? '#fff8ee' : 'var(--ink-soft)', borderColor:'transparent' }}>
            {c !== 'All' && <span style={{ width:8, height:8, borderRadius:'50%', background: cat===c ? '#fff8ee' : (CAT_COLORS[c]||'#888'), display:'inline-block' }}/>}
            {c}
          </button>
        ))}
      </div>

      <div className="page-wrap cal-split" style={{ padding:'26px 28px 0', display:'grid', gridTemplateColumns:'1.3fr 1fr', gap:30, alignItems:'start' }}>
        {/* month grid */}
        <div className="card" style={{ padding:'22px 24px' }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16 }}>
            <button onClick={prevMonth} style={{ background:'none', border:'none', color:'var(--ink-soft)', padding:'4px 8px', borderRadius:8, cursor:'pointer' }}>‹</button>
            <h2 style={{ fontSize:24 }}>{monthLabel}</h2>
            <button onClick={nextMonth} style={{ background:'none', border:'none', color:'var(--ink-soft)', padding:'4px 8px', borderRadius:8, cursor:'pointer' }}>›</button>
          </div>
          {selDay && <button onClick={() => setSelDay(null)} style={{ display:'block', marginBottom:10, background:'none', border:'none', color:'var(--accent)', fontWeight:600, fontSize:14 }}>Show all</button>}
          <div style={{ display:'grid', gridTemplateColumns:'repeat(7,1fr)', gap:6, fontSize:11.5, fontWeight:700, letterSpacing:'.08em', color:'var(--ink-faint)', textTransform:'uppercase', marginBottom:6 }}>
            {['Sun','Mon','Tue','Wed','Thu','Fri','Sat'].map(d => <div key={d} style={{ textAlign:'center' }}>{d}</div>)}
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(7,1fr)', gap:6 }}>
            {cells.map((d, i) => {
              const evs = d ? evByDay[d] : null;
              const has = evs && evs.length;
              const active = selDay === d;
              return (
                <button key={i} disabled={!d} onClick={() => has && setSelDay(active ? null : d)}
                  style={{ aspectRatio:'1', borderRadius:10, border:'1.5px solid '+(active?'var(--accent)':'transparent'),
                    background: d ? (active ? 'var(--accent)' : (has ? 'var(--paper-2)' : 'transparent')) : 'transparent',
                    cursor: has ? 'pointer' : 'default', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:4,
                    color: active ? '#fff8ee' : 'var(--ink)', position:'relative', padding:0 }}>
                  {d && <span style={{ fontWeight: has?700:500, fontSize:15 }}>{d}</span>}
                  {has && <span style={{ display:'flex', gap:3 }}>
                    {evs.slice(0,3).map((e,j) => <span key={j} style={{ width:5, height:5, borderRadius:'50%',
                      background: active ? '#fff8ee' : (CAT_COLORS[e.category]||'var(--accent)') }}/>)}
                  </span>}
                </button>
              );
            })}
          </div>
          {events.length > 0 && (
            <div style={{ marginTop:18, paddingTop:16, borderTop:'1.5px solid var(--line)', display:'flex', gap:14, flexWrap:'wrap' }}>
              {Object.entries(CAT_COLORS).filter(([c]) => events.some(e => e.category === c)).map(([c, col]) => (
                <span key={c} style={{ display:'inline-flex', gap:6, alignItems:'center', fontSize:12.5, color:'var(--ink-soft)' }}>
                  <span style={{ width:8, height:8, borderRadius:'50%', background:col }}/>{c}
                </span>
              ))}
            </div>
          )}
        </div>

        {/* list */}
        <div>
          <h3 style={{ fontSize:19, marginBottom:14 }}>{selDay ? `${monthLabel.split(' ')[0]} ${selDay}` : 'Upcoming events'}</h3>
          <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
            {listEvents.length === 0 && (
              <div style={{ color:'var(--ink-faint)', fontFamily:'var(--serif)', fontStyle:'italic', fontSize:16 }}>
                No events listed yet — know of something happening? Add it below.
              </div>
            )}
            {listEvents.map((e, i) => (
              <div key={e.id||i} className="card" style={{ padding:'15px 17px', borderLeft:`4px solid ${CAT_COLORS[e.category]||'var(--accent)'}` }}>
                <div style={{ display:'flex', justifyContent:'space-between', gap:10, alignItems:'baseline' }}>
                  <div style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:17 }}>{e.title}</div>
                  {e.date && <span style={{ fontWeight:800, color:'var(--ink-faint)', fontSize:13, whiteSpace:'nowrap' }}>
                    {new Date(e.date).toLocaleDateString('en-CA', { month:'short', day:'numeric' })}
                  </span>}
                </div>
                {e.description && <p style={{ color:'var(--ink-soft)', fontSize:14, margin:'6px 0 10px' }}>{e.description}</p>}
                <div style={{ display:'flex', gap:14, fontSize:13, color:'var(--ink-soft)', flexWrap:'wrap' }}>
                  {e.start && <span style={{ display:'inline-flex', gap:5, alignItems:'center' }}><IconClock size={14}/>{e.start}{e.end ? ` – ${e.end}` : ''}</span>}
                  {e.venue && <span style={{ display:'inline-flex', gap:5, alignItems:'center' }}><IconPin size={14}/>{e.venue}</span>}
                  {e.link && <a href={e.link} target="_blank" rel="noopener" style={{ display:'inline-flex', gap:5, alignItems:'center', color:'var(--accent)' }}><IconGlobe size={14}/>More info</a>}
                </div>
                {e.photos && e.photos.length > 0 && <PhotoCarousel photos={e.photos} height={180} />}
              </div>
            ))}
          </div>
          <button className="btn btn-dark" onClick={() => go('submit')} style={{ marginTop:18 }}><IconPlus size={16}/> Add an event</button>
        </div>
      </div>
      <div style={{ height:40 }}/>
    </div>
  );
}

window.Pages = window.Pages || {};
window.Pages.Calendar = Calendar;
