// page-home.jsx — Activity Calendar
// Top: countdown cards (multiple, sorted near→far, dedup by event name)
// Bottom: monthly calendar grid; click event pill → scroll up to its countdown card

const { useState: useStateH, useEffect: useEffectH, useMemo: useMemoH, useRef: useRefH } = React;

function HomePage({ events, eventTemplates, tzOffsetHrs, onToast, onEditEvent, onAddEvent, onDeleteEvent }) {
  useTick(1000);
  const now = new Date();
  const [editing, setEditing] = useStateH(null); // event being edited, or null
  const [expanded, setExpanded] = useStateH(null); // event id currently expanded
  const [highlighted, setHighlighted] = useStateH(null);
  const [copiedChunk, setCopiedChunk] = useStateH(null); // `${eventId}-${idx}` last copied
  const cardRefs = useRefH({});
  const [monthOffset, setMonthOffset] = useStateH(0); // 0 = current, +1 = next month etc

  // Compute next occurrence for every event, sort by start ASC
  const upcoming = useMemoH(() => {
    return events.map(e => {
      const start = nextOccurrence(e, now, tzOffsetHrs);
      if (!start) return null; // one-off, already past
      const end = new Date(start.getTime() + e.duration_min * 60000);
      return { ...e, start, end };
    }).filter(Boolean).sort((a, b) => a.start - b.start);
  }, [events, tzOffsetHrs, Math.floor(now.getTime() / 60000)]);

  // Dedup by name — only the nearest occurrence of each event name
  // (so "Bear Trap" on Mon AND Thu only shows the next one)
  const dedupedCountdown = useMemoH(() => {
    const seen = new Set();
    const out = [];
    for (const e of upcoming) {
      if (seen.has(e.name)) continue;
      seen.add(e.name);
      out.push(e);
    }
    return out;
  }, [upcoming]);

  const handleCopyChunk = async (eventId, chunkIdx, text) => {
    await copyText(text);
    setCopiedChunk(`${eventId}-${chunkIdx}`);
    onToast(`Chunk ${chunkIdx + 1} copied · ${text.length} chars`);
  };

  const scrollToEvent = (eventName) => {
    // Find the countdown card for this event name
    const card = cardRefs.current[eventName];
    if (card) {
      card.scrollIntoView({ behavior: 'smooth', block: 'start' });
      setHighlighted(eventName);
      setTimeout(() => setHighlighted(null), 1400);
    } else {
      onToast(`No upcoming countdown for "${eventName}"`);
    }
  };

  const handleSaveEvent = (form) => {
    if (events.find(e => e.id === form.id)) {
      onEditEvent(form);
    } else {
      onAddEvent(form);
    }
    setEditing(null);
    onToast('Event saved');
  };

  const handleDeleteEvent = (id) => {
    if (!confirm('Delete this event?')) return;
    onDeleteEvent(id);
    setEditing(null);
    onToast('Event deleted');
  };

  return (
    <div className="page home-grid">
      {/* COUNTDOWN STRIP */}
      <section>
        <div className="section-header">
          <h2>Upcoming</h2>
          <span className="sub">— nearest first · one card per event name</span>
        </div>
        {dedupedCountdown.length === 0 ? (
          <div className="empty">No events configured. Add one in the calendar below.</div>
        ) : (
          <div className="eventstrip">
            {dedupedCountdown.map(e => (
              <CountdownCard
                key={e.id}
                ev={e}
                now={now}
                tzOffsetHrs={tzOffsetHrs}
                highlighted={highlighted === e.name}
                expanded={expanded === e.id}
                onToggle={() => setExpanded(expanded === e.id ? null : e.id)}
                onEdit={() => setEditing(e)}
                onCopyChunk={handleCopyChunk}
                copiedChunkKey={copiedChunk}
                attachRef={(el) => { cardRefs.current[e.name] = el; }}
              />
            ))}
          </div>
        )}
      </section>

      {/* MONTHLY CALENDAR */}
      <section>
        <div className="section-header">
          <h2>Monthly Calendar</h2>
          <span className="sub">— server time ({tzLabel(tzOffsetHrs)})</span>
          <span style={{ flex: 1 }}></span>
        </div>
        <MonthCalendar
          events={events}
          tzOffsetHrs={tzOffsetHrs}
          now={now}
          monthOffset={monthOffset}
          onMonthOffsetChange={setMonthOffset}
          onEventClick={(ev) => scrollToEvent(ev.name)}
          onEventEdit={(ev) => setEditing(ev)}
          onDayClick={(date) => {
            // Pre-fill new event with this date's weekday
            const shifted = new Date(date.getTime() + tzOffsetHrs * 3600000);
            setEditing({
              id: `new-${Date.now()}`,
              name: '',
              weekday: shifted.getUTCDay(),
              start_time: '20:00',
              duration_min: 60,
              category: 'alliance',
              guide_text: '',
            });
          }}
        />
      </section>

      {editing && (
        <EventModal
          event={editing}
          templates={eventTemplates}
          onSave={handleSaveEvent}
          onDelete={handleDeleteEvent}
          onCancel={() => setEditing(null)}
        />
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Countdown card

function CountdownCard({ ev, now, tzOffsetHrs, highlighted, expanded, onToggle, onEdit, onCopyChunk, copiedChunkKey, attachRef }) {
  const ms = ev.start.getTime() - now.getTime();
  const inProgress = now >= ev.start && now <= ev.end;
  const urgency = inProgress ? 'live'
    : ms < 5 * 60000 ? 'hot'
    : ms < 60 * 60000 ? 'soon' : 'normal';

  const chunks = useMemoH(() => splitChunks(ev.guide_text || '', 512), [ev.guide_text]);
  const isLong = chunks.length > 1;

  return (
    <div
      className="ecard scroll-anchor"
      data-urgency={urgency}
      ref={attachRef}
      onClick={onToggle}
      style={highlighted ? {
        boxShadow: '0 0 0 2px var(--accent), 0 0 24px var(--accent-soft)',
        transition: 'box-shadow 0.3s ease',
      } : { transition: 'box-shadow 0.4s ease' }}
    >
      <div className="countdown">
        {inProgress ? (
          <>
            <span>LIVE</span>
            <span className="lbl">ends in {formatDuration(ev.end - now)}</span>
          </>
        ) : (
          <>
            <span>{formatDuration(ms)}</span>
            <span className="lbl">until start</span>
          </>
        )}
      </div>
      <div className="name">{ev.name}</div>
      <div className="meta">
        <span>{formatServerTime(ev.start, tzOffsetHrs)}</span>
        <span className="sep">·</span>
        <span>{formatDurationMin(ev.duration_min)}</span>
        <span className="sep">·</span>
        <span className="muted">{ev.category}</span>
      </div>
      <div className="actions" onClick={(e) => e.stopPropagation()}>
        {!isLong ? (
          <button className="btn ghost" onClick={async () => {
            await copyText(ev.guide_text || '');
            onCopyChunk(ev.id, 0, ev.guide_text || '');
          }}>
            Copy
            <span className="muted" style={{ fontSize: 9 }}>{(ev.guide_text || '').length}</span>
          </button>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4, flex: 1 }}>
            <div style={{ fontSize: 10, color: 'var(--fg-3)', fontFamily: 'var(--font-mono)' }}>
              {(ev.guide_text || '').length} chars · {chunks.length} chunks
            </div>
            <div className="chunk-row">
              {chunks.map((c, i) => (
                <button
                  key={i}
                  className="chunk-btn"
                  data-copied={copiedChunkKey === `${ev.id}-${i}`}
                  onClick={() => onCopyChunk(ev.id, i, c)}
                >
                  {i + 1}/{chunks.length}
                  <span className="len">{c.length}</span>
                </button>
              ))}
            </div>
          </div>
        )}
        <button className="btn ghost icon" title="Edit event" onClick={onEdit}>✎</button>
      </div>
      {expanded && (
        <pre className="guide-preview">{ev.guide_text || <span className="muted">— no guide text —</span>}</pre>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Monthly calendar

function MonthCalendar({ events, tzOffsetHrs, now, monthOffset, onMonthOffsetChange, onEventClick, onEventEdit, onDayClick }) {
  // Compute the "anchor" month (in server time)
  const shiftedNow = new Date(now.getTime() + tzOffsetHrs * 3600000);
  const anchorYear = shiftedNow.getUTCFullYear();
  const anchorMonth = shiftedNow.getUTCMonth() + monthOffset;
  const firstOfMonth = new Date(Date.UTC(anchorYear, anchorMonth, 1));
  const monthLabel = firstOfMonth.toLocaleString('en-US', { month: 'long', year: 'numeric', timeZone: 'UTC' });

  // Build 6-week grid starting from Sunday before first of month
  const firstWeekday = firstOfMonth.getUTCDay();
  const gridStart = new Date(firstOfMonth);
  gridStart.setUTCDate(1 - firstWeekday);

  const days = [];
  for (let i = 0; i < 42; i++) {
    const d = new Date(gridStart);
    d.setUTCDate(gridStart.getUTCDate() + i);
    days.push(d);
  }

  // Group events by source weekday vs other recurrences
  // For each cell, we'll check eventOccursOn(event, cellDate)
  const sortedEvents = useMemoH(() => {
    return [...events].sort((a, b) => (a.start_time || '').localeCompare(b.start_time || ''));
  }, [events]);

  // "today" in server time
  const todayKey = `${shiftedNow.getUTCFullYear()}-${shiftedNow.getUTCMonth()}-${shiftedNow.getUTCDate()}`;

  return (
    <div className="monthcal">
      <div className="monthcal-hd">
        <h3>{monthLabel}</h3>
        <span style={{ flex: 1 }}></span>
        <button className="btn ghost" onClick={() => onMonthOffsetChange(monthOffset - 1)}>‹ Prev</button>
        <button className="btn ghost" onClick={() => onMonthOffsetChange(0)} disabled={monthOffset === 0}>Today</button>
        <button className="btn ghost" onClick={() => onMonthOffsetChange(monthOffset + 1)}>Next ›</button>
      </div>
      <div className="monthcal-grid">
        {WEEKDAY_SHORT.map(wd => <div key={wd} className="wd-hdr">{wd}</div>)}
        {days.map((d, i) => {
          const inMonth = d.getUTCMonth() === ((anchorMonth + 12) % 12);
          const weekday = d.getUTCDay();
          const isToday = `${d.getUTCFullYear()}-${d.getUTCMonth()}-${d.getUTCDate()}` === todayKey;
          const dayEvents = sortedEvents.filter(e => eventOccursOn(e, d));
          const isWeekend = weekday === 0 || weekday === 6;
          const visible = dayEvents.slice(0, 3);
          const more = dayEvents.length - visible.length;

          return (
            <div
              key={i}
              className={`monthcal-cell ${inMonth ? '' : 'other-month'} ${isToday ? 'today' : ''} ${isWeekend ? 'weekend' : ''}`}
              onClick={() => onDayClick(d)}
            >
              <div className="daynum">{d.getUTCDate()}</div>
              {visible.map(e => {
                const color = e.color || defaultColorForCategory(e.category);
                return (
                  <div
                    key={e.id}
                    className="evt-pill"
                    style={{
                      background: colorToTint(color, 0.16),
                      borderLeftColor: color,
                    }}
                    title={`${e.name} — ${e.start_time}, ${formatDurationMin(e.duration_min)}\nClick to jump to countdown\nShift-click to edit`}
                    onClick={(ev) => {
                      ev.stopPropagation();
                      if (ev.shiftKey) onEventEdit(e);
                      else onEventClick(e);
                    }}
                  >
                    <span className="evt-time">{e.start_time}</span>
                    <span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{e.name}</span>
                  </div>
                );
              })}
              {more > 0 && <div className="more">+{more} more</div>}
              <button
                className="add-day-btn"
                title="Add event on this weekday"
                onClick={(ev) => { ev.stopPropagation(); onDayClick(d); }}
              >+</button>
            </div>
          );
        })}
      </div>
      <div style={{
        padding: '8px 14px', borderTop: '1px solid var(--border-soft)',
        fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--fg-4)',
        display: 'flex', gap: 14, flexWrap: 'wrap',
      }}>
        <span>Click event → scroll up to its countdown</span>
        <span>·</span>
        <span>Shift-click event → edit</span>
        <span>·</span>
        <span>Click empty day → add new event</span>
      </div>
    </div>
  );
}

Object.assign(window, { HomePage });
