// Calendar screen — month view + day detail, store-backed with full CRUD.

const EVENT_KINDS = [
  { value: 'payment', label: 'Payment' },
  { value: 'rsvp',    label: 'RSVP'    },
  { value: 'tasting', label: 'Tasting' },
  { value: 'venue',   label: 'Venue'   },
  { value: 'attire',  label: 'Attire'  },
  { value: 'event',   label: 'Event'   },
];

function eventFields() {
  return [
    { name: 'title', label: 'Title', type: 'text',
      placeholder: 'e.g. Florist final payment' },
    { name: 'dateISO', label: 'Date', type: 'date' },
    { name: 'time',  label: 'Time',  type: 'text',
      placeholder: 'e.g. 2:00 PM, Due, EOD' },
    { name: 'kind',  label: 'Kind',  type: 'choice', default: 'event',
      options: EVENT_KINDS },
    { name: 'note',  label: 'Notes', type: 'textarea',
      placeholder: 'Anything to remember' },
  ];
}

const MONTH_NAMES = [
  'January','February','March','April','May','June',
  'July','August','September','October','November','December',
];

function CalendarScreen() {
  const events = useEvents();
  const wedding = useWedding();

  // Anchor: if we have a wedding date, default to the wedding month.
  // Otherwise default to "now".
  const today = new Date();
  const anchor = wedding.date || today;

  const [view, setView] = React.useState({
    year:  anchor.getFullYear(),
    month: anchor.getMonth(),
  });
  const [selectedKey, setSelectedKey] = React.useState(null);
  const [editing, setEditing] = React.useState(null);

  const monthStart = new Date(view.year, view.month, 1);
  const daysInMonth = new Date(view.year, view.month + 1, 0).getDate();
  const startOffset = monthStart.getDay();
  const cells = [];
  for (let i = 0; i < startOffset; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);
  while (cells.length % 7 !== 0) cells.push(null);

  const dayKey = (d) =>
    new Date(view.year, view.month, d, 12).toISOString().slice(0, 10);
  const todayKey = new Date().toISOString().slice(0, 10);
  const selectedDate = selectedKey
    ? new Date(selectedKey + 'T12:00:00')
    : null;
  const selectedEvents = selectedKey ? (events.byDay[selectedKey] || []) : [];

  const prevMonth = () => setView(v => v.month === 0
    ? { year: v.year - 1, month: 11 }
    : { ...v, month: v.month - 1 });
  const nextMonth = () => setView(v => v.month === 11
    ? { year: v.year + 1, month: 0 }
    : { ...v, month: v.month + 1 });

  const submitEvent = (values) => {
    let iso = values.dateISO || '';
    if (iso && !iso.includes('T')) {
      const d = new Date(iso + 'T12:00:00');
      iso = isNaN(d.getTime()) ? '' : d.toISOString();
    }
    const patch = { ...values, dateISO: iso };
    if (editing === 'new') events.addEvent(patch);
    else events.updateEvent(editing.id, patch);
    setEditing(null);
  };

  const deleteCurrent = () => {
    if (editing && editing !== 'new') {
      events.deleteEvent(editing.id);
      setEditing(null);
    }
  };

  return (
    <div style={{ background: W.bg, paddingBottom: 28, position: 'relative' }}>
      <div style={{ paddingTop: 56 }}/>
      <ScreenHeader eyebrow="Calendar" title={MONTH_NAMES[view.month]}
        right={
          <div style={{ display: 'flex', gap: 8 }}>
            <button onClick={prevMonth} style={navBtnStyle}>
              <Icon name="chevronL" size={14} color={W.ink2}/>
            </button>
            <button onClick={nextMonth} style={navBtnStyle}>
              <Icon name="chevron" size={14} color={W.ink2}/>
            </button>
          </div>
        }
      />

      {/* Month card */}
      <div style={{ padding: '4px 16px 18px' }}>
        <Card style={{ padding: 18 }}>
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            marginBottom: 12,
          }}>
            <div style={{
              fontFamily: FONT_UI, fontSize: 10.5, fontWeight: 600,
              letterSpacing: 1.4, color: W.muted, textTransform: 'uppercase',
            }}>{view.year}</div>
            <button onClick={() => {
              const t = new Date();
              setView({ year: t.getFullYear(), month: t.getMonth() });
              setSelectedKey(t.toISOString().slice(0, 10));
            }} style={{
              background: 'transparent', border: 'none', cursor: 'pointer', padding: 0,
              fontFamily: FONT_UI, fontSize: 11, fontWeight: 500, color: W.clay,
              letterSpacing: 1,
            }}>Today</button>
          </div>
          {/* Day-of-week header */}
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', marginBottom: 10,
          }}>
            {['S','M','T','W','T','F','S'].map((d, i) => (
              <div key={i} style={{
                fontFamily: FONT_UI, fontSize: 10, fontWeight: 600,
                letterSpacing: 1.2, color: W.muted, textAlign: 'center',
                textTransform: 'uppercase',
              }}>{d}</div>
            ))}
          </div>

          {/* Day cells */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', rowGap: 4 }}>
            {cells.map((d, i) => {
              if (d === null) return <div key={i}/>;
              const k = dayKey(d);
              const dayEvents = events.byDay[k] || [];
              const isSelected = selectedKey === k;
              const isToday = k === todayKey;
              return (
                <button key={i} onClick={() => setSelectedKey(k)} style={{
                  background: 'transparent', border: 'none', cursor: 'pointer',
                  padding: '4px 0', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                }}>
                  <div style={{
                    width: 34, height: 34, borderRadius: 999,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontFamily: FONT_DISPLAY, fontSize: 17, fontWeight: 500,
                    color: isSelected ? W.bg : W.ink,
                    background: isSelected ? W.ink : 'transparent',
                    border: !isSelected && isToday ? `1.5px solid ${W.clay}` : 'none',
                    letterSpacing: -0.2,
                  }}>{d}</div>
                  <div style={{
                    display: 'flex', gap: 2, height: 4, alignItems: 'center',
                  }}>
                    {dayEvents.slice(0, 3).map((e, j) => (
                      <div key={j} style={{
                        width: 4, height: 4, borderRadius: 999,
                        background: KIND_COLORS[e.kind] || W.clay,
                      }}/>
                    ))}
                  </div>
                </button>
              );
            })}
          </div>

          {/* Legend */}
          <div style={{
            marginTop: 14, paddingTop: 14, borderTop: `0.5px solid ${W.lineSoft}`,
            display: 'flex', gap: 14, flexWrap: 'wrap',
          }}>
            {[
              ['Payment', KIND_COLORS.payment],
              ['RSVP', KIND_COLORS.rsvp],
              ['Tasting', KIND_COLORS.tasting],
              ['Attire', KIND_COLORS.attire],
              ['Venue', KIND_COLORS.venue],
            ].map(([label, color]) => (
              <div key={label} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <div style={{ width: 6, height: 6, borderRadius: 999, background: color }}/>
                <div style={{ fontFamily: FONT_UI, fontSize: 11, color: W.ink2 }}>{label}</div>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* Selected day OR upcoming intro */}
      {selectedKey ? (
        <>
          <SectionTitle
            eyebrow={selectedEvents.length
              ? `${selectedEvents.length} ${selectedEvents.length === 1 ? 'event' : 'events'}`
              : 'Free day'}
            title={selectedDate.toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })}
            action={<><Icon name="plus" size={12} color={W.clay} strokeWidth={1.8}/> Add</>}
            onAction={() => setEditing('new')}
          />
          <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
            {selectedEvents.length ? selectedEvents.map((e) => (
              <EventRow key={e.id} event={e} onClick={() => setEditing(e)}/>
            )) : (
              <Card style={{
                padding: 22, textAlign: 'center',
                fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 16,
                color: W.muted,
              }}>Nothing scheduled.</Card>
            )}
          </div>
        </>
      ) : (
        <SectionTitle
          eyebrow="Tap a day"
          title="Or browse what's next"
          action={<><Icon name="plus" size={12} color={W.clay} strokeWidth={1.8}/> Add event</>}
          onAction={() => setEditing('new')}
        />
      )}

      {/* Upcoming */}
      <div style={{ height: 22 }}/>
      <SectionTitle eyebrow="What's next" title="Upcoming"/>
      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {events.upcoming.length === 0 ? (
          <Card style={{ padding: 22, textAlign: 'center' }}>
            <div style={{
              fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 15, color: W.muted,
            }}>No events on the calendar yet.</div>
            <button onClick={() => setEditing('new')} style={{
              marginTop: 14, padding: '10px 16px',
              background: W.ink, color: W.bg, border: 'none', borderRadius: 999,
              cursor: 'pointer',
              fontFamily: FONT_UI, fontSize: 12.5, fontWeight: 500,
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              <Icon name="plus" size={12} color={W.bg} strokeWidth={1.8}/>
              Add event
            </button>
          </Card>
        ) : events.upcoming.slice(0, 8).map((u) => (
          <UpcomingRow key={u.id} u={u} onClick={() => setEditing(u)}/>
        ))}
      </div>

      {editing && (
        <FormSheet
          title={editing === 'new' ? 'Add an event' : 'Edit event'}
          eyebrow={editing === 'new' ? 'New entry' : 'Edit'}
          fields={eventFields()}
          initial={editing === 'new'
            ? { dateISO: selectedKey || new Date().toISOString().slice(0, 10) }
            : { ...editing, dateISO: editing.dateISO ? editing.dateISO.slice(0, 10) : '' }
          }
          submitLabel={editing === 'new' ? 'Add' : 'Save'}
          onClose={() => setEditing(null)}
          onSubmit={submitEvent}
          onDelete={editing !== 'new' ? deleteCurrent : null}
        />
      )}
    </div>
  );
}

const navBtnStyle = {
  width: 36, height: 36, borderRadius: 999,
  background: W.card, border: `0.5px solid ${W.line}`,
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  cursor: 'pointer', padding: 0,
};

function EventRow({ event, onClick }) {
  const color = KIND_COLORS[event.kind] || W.clay;
  const iconByKind = {
    payment: 'wallet', rsvp: 'users', tasting: 'cake',
    venue: 'home', attire: 'sparkle', event: 'calendar',
  };
  return (
    <Card onClick={onClick} style={{
      padding: 14, display: 'flex', alignItems: 'center', gap: 14,
      cursor: onClick ? 'pointer' : 'default',
    }}>
      <div style={{
        width: 4, alignSelf: 'stretch', borderRadius: 999, background: color,
        margin: '-2px 0',
      }}/>
      <div style={{
        width: 38, height: 38, borderRadius: 11,
        background: '#fbf6ea', border: `0.5px solid ${W.lineSoft}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        <Icon name={iconByKind[event.kind] || 'calendar'} size={17} color={color} strokeWidth={1.4}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: FONT_UI, fontSize: 14.5, fontWeight: 500, color: W.ink, lineHeight: 1.25,
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        }}>{event.title || <em style={{ color: W.muted }}>Untitled</em>}</div>
        <div style={{
          fontFamily: FONT_UI, fontSize: 11.5, color: W.muted, marginTop: 3,
        }}>{event.time || '—'}</div>
      </div>
      <Icon name="chevron" size={14} color={W.faint}/>
    </Card>
  );
}

function UpcomingRow({ u, onClick }) {
  const color = KIND_COLORS[u.kind] || W.clay;
  const date = new Date(u.dateISO);
  const day = date.toLocaleDateString('en-US', { weekday: 'short' });
  const dayN = date.getDate();
  const monthN = date.toLocaleDateString('en-US', { month: 'short' });
  return (
    <Card onClick={onClick} style={{
      padding: 14, display: 'flex', alignItems: 'center', gap: 14,
      cursor: onClick ? 'pointer' : 'default',
    }}>
      <div style={{
        width: 48, flexShrink: 0,
        display: 'flex', flexDirection: 'column', alignItems: 'center',
      }}>
        <div style={{
          fontFamily: FONT_UI, fontSize: 10, fontWeight: 600,
          letterSpacing: 1.2, color: W.muted, textTransform: 'uppercase',
        }}>{day}</div>
        <div style={{
          fontFamily: FONT_DISPLAY, fontSize: 22, color: W.ink,
          letterSpacing: -0.4, lineHeight: 1, marginTop: 2,
        }}>{dayN}</div>
        <div style={{
          fontFamily: FONT_UI, fontSize: 9, fontWeight: 600,
          letterSpacing: 1.2, color: W.muted, textTransform: 'uppercase', marginTop: 2,
        }}>{monthN}</div>
      </div>
      <div style={{
        width: 1, alignSelf: 'stretch', background: W.lineSoft,
      }}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
          <div style={{ width: 6, height: 6, borderRadius: 999, background: color }}/>
          <span style={{
            fontFamily: FONT_UI, fontSize: 10.5, fontWeight: 600,
            letterSpacing: 1.2, color: W.muted, textTransform: 'uppercase',
          }}>{u.kind}</span>
        </div>
        <div style={{
          fontFamily: FONT_UI, fontSize: 14.5, fontWeight: 500, color: W.ink, lineHeight: 1.25,
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        }}>{u.title || <em style={{ color: W.muted }}>Untitled</em>}</div>
        <div style={{
          fontFamily: FONT_UI, fontSize: 11.5, color: W.muted, marginTop: 3,
        }}>{u.time || '—'}</div>
      </div>
    </Card>
  );
}

Object.assign(window, { CalendarScreen });
