// Wedding Day timeline — the keepsake screen.
// Vertical magazine-style timeline, fully store-backed with add/edit/delete.

const TIMELINE_ICONS = ['sparkle','users','cake','camera','rings','heart','music','flag'];
const TIMELINE_KINDS = ['event','attire','tasting','venue','rsvp'];

function timelineFields() {
  return [
    { name: 'time',  label: 'Time',     type: 'text', placeholder: 'e.g. 4:00 PM',
      hint: 'Format: 7:00 AM, 12:00 PM, 4:30 PM' },
    { name: 'title', label: 'What',     type: 'text', placeholder: 'e.g. Ceremony' },
    { name: 'where', label: 'Where',    type: 'text', placeholder: 'e.g. Garden lawn' },
    { name: 'kind',  label: 'Category', type: 'choice', options: TIMELINE_KINDS, default: 'event' },
    { name: 'icon',  label: 'Icon',     type: 'choice', options: TIMELINE_ICONS, default: 'sparkle' },
    { name: 'note',  label: 'Note',     type: 'text', placeholder: 'Optional detail' },
    { name: 'hero',  label: 'Mark as the ceremony moment', type: 'toggle' },
  ];
}

function emergencyFields() {
  return [
    { name: 'role',  label: 'Role',  type: 'text', placeholder: 'e.g. Day-of planner' },
    { name: 'name',  label: 'Name',  type: 'text', placeholder: 'e.g. Pat Rivera' },
    { name: 'phone', label: 'Phone', type: 'text', placeholder: '(555) 123-4567' },
  ];
}

