// Guests / RSVP screen — fully store-backed with Add/Edit/Delete.

// Guest group chips · personalized with the wedding partners' names where set.
function makeGuestGroups(brides, groom) {
  const a = (brides || '').trim().split(/\s+/)[0] || 'You';
  const b = (groom || '').trim().split(/\s+/)[0] || 'Partner';
  return [
    `Family · ${a}`, `Family · ${b}`,
    'Bridesmaid', 'Groomsman', 'Wedding party',
    'College', 'High school', 'Childhood',
    `Work · ${a}`, `Work · ${b}`,
    'Neighbors', 'Other',
  ];
}

const MEAL_OPTIONS = [
  'Wild salmon', 'Roasted duck', 'Heirloom risotto',
  'Children\u2019s plate',
];

function guestFields(allGroups, allMeals) {
  return [
    { name: 'name', label: 'Name or household', type: 'text',
      placeholder: 'e.g. Margaret & David Chen' },
    { name: 'group', label: 'Group', type: 'choice',
      options: allGroups.map(g => ({ value: g, label: g })) },
    { name: 'partySize', label: 'Party size', type: 'number',
      min: 1, max: 8, default: 1, unit: 'people' },
    { name: 'status', label: 'RSVP', type: 'choice', default: 'pending',
      options: [
        { value: 'pending',   label: 'Pending'   },
        { value: 'attending', label: 'Attending', color: '#6f8a6a' },
        { value: 'declined',  label: 'Declined',  color: '#9d8d77' },
      ] },
    { name: 'meal', label: 'Meal', type: 'choice',
      showWhen: (v) => v.status === 'attending',
      options: [{ value: '', label: 'No selection' },
        ...allMeals.map(m => ({ value: m, label: m })),
      ] },
    { name: 'plus', label: 'Bringing a plus-one', type: 'toggle',
      hint: 'Counts as 1 additional person' },
    { name: 'plusName', label: 'Plus-one name', type: 'text',
      showWhen: (v) => v.plus,
      placeholder: 'Their name' },
    { name: 'dietary', label: 'Dietary notes', type: 'text',
      placeholder: 'Vegan, Gluten-free, Nut allergy…' },
  ];
}

