/* global React, Icon, Avatar */
const { useState } = React;

function Calendar({ goto }) {
  const [view, setView] = useState('week');
  const [selectedEvent, setSelectedEvent] = useState(null);
  const events = window.CALENDAR_EVENTS;

  const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  const dates = ['27', '28', '29', '30', '01', '02', '03'];
  const hours = Array.from({ length: 11 }, (_, i) => i + 8); // 8am-6pm

  const eventColor = {
    discovery: '#f97316',
    strategy:  '#eab308',
    internal:  '#3b82f6',
    other:     '#6b7280',
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <div className="page-header">
        <div className="page-header-left">
          <div className="page-eyebrow">April · Week 18</div>
          <h1 className="page-title">Calendar</h1>
        </div>
        <div className="page-header-right">
          <div style={{ display: 'flex', border: '1px solid var(--divider)' }}>
            <button className={`btn btn-sm ${view==='week' ? 'btn-primary' : ''}`} style={{ borderRadius: 0, borderColor: 'transparent' }} onClick={() => setView('week')}>Week</button>
            <button className={`btn btn-sm ${view==='month' ? 'btn-primary' : ''}`} style={{ borderRadius: 0, borderColor: 'transparent' }} onClick={() => setView('month')}>Month</button>
          </div>
          <button className="btn"><Icon name="link" size={12} /> Booking pages</button>
          <button className="btn btn-primary"><Icon name="plus" size={12} /> New event</button>
        </div>
      </div>

      {view === 'week' ? (
        <div style={{ flex: 1, overflow: 'auto', padding: 20 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '60px repeat(7, 1fr)', border: '1px solid var(--divider)', minWidth: 800 }}>
            <div style={{ padding: 8, borderBottom: '1px solid var(--divider)', borderRight: '1px solid var(--divider)' }}></div>
            {days.map((d, i) => (
              <div key={d} style={{ padding: 10, borderBottom: '1px solid var(--divider)', borderRight: i === 6 ? 'none' : '1px solid var(--divider)', textAlign: 'center' }}>
                <div className="label">{d}</div>
                <div className="mono" style={{ fontSize: 18, color: i === 1 ? 'var(--accent)' : 'var(--text)', marginTop: 2 }}>{dates[i]}</div>
              </div>
            ))}
            {hours.map(h => (
              <React.Fragment key={h}>
                <div style={{ padding: '6px 8px', borderBottom: '1px solid var(--divider)', borderRight: '1px solid var(--divider)', fontSize: 10, color: 'var(--text-dim)' }} className="mono">
                  {String(h).padStart(2,'0')}:00
                </div>
                {days.map((d, dayIdx) => {
                  const dayEvents = events.filter(e => e.day === dayIdx && Math.floor(e.start) === h);
                  return (
                    <div key={d+h} style={{
                      padding: 4, height: 56, borderBottom: '1px solid var(--divider)',
                      borderRight: dayIdx === 6 ? 'none' : '1px solid var(--divider)', position: 'relative',
                    }}>
                      {dayEvents.map(e => (
                        <div key={e.id} onClick={() => setSelectedEvent(e)} style={{
                          background: `${eventColor[e.type]}22`,
                          border: '1px solid ' + eventColor[e.type],
                          borderLeft: '2px solid ' + eventColor[e.type],
                          padding: 6, fontSize: 10, cursor: 'pointer',
                          height: `${(e.end - e.start) * 56 - 8}px`,
                          minHeight: 28,
                        }}>
                          <div style={{ color: 'var(--text)', fontWeight: 600, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{e.title}</div>
                          <div className="mono" style={{ fontSize: 9, color: 'var(--text-dim)' }}>
                            {String(Math.floor(e.start)).padStart(2,'0')}:{String(Math.round((e.start%1)*60)).padStart(2,'0')}
                          </div>
                        </div>
                      ))}
                    </div>
                  );
                })}
              </React.Fragment>
            ))}
          </div>
        </div>
      ) : (
        <div style={{ flex: 1, overflow: 'auto', padding: 20 }}>
          <MonthView events={events} eventColor={eventColor} onSelect={setSelectedEvent} />
        </div>
      )}

      {selectedEvent && (
        <>
          <div className="drawer-overlay" onClick={() => setSelectedEvent(null)}></div>
          <div className="drawer">
            <div style={{ padding: 20, borderBottom: '1px solid var(--divider)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div className="label">Event</div>
              <button className="btn btn-ghost btn-icon" onClick={() => setSelectedEvent(null)}><Icon name="x" size={14} /></button>
            </div>
            <div style={{ padding: 24, overflow: 'auto', flex: 1 }}>
              <div style={{ width: 36, height: 4, background: eventColor[selectedEvent.type], marginBottom: 14 }}></div>
              <h2 style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 800, fontSize: 24, marginBottom: 8 }}>{selectedEvent.title}</h2>
              <div className="mono" style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 24 }}>
                {days[selectedEvent.day]} · {String(Math.floor(selectedEvent.start)).padStart(2,'0')}:{String(Math.round((selectedEvent.start%1)*60)).padStart(2,'0')} – {String(Math.floor(selectedEvent.end)).padStart(2,'0')}:{String(Math.round((selectedEvent.end%1)*60)).padStart(2,'0')}
              </div>

              {selectedEvent.contactId && (() => {
                const c = window.CONTACTS.find(x => x.id === selectedEvent.contactId);
                return c && (
                  <div style={{ marginBottom: 20 }}>
                    <div className="label" style={{ marginBottom: 8 }}>Contact</div>
                    <div onClick={() => goto('contact', c.id)} style={{ padding: 12, background: 'var(--raised)', border: '1px solid var(--divider)', display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
                      <Avatar name={c.name} initials={c.initials} color={c.avatarColor} size="md" />
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 13, fontWeight: 500 }}>{c.name}</div>
                        <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>{c.title} · {c.company}</div>
                      </div>
                      <Icon name="arrowRight" size={14} style={{ color: 'var(--text-dim)' }} />
                    </div>
                  </div>
                );
              })()}

              {selectedEvent.invite && <InviteStatus invite={selectedEvent.invite} />}
              {selectedEvent.reminders && <ReminderSequence event={selectedEvent} />}

              <div style={{ marginBottom: 20 }}>
                <div className="label" style={{ marginBottom: 8 }}>Prep notes</div>
                <div style={{ padding: 12, background: 'var(--raised)', border: '1px solid var(--divider)', fontSize: 12, color: 'var(--text-secondary)', lineHeight: 1.6, fontFamily: 'var(--font-mono)' }}>
                  {selectedEvent.notes}
                </div>
              </div>

              <div style={{ display: 'grid', gap: 6 }}>
                <button className="btn btn-sm" style={{ justifyContent: 'flex-start' }}><Icon name="external" size={12} /> Open Zoom</button>
                <button className="btn btn-sm" style={{ justifyContent: 'flex-start' }}><Icon name="edit" size={12} /> Edit event</button>
                <button className="btn btn-sm" style={{ justifyContent: 'flex-start', color: 'var(--red)' }}><Icon name="trash" size={12} /> Cancel event</button>
              </div>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

function MonthView({ events, eventColor, onSelect }) {
  const days = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
  // Build a 5x7 grid for April. Today is Apr 28 (col idx 1, row idx 4 if Mon=0)
  const cells = [];
  for (let i = 0; i < 35; i++) {
    const dayNum = i - 1; // April starts on Wed = idx 2
    let label = '';
    if (i >= 2 && i < 32) label = String(i - 1);
    cells.push({ idx: i, label, isToday: label === '28' });
  }
  return (
    <div style={{ border: '1px solid var(--divider)' }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', borderBottom: '1px solid var(--divider)' }}>
        {days.map((d, i) => (
          <div key={d} style={{ padding: 10, textAlign: 'center', borderRight: i === 6 ? 'none' : '1px solid var(--divider)' }}>
            <div className="label">{d}</div>
          </div>
        ))}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)' }}>
        {cells.map((c, i) => {
          const colIdx = i % 7;
          const rowIdx = Math.floor(i / 7);
          // place this week's events on row 4 (week of Apr 27)
          const eventsHere = (rowIdx === 4 && c.label) ? events.filter(e => e.day === colIdx) : [];
          return (
            <div key={i} style={{
              minHeight: 100, padding: 8,
              borderRight: colIdx === 6 ? 'none' : '1px solid var(--divider)',
              borderBottom: rowIdx === 4 ? 'none' : '1px solid var(--divider)',
              background: c.isToday ? 'var(--raised)' : 'transparent',
            }}>
              <div className="mono" style={{ fontSize: 11, color: c.isToday ? 'var(--accent)' : c.label ? 'var(--text-secondary)' : 'var(--text-dim)', fontWeight: c.isToday ? 700 : 400, marginBottom: 6 }}>{c.label || ''}</div>
              {eventsHere.map(e => (
                <div key={e.id} onClick={() => onSelect(e)} style={{ padding: '3px 6px', marginBottom: 3, background: `${eventColor[e.type]}22`, borderLeft: '2px solid ' + eventColor[e.type], fontSize: 10, cursor: 'pointer', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
                  <span className="mono" style={{ fontSize: 9, color: 'var(--text-dim)' }}>{String(Math.floor(e.start)).padStart(2,'0')}:{String(Math.round((e.start%1)*60)).padStart(2,'0')}</span>{' '}
                  <span style={{ color: 'var(--text)' }}>{e.title.split(' · ')[0]}</span>
                </div>
              ))}
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { Calendar });

/* ============================================================
   INVITE STATUS — did the contact accept the Google Calendar invite?
   ============================================================ */

function InviteStatus({ invite }) {
  const cfg = {
    accepted:  { label: 'Accepted',  color: '#22c55e', icon: 'check',     bg: 'rgba(34,197,94,0.10)' },
    tentative: { label: 'Maybe',     color: '#eab308', icon: 'clock',     bg: 'rgba(234,179,8,0.10)' },
    declined:  { label: 'Declined',  color: '#ef4444', icon: 'x',         bg: 'rgba(239,68,68,0.10)' },
    pending:   { label: 'No response', color: 'var(--text-dim)', icon: 'mail', bg: 'var(--raised)' },
  }[invite.status] || { label: invite.status, color: 'var(--text-secondary)', icon: 'mail', bg: 'var(--raised)' };

  return (
    <div style={{ marginBottom: 20 }}>
      <div className="label" style={{ marginBottom: 8 }}>Google Calendar Invite</div>
      <div style={{ padding: 12, background: cfg.bg, border: '1px solid var(--divider)', display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{
          width: 28, height: 28, borderRadius: '50%',
          background: invite.status === 'pending' ? 'transparent' : cfg.color + '22',
          color: cfg.color, border: '1px solid ' + cfg.color,
          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}>
          <Icon name={cfg.icon} size={13} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: cfg.color }}>{cfg.label}</div>
          <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>
            {invite.status === 'pending'
              ? 'Awaiting response from contact'
              : `Responded ${invite.respondedAt}${invite.note ? ' · ' + invite.note : ''}`}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   REMINDER SEQUENCE — 24h, 8h, 1h, 10m before
   ============================================================ */

const REM_OFFSET_LABEL = {
  '24h': '24 hours before',
  '8h':  '8 hours before',
  '1h':  '1 hour before',
  '10m': '10 minutes before',
};

const REM_STATUS = {
  scheduled: { label: 'Scheduled', color: 'var(--text-dim)',     icon: 'clock' },
  sent:      { label: 'Sent',      color: 'var(--text-secondary)', icon: 'check' },
  delivered: { label: 'Delivered', color: 'var(--text-secondary)', icon: 'check' },
  opened:    { label: 'Opened',    color: '#22c55e',              icon: 'eye' },
  read:      { label: 'Read',      color: '#22c55e',              icon: 'eye' },
  cancelled: { label: 'Cancelled', color: '#ef4444',              icon: 'x' },
  failed:    { label: 'Failed',    color: '#ef4444',              icon: 'x' },
};

function ReminderSequence({ event }) {
  const reminders = event.reminders || [];
  const sentCount = reminders.filter(r => ['sent','delivered','opened','read'].includes(r.status)).length;
  const openedCount = reminders.filter(r => ['opened','read'].includes(r.status)).length;

  return (
    <div style={{ marginBottom: 20 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
        <div className="label">Reminder Sequence</div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>
          {sentCount}/{reminders.length} sent · {openedCount} opened
        </div>
      </div>

      <div style={{ border: '1px solid var(--divider)', background: 'var(--surface)' }}>
        {reminders.map((r, i) => {
          const s = REM_STATUS[r.status] || REM_STATUS.scheduled;
          const channelColor = r.channel === 'whatsapp' ? '#22c55e' : '#3b82f6';
          return (
            <div key={i} style={{
              padding: '10px 12px',
              borderBottom: i === reminders.length - 1 ? 'none' : '1px solid var(--divider)',
              display: 'flex', alignItems: 'center', gap: 10,
              opacity: r.status === 'cancelled' ? 0.55 : 1,
            }}>
              {/* Channel badge */}
              <div style={{
                width: 24, height: 24,
                background: channelColor + '22', color: channelColor,
                display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              }}>
                <Icon name={r.channel === 'whatsapp' ? 'whatsappIcon' : 'mail'} size={11} />
              </div>

              {/* Offset + detail */}
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
                  <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--text)', textDecoration: r.status === 'cancelled' ? 'line-through' : 'none' }}>
                    {REM_OFFSET_LABEL[r.offset] || r.offset}
                  </span>
                  <span style={{ fontSize: 10, color: 'var(--text-dim)', textTransform: 'capitalize' }}>· {r.channel}</span>
                </div>
                <div style={{ fontSize: 11, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>
                  {r.detail || (r.sentAt ? r.sentAt : '—')}
                </div>
              </div>

              {/* Status pill */}
              <div style={{
                display: 'inline-flex', alignItems: 'center', gap: 4,
                padding: '3px 8px', fontSize: 10, fontWeight: 600,
                letterSpacing: '0.04em', textTransform: 'uppercase',
                color: s.color, border: '1px solid ' + (s.color === 'var(--text-dim)' ? 'var(--divider)' : s.color),
                background: s.color === 'var(--text-dim)' ? 'transparent' : s.color + '14',
              }}>
                <Icon name={s.icon} size={9} />
                {s.label}
              </div>
            </div>
          );
        })}
      </div>

      <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
        <button className="btn btn-sm" style={{ flex: 1 }}>
          <Icon name="edit" size={11} /> Edit sequence
        </button>
        <button className="btn btn-sm" style={{ flex: 1 }}>
          <Icon name="send" size={11} /> Send now
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { InviteStatus, ReminderSequence });