function DayOfScreen({ onBack }) {
  const wedding = useWedding();
  const timeline = useDayOfTimeline();
  const emergency = useEmergencyContacts();
  const [editingEvent, setEditingEvent] = React.useState(null);
  const [editingContact, setEditingContact] = React.useState(null);

  const submitEvent = (v) => {
    if (editingEvent === 'new') timeline.addTimelineEvent(v);
    else timeline.updateTimelineEvent(editingEvent.id, v);
    setEditingEvent(null);
  };
  const submitContact = (v) => {
    if (editingContact === 'new') emergency.addEmergencyContact(v);
    else emergency.updateEmergencyContact(editingContact.id, v);
    setEditingContact(null);
  };

  const dayName  = wedding.dayName || '';
  const monthDay = wedding.date ? wedding.date.toLocaleDateString('en-US', { month: 'long', day: 'numeric' }) : '';
  const year     = wedding.date ? wedding.date.getFullYear() : '';
  return (
    <div style={{ background: W.bg, paddingBottom: 28 }}>
      <div style={{ paddingTop: 56 }}/>

      {/* Back row */}
      <div style={{
        padding: '4px 22px 16px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <button onClick={onBack} style={{
          background: W.card, border: `0.5px solid ${W.line}`,
          width: 36, height: 36, borderRadius: 999, cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: 0,
        }}>
          <Icon name="chevronL" size={14} color={W.ink2}/>
        </button>
        <button onClick={() => printReport('dayof')} style={{
          display: 'flex', alignItems: 'center', gap: 8,
          background: W.card, border: `0.5px solid ${W.line}`,
          padding: '8px 14px', borderRadius: 999, cursor: 'pointer',
        }}>
          <Icon name="sparkle" size={13} color={W.clay} strokeWidth={1.4}/>
          <span style={{ fontFamily: FONT_UI, fontSize: 12, fontWeight: 500, color: W.ink2 }}>
            Print PDF
          </span>
        </button>
      </div>

      {/* Magazine hero */}
      <div style={{ padding: '0 22px 24px' }}>
        <div style={{
          fontFamily: FONT_UI, fontSize: 10.5, fontWeight: 600,
          letterSpacing: 2, textTransform: 'uppercase', color: W.muted,
        }}>The Wedding of</div>
        <div style={{
          fontFamily: FONT_DISPLAY, fontSize: 42, fontWeight: 500,
          color: W.ink, lineHeight: 1, marginTop: 8, letterSpacing: -0.5,
        }}>
          {wedding.brides || 'You'}{' '}
          <span style={{ fontStyle: 'italic' }}>&amp;</span>{' '}
          {wedding.groom || 'them'}
        </div>
        {wedding.date && (
          <div style={{
            fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 17,
            color: W.ink2, marginTop: 10,
          }}>{dayName}, {monthDay} · {year}</div>
        )}
        {(wedding.city || wedding.venue) && (
          <div style={{
            fontFamily: FONT_UI, fontSize: 13, color: W.muted, marginTop: 4,
            letterSpacing: 0.2,
          }}>
            {wedding.city}{wedding.city && wedding.venue ? ' · ' : ''}{wedding.venue}
          </div>
        )}

        {/* hairline */}
        <div style={{
          height: 0.5, background: W.line, margin: '20px 0',
        }}/>

        {/* weather + sunset strip */}
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12,
        }}>
          {[
            ['Sunrise', '7:01'],
            ['Ceremony', '4:00'],
            ['Sunset',  '6:48'],
          ].map(([k, v]) => (
            <div key={k}>
              <div style={{
                fontFamily: FONT_UI, fontSize: 9.5, fontWeight: 600,
                letterSpacing: 1.4, color: W.muted, textTransform: 'uppercase',
              }}>{k}</div>
              <div style={{
                fontFamily: FONT_DISPLAY, fontSize: 22, color: W.ink,
                letterSpacing: -0.2, marginTop: 2,
              }}>{v}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Timeline */}
      <div style={{
        display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
        padding: '0 22px 6px',
      }}>
        <SectionTitle eyebrow="The Day" title="Timeline"/>
        <button onClick={() => setEditingEvent('new')} style={{
          background: 'transparent', border: 'none', cursor: 'pointer',
          fontFamily: FONT_UI, fontSize: 12.5, fontWeight: 500, color: W.clay,
          padding: 4,
        }}>+ Add event</button>
      </div>
      <div style={{ padding: '0 22px 32px', position: 'relative' }}>
        {timeline.all.length === 0 ? (
          <div style={{
            padding: '28px 16px', textAlign: 'center',
            background: W.cardSoft, border: `0.5px dashed ${W.line}`, borderRadius: 12,
          }}>
            <div style={{
              fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 16,
              color: W.ink2, lineHeight: 1.4,
            }}>
              Your day-of timeline lives here.
            </div>
            <div style={{
              fontFamily: FONT_UI, fontSize: 12.5, color: W.muted, marginTop: 6,
              lineHeight: 1.5,
            }}>
              Add the moments that matter · ceremony, photos, first dance, send-off.
            </div>
            <button onClick={() => setEditingEvent('new')} style={{
              marginTop: 14, padding: '10px 18px',
              background: W.ink, color: W.bg, border: 'none', borderRadius: 999,
              fontFamily: FONT_UI, fontSize: 13, fontWeight: 500, cursor: 'pointer',
            }}>+ Add first event</button>
          </div>
        ) : (
          <>
            {/* Spine */}
            <div style={{
              position: 'absolute', left: 86, top: 4, bottom: 4,
              width: 0.5, background: W.line,
            }}/>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              {timeline.all.map((e) => (
                <TimelineRow
                  key={e.id}
                  event={e}
                  onEdit={() => setEditingEvent(e)}
                />
              ))}
            </div>
          </>
        )}
      </div>

      {/* Emergency contacts */}
      <div style={{
        display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
        padding: '0 22px 6px',
      }}>
        <SectionTitle eyebrow="Reach out" title="Emergency contacts"/>
        <button onClick={() => setEditingContact('new')} style={{
          background: 'transparent', border: 'none', cursor: 'pointer',
          fontFamily: FONT_UI, fontSize: 12.5, fontWeight: 500, color: W.clay,
          padding: 4,
        }}>+ Add contact</button>
      </div>
      <div style={{ padding: '0 16px 26px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {emergency.all.length === 0 ? (
          <div style={{
            padding: '20px 16px', textAlign: 'center',
            background: W.cardSoft, border: `0.5px dashed ${W.line}`, borderRadius: 12,
          }}>
            <div style={{
              fontFamily: FONT_UI, fontSize: 12.5, color: W.muted, lineHeight: 1.5,
            }}>
              Day-of planner, maid of honor, venue manager, officiant · whoever
              your bridal party needs to reach in a pinch.
            </div>
          </div>
        ) : emergency.all.map(c => (
          <Card key={c.id} onClick={() => setEditingContact(c)} style={{
            padding: 14, display: 'flex', alignItems: 'center', gap: 12,
            cursor: 'pointer',
          }}>
            <div style={{
              width: 40, height: 40, borderRadius: 999, background: '#fbf6ea',
              border: `0.5px solid ${W.lineSoft}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              flexShrink: 0,
            }}>
              <Icon name="bell" size={16} color={W.clayDeep} strokeWidth={1.4}/>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{
                fontFamily: FONT_UI, fontSize: 10.5, fontWeight: 600,
                letterSpacing: 1.2, color: W.muted, textTransform: 'uppercase',
              }}>{c.role || 'Contact'}</div>
              <div style={{
                fontFamily: FONT_UI, fontSize: 14.5, fontWeight: 500, color: W.ink, marginTop: 2,
                whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
              }}>{c.name || 'Untitled'}</div>
            </div>
            {c.phone && (
              <a
                href={`tel:${c.phone.replace(/[^0-9+]/g, '')}`}
                onClick={(e) => e.stopPropagation()}
                style={{
                  fontFamily: FONT_MONO, fontSize: 12, color: W.clay,
                  textDecoration: 'none',
                }}>
                {c.phone}
              </a>
            )}
          </Card>
        ))}
      </div>

      {editingEvent && (
        <FormSheet
          title={editingEvent === 'new' ? 'Add timeline event' : 'Edit event'}
          eyebrow={editingEvent === 'new' ? 'New' : 'Edit'}
          fields={timelineFields()}
          initial={editingEvent === 'new' ? {} : editingEvent}
          submitLabel={editingEvent === 'new' ? 'Add' : 'Save'}
          onClose={() => setEditingEvent(null)}
          onSubmit={submitEvent}
          onDelete={editingEvent !== 'new' ? () => {
            timeline.deleteTimelineEvent(editingEvent.id);
            setEditingEvent(null);
          } : null}
        />
      )}
      {editingContact && (
        <FormSheet
          title={editingContact === 'new' ? 'Add emergency contact' : 'Edit contact'}
          eyebrow={editingContact === 'new' ? 'New' : 'Edit'}
          fields={emergencyFields()}
          initial={editingContact === 'new' ? {} : editingContact}
          submitLabel={editingContact === 'new' ? 'Add' : 'Save'}
          onClose={() => setEditingContact(null)}
          onSubmit={submitContact}
          onDelete={editingContact !== 'new' ? () => {
            emergency.deleteEmergencyContact(editingContact.id);
            setEditingContact(null);
          } : null}
        />
      )}
    </div>
  );
}

function TimelineRow({ event, onEdit }) {
  const color = KIND_COLORS[event.kind] || W.clay;
  const isHero = event.hero;
  return (
    <div
      onClick={onEdit}
      style={{
        display: 'grid', gridTemplateColumns: '70px 1fr', gap: 16,
        padding: '10px 0', alignItems: 'flex-start', position: 'relative',
        cursor: onEdit ? 'pointer' : 'default',
        borderRadius: 8, transition: 'background 120ms ease',
      }}
      onMouseEnter={(e) => onEdit && (e.currentTarget.style.background = 'rgba(168,122,79,0.04)')}
      onMouseLeave={(e) => onEdit && (e.currentTarget.style.background = 'transparent')}
    >
      <div style={{
        textAlign: 'right', paddingRight: 4,
        fontFamily: FONT_DISPLAY, fontSize: isHero ? 17 : 15,
        color: isHero ? W.ink : W.ink2, letterSpacing: -0.1,
        lineHeight: 1.3, paddingTop: 4,
      }}>{event.time}</div>

      {/* Dot on the spine */}
      <div style={{
        position: 'absolute', left: 70, top: 14,
        width: isHero ? 12 : 8, height: isHero ? 12 : 8, borderRadius: 999,
        background: isHero ? color : W.bg,
        border: `1.5px solid ${color}`,
        transform: 'translateX(-50%)',
      }}/>

      <div style={{ paddingLeft: 22, paddingTop: 2 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <Icon name={event.icon} size={14} color={color} strokeWidth={1.4}/>
          <div style={{
            fontFamily: FONT_UI, fontSize: isHero ? 15 : 14, fontWeight: 500,
            color: W.ink, lineHeight: 1.3,
          }}>{event.title}</div>
        </div>
        <div style={{
          fontFamily: FONT_UI, fontSize: 12, color: W.muted, marginTop: 3,
        }}>{event.where}</div>
        {event.note && (
          <div style={{
            fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 13.5,
            color: W.ink2, marginTop: 6, lineHeight: 1.4,
          }}>{event.note}</div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { DayOfScreen });