function GuestsScreen() {
  const guests = useGuests();
  const wedding = useWedding();
  const guestGroups = React.useMemo(
    () => makeGuestGroups(wedding.brides, wedding.groom),
    [wedding.brides, wedding.groom]
  );
  const [filter, setFilter] = React.useState('all');
  const [editing, setEditing] = React.useState(null); // null | 'new' | guest object
  const [query, setQuery] = React.useState('');

  const total = guests.total;
  const filtered = guests.all
    .filter(g => filter === 'all' ? true : g.status === filter)
    .filter(g => !query ? true :
      g.name.toLowerCase().includes(query.toLowerCase()) ||
      (g.group || '').toLowerCase().includes(query.toLowerCase()) ||
      (g.dietary || '').toLowerCase().includes(query.toLowerCase()));

  const isEmpty = guests.all.length === 0;

  const submitGuest = (values) => {
    if (editing === 'new') guests.addGuest(values);
    else guests.updateGuest(editing.id, values);
    setEditing(null);
  };

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

  return (
    <div style={{ background: W.bg, paddingBottom: 28, position: 'relative' }}>
      <div style={{ paddingTop: 56 }}/>
      <ScreenHeader eyebrow="Guests" title={`${total} invited`}/>

      {isEmpty ? (
        <EmptyGuests onAdd={() => setEditing('new')}/>
      ) : (
        <>
          {/* Hero RSVP card */}
          <div style={{ padding: '8px 16px 16px' }}>
            <Card style={{ padding: 22 }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 18 }}>
                <div style={{ flex: 1 }}>
                  <div style={{
                    fontFamily: FONT_UI, fontSize: 10.5, fontWeight: 600,
                    letterSpacing: 1.4, textTransform: 'uppercase', color: W.muted,
                  }}>Responded</div>
                  <div style={{
                    fontFamily: FONT_DISPLAY, fontSize: 52, fontWeight: 500,
                    color: W.ink, letterSpacing: -1.6, lineHeight: 0.95, marginTop: 6,
                  }}>
                    {guests.attending + guests.declined}
                    <span style={{ color: W.faint, fontSize: 32, letterSpacing: -0.6 }}>/{total}</span>
                  </div>
                  <div style={{
                    fontFamily: FONT_UI, fontSize: 13, color: W.ink2, marginTop: 10,
                  }}>
                    {guests.pending > 0
                      ? `${guests.pending} still pending`
                      : 'Everyone has responded'}
                  </div>
                </div>
                <RsvpDonut g={guests}/>
              </div>

              <div style={{
                marginTop: 22, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10,
                paddingTop: 18, borderTop: `0.5px solid ${W.lineSoft}`,
              }}>
                <LegendStat dotColor={W.sage}  label="Attending" value={guests.attending}/>
                <LegendStat dotColor={W.clay}  label="Pending"   value={guests.pending}/>
                <LegendStat dotColor={W.faint} label="Declined"  value={guests.declined}/>
              </div>
            </Card>
          </div>

          {/* Dietary alert — only if any */}
          {guests.dietary.length > 0 && (
            <div style={{ padding: '0 16px 18px' }}>
              <div style={{
                background: '#f3dfd9', borderRadius: 16,
                padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 12,
                border: `0.5px solid #ebcabd`,
              }}>
                <div style={{
                  width: 28, height: 28, borderRadius: 999, background: '#d9988b',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  color: '#fff', fontFamily: FONT_DISPLAY, fontWeight: 600, fontSize: 16,
                  flexShrink: 0,
                }}>{guests.dietary.length}</div>
                <div style={{ flex: 1 }}>
                  <div style={{
                    fontFamily: FONT_UI, fontSize: 13.5, fontWeight: 500, color: '#7d4a3f',
                  }}>Dietary notes to track</div>
                  <div style={{
                    fontFamily: FONT_UI, fontSize: 12, color: '#8d5949', marginTop: 1,
                    whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                  }}>
                    {guests.dietary.map(d => `${d.count} ${d.label}`).join(' · ')}
                  </div>
                </div>
                <Icon name="chevron" size={14} color="#7d4a3f"/>
              </div>
            </div>
          )}

          {/* Meal breakdown */}
          {Object.keys(guests.meals).length > 0 && (
            <div style={{ padding: '0 22px 12px' }}>
              <div style={{
                fontFamily: FONT_UI, fontSize: 10.5, fontWeight: 600,
                letterSpacing: 1.6, textTransform: 'uppercase', color: W.muted,
                marginBottom: 10,
              }}>Meal selections</div>
              <div style={{
                display: 'flex', gap: 10, overflowX: 'auto', paddingBottom: 4,
              }}>
                {Object.entries(guests.meals).map(([k, v]) => (
                  <div key={k} style={{
                    padding: '12px 14px', background: W.card, borderRadius: 14,
                    border: `0.5px solid ${W.line}`, minWidth: 130, flexShrink: 0,
                  }}>
                    <div style={{
                      fontFamily: FONT_DISPLAY, fontSize: 24, color: W.ink, letterSpacing: -0.3,
                    }}>{v}</div>
                    <div style={{
                      fontFamily: FONT_UI, fontSize: 12, color: W.ink2, marginTop: 2,
                    }}>{k}</div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Search */}
          <div style={{ padding: '8px 16px 14px' }}>
            <div style={{
              background: W.card, borderRadius: 14, border: `0.5px solid ${W.line}`,
              display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px',
            }}>
              <Icon name="search" size={16} color={W.muted}/>
              <input
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="Search guests, households, dietary…"
                style={{
                  flex: 1, border: 'none', background: 'transparent', outline: 'none',
                  fontFamily: FONT_UI, fontSize: 14, color: W.ink,
                }}
              />
            </div>
          </div>

          {/* Filter chips */}
          <div style={{
            display: 'flex', gap: 8, padding: '0 22px 14px',
            overflowX: 'auto',
          }}>
            {[
              ['all',       'All',       total],
              ['attending', 'Attending', guests.attending],
              ['pending',   'Pending',   guests.pending],
              ['declined',  'Declined',  guests.declined],
            ].map(([k, label, n]) => {
              const active = filter === k;
              return (
                <button key={k} onClick={() => setFilter(k)} style={{
                  background: active ? W.ink : 'transparent',
                  border: active ? 'none' : `0.5px solid ${W.line}`,
                  color: active ? W.bg : W.ink2,
                  fontFamily: FONT_UI, fontSize: 12.5, fontWeight: 500,
                  padding: '7px 12px', borderRadius: 999, cursor: 'pointer',
                  whiteSpace: 'nowrap', display: 'flex', alignItems: 'center', gap: 6,
                }}>
                  {label}
                  <span style={{
                    fontSize: 10.5, color: active ? 'rgba(245,239,226,0.55)' : W.muted, fontWeight: 600,
                  }}>{n}</span>
                </button>
              );
            })}
          </div>

          {/* Guest list */}
          <div style={{
            padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 8,
          }}>
            {filtered.length === 0 ? (
              <Card style={{ padding: 20, textAlign: 'center' }}>
                <div style={{
                  fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 14,
                  color: W.muted,
                }}>No guests match this filter.</div>
              </Card>
            ) : (
              filtered.map((g) => (
                <GuestRow key={g.id} g={g} onClick={() => setEditing(g)}/>
              ))
            )}
          </div>

          {/* Add guest — floating-ish at bottom of list */}
          <div style={{ padding: '20px 16px 4px' }}>
            <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 guest
            </button>
          </div>
        </>
      )}

      {editing && (
        <FormSheet
          title={editing === 'new' ? 'Add a guest' : 'Edit guest'}
          eyebrow={editing === 'new' ? 'New entry' : 'Edit'}
          fields={guestFields(guestGroups, MEAL_OPTIONS)}
          initial={editing === 'new' ? {} : editing}
          submitLabel={editing === 'new' ? 'Add guest' : 'Save'}
          onClose={() => setEditing(null)}
          onSubmit={submitGuest}
          onDelete={editing !== 'new' ? deleteCurrent : null}
        />
      )}
    </div>
  );
}

function EmptyGuests({ 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="users" 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,
      }}>Your guest list,<br/>
        <span style={{ fontStyle: 'italic' }}>fresh and waiting.</span>
      </div>
      <div style={{
        fontFamily: FONT_UI, fontSize: 13.5, color: W.muted,
        marginTop: 14, lineHeight: 1.55, maxWidth: 280,
      }}>
        Add a guest or household to start tracking RSVPs, meals, and dietary notes.
        Your seating plan and reports will fill in automatically.
      </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 guest
      </button>
    </div>
  );
}

function RsvpDonut({ g }) {
  const size = 96, stroke = 12;
  const r = (size - stroke) / 2;
  const C = 2 * Math.PI * r;
  const t = Math.max(1, g.total);
  const attPct = g.attending / t;
  const decPct = g.declined  / t;
  const penPct = g.pending   / t;

  return (
    <div style={{ position: 'relative', width: size, height: size, flexShrink: 0 }}>
      <svg width={size} height={size} style={{ transform: 'rotate(-90deg)' }}>
        <circle cx={size/2} cy={size/2} r={r} stroke={W.lineSoft} strokeWidth={stroke} fill="none"/>
        <circle cx={size/2} cy={size/2} r={r} stroke={W.sage} strokeWidth={stroke} fill="none"
          strokeDasharray={`${C * attPct} ${C}`} strokeDashoffset={0}/>
        <circle cx={size/2} cy={size/2} r={r} stroke={W.clay} strokeWidth={stroke} fill="none"
          strokeDasharray={`${C * penPct} ${C}`} strokeDashoffset={-C * attPct}/>
        <circle cx={size/2} cy={size/2} r={r} stroke={W.faint} strokeWidth={stroke} fill="none"
          strokeDasharray={`${C * decPct} ${C}`} strokeDashoffset={-C * (attPct + penPct)}/>
      </svg>
      <div style={{
        position: 'absolute', inset: 0, display: 'flex',
        flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      }}>
        <div style={{
          fontFamily: FONT_DISPLAY, fontSize: 18, color: W.ink, letterSpacing: -0.3, lineHeight: 1,
        }}>{Math.round(attPct * 100)}%</div>
        <div style={{
          fontFamily: FONT_UI, fontSize: 9, fontWeight: 600,
          letterSpacing: 1, color: W.muted, marginTop: 3, textTransform: 'uppercase',
        }}>Yes</div>
      </div>
    </div>
  );
}

function LegendStat({ dotColor, label, value }) {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
        <div style={{
          width: 7, height: 7, borderRadius: 999, background: dotColor,
        }}/>
        <div style={{
          fontFamily: FONT_UI, fontSize: 10.5, fontWeight: 600,
          letterSpacing: 1.2, color: W.muted, textTransform: 'uppercase',
        }}>{label}</div>
      </div>
      <div style={{
        fontFamily: FONT_DISPLAY, fontSize: 22, color: W.ink, letterSpacing: -0.3, lineHeight: 1,
      }}>{value}</div>
    </div>
  );
}

