// Wedding Party — store-backed, full CRUD via FormSheet.

const PARTY_SECTIONS = [
  { value: 'bridal',  label: 'Bridal party' },
  { value: 'groom',   label: 'Groom\u2019s side' },
  { value: 'family',  label: 'Family' },
  { value: 'special', label: 'Special role' },
];

const PARTY_SIDES = [
  { value: 'sloane', label: 'Side 1' },
  { value: 'theo',   label: 'Side 2' },
  { value: 'both',   label: 'Both' },
];

function partyFields(weddingBrides, weddingGroom) {
  return [
    { name: 'name', label: 'Name', type: 'text',
      placeholder: 'e.g. Amelia Park' },
    { name: 'role', label: 'Role', type: 'text',
      placeholder: 'e.g. Maid of Honor, Bridesmaid, Ring Bearer' },
    { name: 'section', label: 'Section', type: 'choice', default: 'bridal',
      options: PARTY_SECTIONS },
    { name: 'side',    label: 'Side',    type: 'choice', default: 'sloane',
      options: [
        { value: 'sloane', label: weddingBrides || 'Side 1' },
        { value: 'theo',   label: weddingGroom  || 'Side 2' },
        { value: 'both',   label: 'Both' },
      ]},
  ];
}

function WeddingPartyScreen() {
  const wedding = useWedding();
  const party = useParty();
  const [editing, setEditing] = React.useState(null);

  const submitMember = (values) => {
    if (editing === 'new') party.addPartyMember(values);
    else party.updatePartyMember(editing.id, values);
    setEditing(null);
  };

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

  const isEmpty = party.total === 0;

  return (
    <div style={{ background: W.bg, paddingBottom: 28, position: 'relative' }}>
      <div style={{ paddingTop: 56 }}/>

      <ScreenHeader
        eyebrow="Wedding party"
        title={isEmpty
          ? 'Choose your people'
          : `${party.total} ${party.total === 1 ? 'standing with you' : 'standing with you'}`}
      />

      {isEmpty ? (
        <EmptyParty onAdd={() => setEditing('new')}/>
      ) : (
        <>
          {/* Hero strip — only if a wedding has been set up */}
          {(wedding.brides || wedding.groom) && (
            <div style={{ padding: '8px 16px 18px' }}>
              <Card soft style={{ padding: '22px 20px' }}>
                <div style={{
                  fontFamily: FONT_UI, fontSize: 10.5, fontWeight: 600,
                  letterSpacing: 1.8, textTransform: 'uppercase', color: W.muted,
                }}>The Wedding of</div>
                <div style={{
                  fontFamily: FONT_DISPLAY, fontSize: 30, fontWeight: 500,
                  color: W.ink, letterSpacing: -0.2, lineHeight: 1.1, marginTop: 6,
                }}>
                  {wedding.brides || 'You'} <span style={{ fontStyle: 'italic' }}>&amp;</span> {wedding.groom || 'Yours'}
                </div>
                <div style={{
                  fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 14.5,
                  color: W.ink2, marginTop: 8, lineHeight: 1.5,
                }}>
                  With these dear people beside us
                  {wedding.dateLabel ? ` on ${wedding.dateLabel}.` : '.'}
                </div>
              </Card>
            </div>
          )}

          {party.bridal.length > 0 && (
            <PartySection
              eyebrow={`${wedding.brides || 'Side 1'}\u2019s side`}
              title="Bridal party"
              people={party.bridal}
              onEdit={(p) => setEditing(p)}/>
          )}
          {party.groom.length > 0 && (
            <PartySection
              eyebrow={`${wedding.groom || 'Side 2'}\u2019s side`}
              title="Groomsmen"
              people={party.groom}
              onEdit={(p) => setEditing(p)}/>
          )}

          {party.family.length > 0 && (
            <>
              <SectionTitle eyebrow="Family" title="Parents"/>
              <div style={{
                display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8,
                padding: '0 16px 24px',
              }}>
                {party.family.map(p => (
                  <PartyTile key={p.id} person={p} compact onClick={() => setEditing(p)}/>
                ))}
              </div>
            </>
          )}

          {party.special.length > 0 && (
            <>
              <SectionTitle eyebrow="With love" title="Special roles"/>
              <div style={{
                padding: '0 16px 28px', display: 'flex', flexDirection: 'column', gap: 8,
              }}>
                {party.special.map(p => (
                  <SpecialRow key={p.id} person={p} onClick={() => setEditing(p)}/>
                ))}
              </div>
            </>
          )}

          {/* Add member */}
          <div style={{ padding: '4px 16px 24px' }}>
            <button onClick={() => setEditing('new')} style={{
              width: '100%', padding: '14px 0',
              background: W.ink, color: W.bg, border: 'none', borderRadius: 999,
              cursor: 'pointer',
              fontFamily: FONT_UI, fontSize: 14, fontWeight: 500,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            }}>
              <Icon name="plus" size={15} color={W.bg} strokeWidth={1.8}/>
              Add to wedding party
            </button>
          </div>

          {/* Footer poem */}
          <div style={{ padding: '0 24px 32px', textAlign: 'center' }}>
            <div style={{
              fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 14,
              color: W.muted, lineHeight: 1.6, maxWidth: 320, margin: '0 auto',
            }}>
              &ldquo;A wedding is a portrait of the love that surrounds you.&rdquo;
            </div>
          </div>
        </>
      )}

      {editing && (
        <FormSheet
          title={editing === 'new' ? 'Add to wedding party' : 'Edit'}
          eyebrow={editing === 'new' ? 'New entry' : 'Edit'}
          fields={partyFields(wedding.brides, wedding.groom)}
          initial={editing === 'new' ? {} : editing}
          submitLabel={editing === 'new' ? 'Add' : 'Save'}
          onClose={() => setEditing(null)}
          onSubmit={submitMember}
          onDelete={editing !== 'new' ? deleteCurrent : null}
        />
      )}
    </div>
  );
}

