// Calendar — Full month view with waste collection + Google Calendar prep

function CalendarScreen({ store, cfg }) {
  const { events, wasteCalendar, wasteConfig } = store;

  // Current viewed month
  const [viewDate, setViewDate] = React.useState(() => {
    const d = new Date(); d.setDate(1); d.setHours(0,0,0,0); return d;
  });
  const [selDate, setSelDate] = React.useState(() => new Date().toISOString().slice(0, 10));
  const [showComposer, setShowComposer] = React.useState(false);
  const [editingId, setEditingId] = React.useState(null);
  const [showWasteSetup, setShowWasteSetup] = React.useState(false);

  // Month navigation
  const prevMonth = () => setViewDate(d => { const n = new Date(d); n.setMonth(n.getMonth() - 1); return n; });
  const nextMonth = () => setViewDate(d => { const n = new Date(d); n.setMonth(n.getMonth() + 1); return n; });
  const goToday = () => { const d = new Date(); d.setDate(1); d.setHours(0,0,0,0); setViewDate(d); setSelDate(new Date().toISOString().slice(0, 10)); };

  const monthLabel = viewDate.toLocaleDateString('en', { month: 'long', year: 'numeric' });

  // Build calendar grid
  const year = viewDate.getFullYear();
  const month = viewDate.getMonth();
  const firstDay = new Date(year, month, 1).getDay(); // 0=Sun
  const startOffset = (firstDay + 6) % 7; // Mon=0
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const todayIso = new Date().toISOString().slice(0, 10);

  const calendarDays = [];
  // Fill leading days from prev month
  const prevMonthDays = new Date(year, month, 0).getDate();
  for (let i = startOffset - 1; i >= 0; i--) {
    const d = new Date(year, month - 1, prevMonthDays - i);
    calendarDays.push({ date: d.getDate(), iso: d.toISOString().slice(0, 10), outside: true });
  }
  // Current month days
  for (let i = 1; i <= daysInMonth; i++) {
    const d = new Date(year, month, i);
    calendarDays.push({ date: i, iso: d.toISOString().slice(0, 10), outside: false });
  }
  // Fill trailing days
  const trailing = 42 - calendarDays.length;
  for (let i = 1; i <= trailing; i++) {
    const d = new Date(year, month + 1, i);
    calendarDays.push({ date: i, iso: d.toISOString().slice(0, 10), outside: true });
  }

  // Index events and waste by date for quick lookup
  const eventsByDate = React.useMemo(() => {
    const map = {};
    for (const e of events) {
      if (!e.date) continue;
      (map[e.date] = map[e.date] || []).push(e);
    }
    return map;
  }, [events]);

  const wasteByDate = React.useMemo(() => {
    const map = {};
    for (const w of wasteCalendar) {
      if (!w.date) continue;
      (map[w.date] = map[w.date] || []).push(w);
    }
    return map;
  }, [wasteCalendar]);

  const selEvents = eventsByDate[selDate] || [];
  const selWaste = wasteByDate[selDate] || [];

  // Draft for event composer
  const [draft, setDraft] = React.useState({
    title: '', date: todayIso, time: '09:00', end_time: '10:00', category: 'Family', color: '#C9562E',
  });

  const openNew = () => {
    setEditingId(null);
    setDraft({ title: '', date: selDate, time: '09:00', end_time: '10:00', category: 'Family', color: '#C9562E' });
    setShowComposer(true);
  };

  const openEdit = (ev) => {
    setEditingId(ev.id);
    setDraft({ title: ev.title, date: ev.date, time: ev.time || '09:00', end_time: ev.end_time || '', category: ev.category || 'Family', color: ev.color || '#C9562E' });
    setShowComposer(true);
  };

  const saveEvent = () => {
    const title = (draft.title || '').trim();
    if (!title || !draft.date) return;
    const payload = { title, date: draft.date, time: draft.time || '', end_time: draft.end_time || '', color: draft.color || '#C9562E', description: draft.category || '', notify_before_minutes: 60 };
    if (editingId) store.updateEvent(editingId, payload);
    else store.addEvent(payload);
    setShowComposer(false);
    setEditingId(null);
    setDraft(d => ({ ...d, title: '' }));
  };

  // Selected day label
  const selDateObj = new Date(selDate + 'T00:00:00');
  const selDayLabel = selDateObj.toLocaleDateString('en', { weekday: 'long', month: 'long', day: 'numeric' });

  return (
    <div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <TopBar title="Calendar" subtitle={monthLabel} trailing={
        <div style={{ display: 'flex', gap: 8 }}>
          {!wasteConfig && (
            <button onClick={() => setShowWasteSetup(true)} className="press" style={{ width: 40, height: 40, borderRadius: 999, background: 'var(--hh-surface)', border: '1px solid var(--hh-line-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="settings" size={18}/>
            </button>
          )}
          <button onClick={openNew} className="press" style={{ width: 40, height: 40, borderRadius: 999, background: 'var(--hh-surface)', border: '1px solid var(--hh-line-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="plus" size={18}/>
          </button>
        </div>
      }/>

      {/* Waste address setup sheet */}
      {showWasteSetup && <WasteSetupSheet store={store} onClose={() => setShowWasteSetup(false)} />}

      <div className="hh-scroll" style={{ flex: 1, minHeight: 0, overflow: 'auto' }}>
        {/* Event composer */}
        {showComposer && (
          <div style={{ padding: '0 20px 10px' }}>
            <div className="hh-card" style={{ padding: 12, display: 'grid', gap: 8 }}>
              <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                <input
                  value={draft.title}
                  onChange={(e) => setDraft(d => ({ ...d, title: e.target.value }))}
                  placeholder="Event title"
                  style={{ flex: 1, height: 40, borderRadius: 10, border: '1px solid var(--hh-line-soft)', padding: '0 10px', background: 'var(--hh-surface-2)', color: 'var(--hh-ink)', outline: 'none' }}
                />
                <button onClick={() => { setShowComposer(false); setEditingId(null); }} className="press" style={{ width: 34, height: 34, borderRadius: 8, background: 'var(--hh-surface-2)', border: '1px solid var(--hh-line-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Icon name="x" size={14} color="var(--hh-ink-mute)"/>
                </button>
              </div>
              <div style={{ display: 'grid', gap: 8, gridTemplateColumns: '1fr 1fr 1fr' }}>
                <input type="date" value={draft.date} onChange={(e) => setDraft(d => ({ ...d, date: e.target.value }))} style={{ height: 38, borderRadius: 10, border: '1px solid var(--hh-line-soft)', padding: '0 8px', background: 'var(--hh-surface-2)', color: 'var(--hh-ink)', outline: 'none' }} />
                <input type="time" value={draft.time} onChange={(e) => setDraft(d => ({ ...d, time: e.target.value }))} style={{ height: 38, borderRadius: 10, border: '1px solid var(--hh-line-soft)', padding: '0 8px', background: 'var(--hh-surface-2)', color: 'var(--hh-ink)', outline: 'none' }} />
                <input type="time" value={draft.end_time} onChange={(e) => setDraft(d => ({ ...d, end_time: e.target.value }))} style={{ height: 38, borderRadius: 10, border: '1px solid var(--hh-line-soft)', padding: '0 8px', background: 'var(--hh-surface-2)', color: 'var(--hh-ink)', outline: 'none' }} />
              </div>
              <div style={{ display: 'grid', gap: 8, gridTemplateColumns: '1fr auto auto auto' }}>
                <input
                  value={draft.category}
                  onChange={(e) => setDraft(d => ({ ...d, category: e.target.value }))}
                  placeholder="Category"
                  style={{ height: 38, borderRadius: 10, border: '1px solid var(--hh-line-soft)', padding: '0 10px', background: 'var(--hh-surface-2)', color: 'var(--hh-ink)', outline: 'none' }}
                />
                <input type="color" value={draft.color} onChange={(e) => setDraft(d => ({ ...d, color: e.target.value }))} style={{ width: 42, height: 38, borderRadius: 10, border: '1px solid var(--hh-line-soft)', background: 'var(--hh-surface-2)', cursor: 'pointer' }} />
                {editingId && (
                  <button onClick={() => { store.removeEvent(editingId); setShowComposer(false); setEditingId(null); }} className="press" style={{ height: 38, borderRadius: 10, background: '#fee2e2', color: '#ef4444', padding: '0 10px', fontSize: 12, fontWeight: 600 }}>Del</button>
                )}
                <button onClick={saveEvent} className="press" style={{ height: 38, borderRadius: 10, background: 'var(--hh-accent)', color: '#fff', padding: '0 12px', fontSize: 12, fontWeight: 600 }}>{editingId ? 'Update' : 'Save'}</button>
              </div>
            </div>
          </div>
        )}

        {/* Month nav */}
        <div style={{ padding: '0 20px 8px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <button onClick={prevMonth} className="press" style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--hh-surface)', border: '1px solid var(--hh-line-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="chevronLeft" size={16}/>
          </button>
          <button onClick={goToday} className="press" style={{ fontSize: 12, fontWeight: 600, color: 'var(--hh-accent)', background: 'none', border: 'none' }}>Today</button>
          <button onClick={nextMonth} className="press" style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--hh-surface)', border: '1px solid var(--hh-line-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="chevronRight" size={16}/>
          </button>
        </div>

        {/* Day-of-week headers */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', padding: '0 12px 4px' }}>
          {['Mon','Tue','Wed','Thu','Fri','Sat','Sun'].map(d => (
            <div key={d} style={{ textAlign: 'center', fontSize: 10, fontWeight: 600, color: 'var(--hh-ink-mute)', textTransform: 'uppercase', letterSpacing: 0.5 }}>{d}</div>
          ))}
        </div>

        {/* Calendar grid */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', padding: '0 12px 6px', gap: 2 }}>
          {calendarDays.map((day, i) => {
            const isToday = day.iso === todayIso;
            const isSel = day.iso === selDate;
            const hasEvents = (eventsByDate[day.iso] || []).length > 0;
            const hasWaste = (wasteByDate[day.iso] || []).length > 0;
            const dotColors = [];
            if (hasEvents) dotColors.push('var(--hh-accent)');
            if (hasWaste) dotColors.push('#6E8662');

            return (
              <button key={i} onClick={() => setSelDate(day.iso)} className="press" style={{
                aspectRatio: '1', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                borderRadius: 10, border: 'none', cursor: 'pointer', position: 'relative',
                background: isSel ? 'var(--hh-accent)' : isToday ? 'var(--hh-accent-soft, rgba(99,102,241,0.1))' : 'transparent',
                color: isSel ? '#fff' : day.outside ? 'var(--hh-ink-mute)' : 'var(--hh-ink)',
                opacity: day.outside ? 0.4 : 1,
              }}>
                <span style={{ fontSize: 13, fontWeight: isToday || isSel ? 700 : 400 }}>{day.date}</span>
                {dotColors.length > 0 && (
                  <div style={{ display: 'flex', gap: 2, marginTop: 2, position: 'absolute', bottom: 4 }}>
                    {dotColors.map((c, j) => (
                      <div key={j} style={{ width: 4, height: 4, borderRadius: 2, background: isSel ? '#fff' : c }} />
                    ))}
                  </div>
                )}
              </button>
            );
          })}
        </div>

        {/* Selected day detail */}
        <div className="hh-section-h" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingRight: 20 }}>
          <span>{selDayLabel}</span>
          <button onClick={openNew} className="press" style={{ fontSize: 11, fontWeight: 600, color: 'var(--hh-accent)', background: 'none', border: 'none' }}>+ Add event</button>
        </div>

        {/* Waste collections for selected day */}
        {selWaste.length > 0 && (
          <div style={{ padding: '0 20px 8px' }}>
            {selWaste.map((w, i) => (
              <div key={i} className="hh-card" style={{ padding: '10px 14px', marginBottom: 6, display: 'flex', gap: 10, alignItems: 'center', borderLeft: `4px solid ${w.color}` }}>
                <span style={{ fontSize: 20 }}>{w.icon}</span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>{w.type}</div>
                  <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)' }}>Waste collection</div>
                </div>
              </div>
            ))}
          </div>
        )}

        {/* Calendar events */}
        <div style={{ padding: '0 20px 20px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {selEvents.length === 0 && selWaste.length === 0 ? (
            <div style={{ padding: 32, textAlign: 'center', color: 'var(--hh-ink-mute)' }}>
              <Icon name="cal2" size={32} color="var(--hh-ink-mute)" variant={cfg.iconVariant}/>
              <div style={{ marginTop: 10, fontSize: 14 }}>Nothing scheduled</div>
              <div style={{ fontSize: 12, marginTop: 4, opacity: 0.7 }}>Tap + to add an event</div>
            </div>
          ) : selEvents.map(e => (
            <div key={e.id} className="hh-card" style={{ padding: 14, display: 'flex', gap: 12, alignItems: 'stretch', borderLeft: `4px solid ${e.color}` }}>
              <div>
                <div className="hh-mono" style={{ fontSize: 12, color: 'var(--hh-ink-mute)', fontWeight: 500 }}>{e.time}</div>
                <div className="hh-mono" style={{ fontSize: 10, color: 'var(--hh-ink-mute)' }}>{e.duration}</div>
              </div>
              <div style={{ width: 1, background: 'var(--hh-line-soft)' }}/>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 15, fontWeight: 600 }}>{e.title}</div>
                {e.category && <div className="hh-pill" style={{ marginTop: 6, background: e.color + '22', color: e.color, borderColor: e.color + '44' }}>{e.category}</div>}
                {e.source === 'google' && <div style={{ fontSize: 10, color: 'var(--hh-ink-mute)', marginTop: 4 }}>📅 Google Calendar</div>}
              </div>
              {e.source === 'local' && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                  <button onClick={() => openEdit(e)} className="press" style={{ width: 28, height: 28, borderRadius: 8, background: 'var(--hh-surface-2)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Icon name="edit" size={12} color="var(--hh-ink-mute)"/>
                  </button>
                  <button onClick={() => store.removeEvent(e.id)} className="press" style={{ width: 28, height: 28, borderRadius: 8, background: '#fee2e2', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Icon name="trash2" size={12} color="#ef4444"/>
                  </button>
                </div>
              )}
            </div>
          ))}
        </div>

        {/* Upcoming waste summary */}
        {wasteCalendar.length > 0 && (
          <>
            <div className="hh-section-h" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingRight: 20 }}>
              <span>Upcoming waste</span>
              <button onClick={() => store.syncRecycleApp()} className="press" style={{ fontSize: 11, fontWeight: 600, color: 'var(--hh-accent)', background: 'none', border: 'none' }}>Sync</button>
            </div>
            <div style={{ padding: '0 20px 20px' }}>
              <div className="hh-card" style={{ padding: 14 }}>
                {wasteCalendar.filter(w => w.date >= todayIso).slice(0, 6).map((w, i, arr) => (
                  <div key={i} style={{ display: 'flex', gap: 12, alignItems: 'center', padding: '10px 0', borderBottom: i < arr.length - 1 ? '1px solid var(--hh-line-soft)' : 'none' }}>
                    <div style={{ width: 36, height: 36, borderRadius: 10, background: w.color, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, color: '#fff' }}>{w.icon}</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 14, fontWeight: 600 }}>{w.type}</div>
                      <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)' }}>{new Date(w.date + 'T00:00:00').toLocaleDateString('en', { weekday: 'short', month: 'short', day: 'numeric' })}</div>
                    </div>
                    <div style={{ fontSize: 12, fontWeight: 600, color: w.date === todayIso ? 'var(--hh-accent)' : 'var(--hh-ink-mute)' }}>
                      {w.date === todayIso ? 'Today' : (() => { const diff = Math.round((new Date(w.date) - new Date(todayIso)) / 86400000); return diff === 1 ? 'Tomorrow' : `In ${diff} days`; })()}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </>
        )}

        {/* RecycleApp.be setup prompt */}
        {!wasteConfig && wasteCalendar.length === 0 && (
          <div style={{ padding: '0 20px 20px' }}>
            <div className="hh-card" style={{ padding: 20, textAlign: 'center' }}>
              <div style={{ fontSize: 32, marginBottom: 8 }}>♻️</div>
              <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4 }}>Waste collection</div>
              <div style={{ fontSize: 12, color: 'var(--hh-ink-mute)', marginBottom: 12 }}>Connect RecycleApp.be to see your waste collection calendar</div>
              <button onClick={() => setShowWasteSetup(true)} className="press" style={{ height: 38, borderRadius: 10, background: 'var(--hh-accent)', color: '#fff', padding: '0 20px', fontSize: 13, fontWeight: 600, border: 'none' }}>Set up address</button>
            </div>
          </div>
        )}

        {/* Google Calendar placeholder */}
        <div style={{ padding: '0 20px 20px' }}>
          <div className="hh-card" style={{ padding: 16, display: 'flex', gap: 12, alignItems: 'center', opacity: 0.6 }}>
            <div style={{ fontSize: 24 }}>📅</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 600 }}>Google Calendar</div>
              <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)' }}>Coming soon — sync your Google Calendar events</div>
            </div>
            <div className="hh-pill" style={{ background: 'var(--hh-surface-2)', color: 'var(--hh-ink-mute)' }}>Soon</div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Waste address setup sheet ──────────────────────────────────
function WasteSetupSheet({ store, onClose }) {
  const [postal, setPostal] = React.useState(store.wasteConfig?.postal || '');
  const [street, setStreet] = React.useState(store.wasteConfig?.street || '');
  const [number, setNumber] = React.useState(store.wasteConfig?.number || '');
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState('');

  const save = async () => {
    if (!postal || !street || !number) return setError('All fields required');
    setSaving(true);
    setError('');
    try {
      await store.configureRecycleApp(postal, street, number);
      onClose();
    } catch (e) {
      setError(e.message || 'Failed to connect');
    }
    setSaving(false);
  };

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(42,33,26,0.32)', backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)', zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '24px 16px calc(24px + env(safe-area-inset-bottom))' }} onClick={onClose}>
      <div style={{ width: '100%', maxWidth: 460, background: 'linear-gradient(180deg, rgba(255,255,255,0.98), var(--hh-surface))', borderRadius: 28, padding: 20, border: '1px solid rgba(42,33,26,0.08)', boxShadow: '0 24px 60px rgba(42,33,26,0.18)' }} onClick={e => e.stopPropagation()}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12, marginBottom: 14 }}>
          <div>
            <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--hh-accent)', marginBottom: 8 }}>Waste calendar</div>
            <div style={{ fontSize: 26, lineHeight: 1, fontWeight: 800, color: 'var(--hh-ink)', display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{ fontSize: 28 }}>♻️</span>
              <span>RecycleApp.be</span>
            </div>
            <div style={{ fontSize: 13, lineHeight: 1.5, color: 'var(--hh-ink-mute)', marginTop: 10, maxWidth: 320 }}>Enter your Belgian address to fetch waste collection dates directly into the calendar.</div>
          </div>
          <button onClick={onClose} className="press" style={{ width: 34, height: 34, borderRadius: 999, background: 'var(--hh-surface-2)', border: '1px solid var(--hh-line-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icon name="close" size={14} color="var(--hh-ink-mute)" />
          </button>
        </div>

        <div style={{ display: 'grid', gap: 10 }}>
          <input value={postal} onChange={e => setPostal(e.target.value)} placeholder="Postal code (e.g. 3200)" style={{ height: 46, borderRadius: 14, border: '1px solid var(--hh-line-soft)', padding: '0 14px', background: 'var(--hh-surface-2)', color: 'var(--hh-ink)', outline: 'none', fontSize: 15 }} />
          <input value={street} onChange={e => setStreet(e.target.value)} placeholder="Street name" style={{ height: 46, borderRadius: 14, border: '1px solid var(--hh-line-soft)', padding: '0 14px', background: 'var(--hh-surface-2)', color: 'var(--hh-ink)', outline: 'none', fontSize: 15 }} />
          <input value={number} onChange={e => setNumber(e.target.value)} placeholder="House number" style={{ height: 46, borderRadius: 14, border: '1px solid var(--hh-line-soft)', padding: '0 14px', background: 'var(--hh-surface-2)', color: 'var(--hh-ink)', outline: 'none', fontSize: 15 }} />
        </div>

        {error && <div style={{ marginTop: 10, fontSize: 12, color: '#ef4444' }}>{error}</div>}

        <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
          <button onClick={onClose} className="press" style={{ flex: 1, height: 44, borderRadius: 14, background: 'var(--hh-surface-2)', border: '1px solid var(--hh-line-soft)', fontSize: 13, fontWeight: 700, color: 'var(--hh-ink)' }}>Cancel</button>
          <button onClick={save} disabled={saving} className="press" style={{ flex: 1, height: 44, borderRadius: 14, background: 'var(--hh-accent)', color: '#fff', border: 'none', fontSize: 13, fontWeight: 700, opacity: saving ? 0.6 : 1 }}>
            {saving ? 'Connecting...' : 'Connect'}
          </button>
        </div>
      </div>
    </div>
  );
}

window.CalendarScreen = CalendarScreen;