function avatarBg(name) {
  const palette = ['#e0c9b2', '#d4b9a4', '#cdb491', '#bcbfa6', '#d6c4c0', '#c2a98e'];
  let h = 0;
  for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) | 0;
  return palette[Math.abs(h) % palette.length];
}

function initials(name) {
  if (!name) return '?';
  const parts = name.replace(/\(.*\)/, '').split(/[&,]/)[0].trim().split(/\s+/);
  return ((parts[0]?.[0] || '') + (parts[1]?.[0] || '')).toUpperCase() || '?';
}

function GuestRow({ g, onClick }) {
  const statusMeta = {
    attending: { tone: 'sage',    label: 'Attending' },
    pending:   { tone: 'clay',    label: 'Pending'   },
    declined:  { tone: 'neutral', label: 'Declined'  },
  }[g.status] || { tone: 'neutral', label: g.status };
  return (
    <Card onClick={onClick} style={{
      padding: 14, display: 'flex', alignItems: 'center', gap: 12,
      cursor: onClick ? 'pointer' : 'default',
    }}>
      <div style={{
        width: 40, height: 40, borderRadius: 999,
        background: avatarBg(g.name || '?'), color: W.ink,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: FONT_DISPLAY, fontSize: 15, fontWeight: 500, letterSpacing: -0.2,
        flexShrink: 0,
      }}>{initials(g.name)}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: FONT_UI, fontSize: 14.5, fontWeight: 500, color: W.ink,
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        }}>
          {g.name || <span style={{ color: W.muted, fontStyle: 'italic' }}>(unnamed)</span>}
          {g.plus && <span style={{ color: W.muted, fontWeight: 400, fontSize: 12.5 }}>
            {g.plusName ? ` & ${g.plusName}` : ' +1'}
          </span>}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 4 }}>
          <span style={{
            fontFamily: FONT_UI, fontSize: 11.5, color: W.muted,
          }}>{g.group || 'Ungrouped'}</span>
          {g.partySize > 1 && (
            <>
              <span style={{ color: W.faint, fontSize: 10 }}>·</span>
              <span style={{ fontFamily: FONT_UI, fontSize: 11.5, color: W.ink2 }}>
                Party of {g.partySize}
              </span>
            </>
          )}
          {g.meal && (
            <>
              <span style={{ color: W.faint, fontSize: 10 }}>·</span>
              <span style={{ fontFamily: FONT_UI, fontSize: 11.5, color: W.ink2 }}>{g.meal}</span>
            </>
          )}
          {g.dietary && (
            <>
              <span style={{ color: W.faint, fontSize: 10 }}>·</span>
              <span style={{
                fontFamily: FONT_UI, fontStyle: 'italic', fontSize: 11.5, color: W.amber,
              }}>{g.dietary}</span>
            </>
          )}
        </div>
      </div>
      <Pill tone={statusMeta.tone} style={{ padding: '3px 8px', fontSize: 9.5 }}>{statusMeta.label}</Pill>
    </Card>
  );
}

Object.assign(window, { GuestsScreen });