function EmptyParty({ onAdd }) {
  return (
    <div style={{
      padding: '60px 28px 80px',
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      textAlign: 'center',
    }}>
      <div style={{
        width: 64, height: 64, borderRadius: 999,
        background: W.cardSoft, border: `0.5px solid ${W.line}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        marginBottom: 22,
      }}>
        <Icon name="heart" size={26} color={W.clay} strokeWidth={1.4}/>
      </div>
      <div style={{
        fontFamily: FONT_DISPLAY, fontSize: 28, fontWeight: 500,
        color: W.ink, letterSpacing: -0.3, lineHeight: 1.1,
      }}>The people who'll<br/>
        <span style={{ fontStyle: 'italic' }}>stand with you.</span>
      </div>
      <div style={{
        fontFamily: FONT_UI, fontSize: 13.5, color: W.muted,
        marginTop: 14, lineHeight: 1.55, maxWidth: 280,
      }}>
        Maid of honor, best man, parents, officiant. Add each person with their role
        — they'll appear in your reports and day-of timeline.
      </div>
      <button onClick={onAdd} style={{
        marginTop: 28, padding: '14px 22px',
        background: W.ink, color: W.bg, border: 'none', borderRadius: 999,
        cursor: 'pointer',
        fontFamily: FONT_UI, fontSize: 14, fontWeight: 500,
        display: 'flex', alignItems: 'center', gap: 8,
      }}>
        <Icon name="plus" size={15} color={W.bg} strokeWidth={1.8}/>
        Add your first
      </button>
    </div>
  );
}

function PartySection({ eyebrow, title, people, onEdit }) {
  return (
    <>
      <SectionTitle eyebrow={eyebrow} title={title}/>
      <div style={{
        padding: '0 16px 24px', display: 'flex', flexDirection: 'column', gap: 8,
      }}>
        {people.map((p) => (
          <PartyTile key={p.id} person={p} onClick={() => onEdit && onEdit(p)}/>
        ))}
      </div>
    </>
  );
}

function PartyTile({ person, compact = false, onClick }) {
  const isPrimary = /Maid of Honor|Best Man/i.test(person.role || '');
  const sideColor = person.side === 'theo' ? W.sage : W.clay;
  return (
    <Card onClick={onClick} style={{
      padding: compact ? 12 : 14,
      display: 'flex', alignItems: 'center', gap: 12,
      cursor: onClick ? 'pointer' : 'default',
    }}>
      <div style={{
        width: compact ? 42 : 48, height: compact ? 42 : 48, borderRadius: 999,
        background: isPrimary ? sideColor : '#fbf6ea',
        border: `0.5px solid ${isPrimary ? sideColor : W.lineSoft}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
        fontFamily: FONT_DISPLAY, fontSize: compact ? 16 : 18, fontWeight: 500,
        color: isPrimary ? W.bg : W.ink,
      }}>{initials(person.name || '?')}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: FONT_DISPLAY, fontSize: compact ? 16 : 18, color: W.ink,
          letterSpacing: -0.1, lineHeight: 1.1,
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        }}>{person.name || <span style={{ color: W.muted, fontStyle: 'italic' }}>(unnamed)</span>}</div>
        {person.role && (
          <div style={{
            fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 12.5,
            color: W.ink2, marginTop: 3,
          }}>{person.role}</div>
        )}
      </div>
      {isPrimary && (
        <Pill tone={person.side === 'theo' ? 'sage' : 'clay'} style={{ fontSize: 9 }}>
          Lead
        </Pill>
      )}
    </Card>
  );
}

function SpecialRow({ person, onClick }) {
  const iconByRole = (role) => {
    const r = (role || '').toLowerCase();
    if (r.includes('officiant')) return 'sparkle';
    if (r.includes('ring'))      return 'rings';
    if (r.includes('flower'))    return 'leaf';
    if (r.includes('reader'))    return 'flag';
    if (r.includes('usher'))     return 'home';
    return 'heart';
  };
  return (
    <Card onClick={onClick} style={{
      padding: 14, display: 'flex', alignItems: 'center', gap: 12,
      cursor: onClick ? 'pointer' : 'default',
    }}>
      <div style={{
        width: 42, height: 42, borderRadius: 999, background: W.cardSoft,
        border: `0.5px solid ${W.lineSoft}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        <Icon name={iconByRole(person.role)} size={17} color={W.clay} strokeWidth={1.4}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: FONT_UI, fontSize: 10.5, fontWeight: 600,
          letterSpacing: 1.4, textTransform: 'uppercase', color: W.muted,
        }}>{person.role || 'Role'}</div>
        <div style={{
          fontFamily: FONT_DISPLAY, fontSize: 17, color: W.ink, marginTop: 3,
        }}>{person.name || <em style={{ color: W.muted }}>(unnamed)</em>}</div>
      </div>
    </Card>
  );
}

Object.assign(window, { WeddingPartyScreen });
