// guestlist.jsx — Gæsteliste-fanen
const { useState: useStateG, useRef: useRefG, useMemo: useMemoG } = React;

function GuestList({ project, addGuest, updateGuest, removeGuest, addRule, removeRule, addGroup, goToSettings }) {
  const DIET = window.PlaniqData.DIET_TYPES;
  const [q, setQ] = useStateG('');
  const [filter, setFilter] = useStateG('all'); // all | unplaced | placed | group id
  const [addToGroup, setAddToGroup] = useStateG(project.groups[0]?.id || '');
  const [quickName, setQuickName] = useStateG('');
  const [editing, setEditing] = useStateG(null);
  const inputRef = useRefG(null);

  const groups = project.groups;
  const groupById = (id) => groups.find(x => x.id === id);

  const filtered = useMemoG(() => {
    let list = project.guests;
    if (q.trim()) list = list.filter(g => g.name.toLowerCase().includes(q.toLowerCase()));
    if (filter === 'unplaced') list = list.filter(g => !g.seat);
    else if (filter === 'placed') list = list.filter(g => g.seat);
    else if (filter !== 'all') list = list.filter(g => g.group === filter);
    return list;
  }, [project.guests, q, filter]);

  // group the filtered list by group for display
  const grouped = useMemoG(() => {
    const map = {};
    filtered.forEach(g => { (map[g.group] = map[g.group] || []).push(g); });
    return groups.map(gr => ({ group: gr, items: map[gr.id] || [] })).filter(x => x.items.length);
  }, [filtered, groups]);

  const total = project.guests.length;
  const placed = project.guests.filter(g => g.seat).length;
  const heads = project.guests.reduce((s, g) => s + 1 + (g.plusOne ? 1 : 0), 0);

  const submitQuick = () => {
    const name = quickName.trim();
    if (!name) return;
    // Fald tilbage til første gruppe hvis valget er tomt/forældet (fx lige efter første gruppe blev oprettet).
    const groupId = groups.some(g => g.id === addToGroup) ? addToGroup : groups[0].id;
    addGuest({ name, group: groupId });
    setQuickName('');
    inputRef.current && inputRef.current.focus();
  };

  // Man skal oprette mindst én gruppe, før gæster kan tilføjes.
  // (Renderes her — efter alle hooks — så React altid kalder samme antal hooks.)
  if (groups.length === 0) {
    return <NoGroupsGate addGroup={addGroup} goToSettings={goToSettings} />;
  }

  return (
    <div className="row" style={{ height: '100%', alignItems: 'stretch' }}>
      <div className="col" style={{ flex: 1, minWidth: 0 }}>
        {/* quick add */}
        <div style={{ padding: '20px 28px 16px', borderBottom: '1px solid var(--line)', background: 'var(--surface)' }}>
          <div className="row gap-3" style={{ alignItems: 'stretch', flexWrap: 'wrap' }}>
            <div className="row" style={{ flex: 1, minWidth: 280, gap: 0, background: 'var(--surface)', border: '1.5px solid var(--line-2)', borderRadius: 'var(--radius-pill)', paddingLeft: 18, overflow: 'hidden' }}>
              <Icon name="plus" size={20} color="var(--accent)" />
              <input ref={inputRef} className="input" style={{ border: 'none', background: 'transparent', boxShadow: 'none', flex: 1 }}
                placeholder="Tilføj gæst — tast navn og tryk Enter…" value={quickName}
                onChange={e => setQuickName(e.target.value)}
                onKeyDown={e => { if (e.key === 'Enter') submitQuick(); }} />
            </div>
            <GroupPicker groups={groups} value={addToGroup} onChange={setAddToGroup} />
            <button className="btn btn-primary" onClick={submitQuick} disabled={!quickName.trim()}>Tilføj</button>
          </div>
        </div>

        {/* filter bar */}
        <div className="row gap-2" style={{ padding: '14px 28px', flexWrap: 'wrap', borderBottom: '1px solid var(--line)' }}>
          <div className="row" style={{ background: 'var(--surface)', border: '1.5px solid var(--line-2)', borderRadius: 'var(--radius-pill)', paddingLeft: 14, marginRight: 'auto', minWidth: 200, flex: '0 1 280px' }}>
            <Icon name="search" size={18} color="var(--ink-faint)" />
            <input className="input" style={{ border: 'none', background: 'transparent', boxShadow: 'none', minHeight: 42 }} placeholder="Søg…" value={q} onChange={e => setQ(e.target.value)} />
          </div>
          <FilterChip active={filter==='all'} onClick={() => setFilter('all')}>Alle {total}</FilterChip>
          <FilterChip active={filter==='unplaced'} onClick={() => setFilter('unplaced')} dot="var(--honey)">Ikke placeret {total-placed}</FilterChip>
          <FilterChip active={filter==='placed'} onClick={() => setFilter('placed')} dot="var(--sage)">Placeret {placed}</FilterChip>
        </div>

        {/* list */}
        <div className="scroll" style={{ flex: 1, padding: '8px 28px 40px' }}>
          {total === 0 && <EmptyGuests onFocus={() => inputRef.current && inputRef.current.focus()} />}
          {total > 0 && filtered.length === 0 && (
            <p className="muted center" style={{ padding: 50, fontSize: 17 }}>Ingen gæster matcher.</p>
          )}
          {grouped.map(({ group, items }) => (
            <div key={group.id} style={{ marginTop: 22 }}>
              <div className="row gap-2" style={{ marginBottom: 10, paddingLeft: 4 }}>
                <span className={"dot gc-" + group.color} style={{ width: 11, height: 11, borderRadius: '50%' }}></span>
                <h4 style={{ fontSize: 16, color: 'var(--ink-soft)' }}>{group.name}</h4>
                <span className="faint" style={{ fontSize: 14, fontWeight: 700 }}>{items.length}</span>
              </div>
              <div className="col gap-2">
                {items.map(g => <GuestRow key={g.id} g={g} group={group} onEdit={() => setEditing(g)} />)}
              </div>
            </div>
          ))}
        </div>
      </div>

      {editing && <GuestEditor guest={editing} project={project} onClose={() => setEditing(null)}
        updateGuest={updateGuest} removeGuest={removeGuest} addRule={addRule} removeRule={removeRule} />}
    </div>
  );
}

function GroupPicker({ groups, value, onChange }) {
  const [open, setOpen] = useStateG(false);
  const cur = groups.find(g => g.id === value) || groups[0];
  return (
    <div style={{ position: 'relative' }}>
      <button className="btn" style={{ minWidth: 170, justifyContent: 'space-between' }} onClick={() => setOpen(o => !o)}>
        <span className="row gap-2"><span className={"dot gc-" + (cur?.color||1)} style={{ width: 10, height: 10, borderRadius: '50%' }}></span>{cur?.name}</span>
        <Icon name="chevD" size={18} />
      </button>
      {open && (
        <>
          <div style={{ position: 'fixed', inset: 0, zIndex: 30 }} onPointerDown={() => setOpen(false)}></div>
          <div className="card anim-pop" style={{ position: 'absolute', top: 56, left: 0, zIndex: 31, padding: 7, width: 210, borderRadius: 16 }}>
            {groups.map(g => (
              <button key={g.id} className="row gap-3" onClick={() => { onChange(g.id); setOpen(false); }}
                style={{ width: '100%', padding: '10px 12px', borderRadius: 11, fontSize: 16, fontWeight: 700, justifyContent: 'flex-start' }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--surface-2)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                <span className={"dot gc-" + g.color} style={{ width: 11, height: 11, borderRadius: '50%' }}></span>{g.name}
              </button>
            ))}
          </div>
        </>
      )}
    </div>
  );
}

function FilterChip({ active, onClick, children, dot }) {
  return (
    <button onClick={onClick} className="row gap-2" style={{
      height: 38, padding: '0 15px', borderRadius: 'var(--radius-pill)', fontSize: 14.5, fontWeight: 800,
      border: `1.5px solid ${active ? 'transparent' : 'var(--line)'}`,
      background: active ? 'var(--ink)' : 'var(--surface)', color: active ? '#fff' : 'var(--ink-soft)',
      transition: 'all .14s var(--ease)',
    }}>
      {dot && <span style={{ width: 9, height: 9, borderRadius: '50%', background: dot }}></span>}{children}
    </button>
  );
}

function GuestRow({ g, group, onEdit }) {
  const DIET = window.PlaniqData.DIET_TYPES;
  return (
    <div className="row gap-3" onClick={onEdit} style={{
      background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 16, padding: '12px 14px', cursor: 'pointer',
      transition: 'transform .12s var(--ease), box-shadow .15s', boxShadow: 'var(--shadow-sm)',
    }} onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-1px)'; e.currentTarget.style.boxShadow = 'var(--shadow)'; }}
       onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = 'var(--shadow-sm)'; }}>
      <Avatar name={g.name} group={group.color} size={42} child={g.child} />
      <div className="col" style={{ flex: 1, minWidth: 0, gap: 3 }}>
        <div className="row gap-2" style={{ flexWrap: 'wrap' }}>
          <span style={{ fontWeight: 800, fontSize: 17 }}>{g.name}</span>
          {g.plusOne && <span className="chip" style={{ height: 24, background: 'var(--accent-tint)', color: 'var(--accent-deep)', border: 'none', fontSize: 12 }}>+1{g.plusOneName ? ' · ' + g.plusOneName : ''}</span>}
        </div>
        <div className="row gap-2" style={{ flexWrap: 'wrap' }}>
          {g.diet.map(d => { const dt = DIET.find(x => x.id === d); return <span key={d} className="chip" style={{ height: 22, fontSize: 11.5, background: 'var(--sage-tint)', color: 'var(--sage-deep)', border: 'none' }}><Icon name="leaf" size={12} /> {dt?.label}</span>; })}
          {g.note && <span className="row gap-2 faint" style={{ fontSize: 13, fontWeight: 700 }}><Icon name="pin" size={13} /> {g.note}</span>}
        </div>
      </div>
      <span className="row gap-2" style={{ fontSize: 13.5, fontWeight: 800, color: g.seat ? 'var(--sage-deep)' : 'var(--ink-faint)' }}>
        <span style={{ width: 9, height: 9, borderRadius: '50%', background: g.seat ? 'var(--sage)' : 'var(--honey)' }}></span>
        {g.seat ? 'Placeret' : 'Ikke placeret'}
      </span>
      <Icon name="chevR" size={20} color="var(--ink-faint)" />
    </div>
  );
}

function EmptyGuests({ onFocus }) {
  return (
    <div className="col center anim-up" style={{ padding: '70px 20px', textAlign: 'center', gap: 14 }}>
      <div style={{ width: 84, height: 84, borderRadius: 28, background: 'var(--accent-tint)', display: 'grid', placeItems: 'center' }}>
        <Icon name="users" size={40} color="var(--accent)" sw={1.6} />
      </div>
      <h3 style={{ fontSize: 24 }}>Du har ingen gæster endnu</h3>
      <p className="muted" style={{ fontSize: 17, maxWidth: 360, lineHeight: 1.5 }}>Tilføj din første gæst foroven — tast et navn, tryk Enter, og fortsæt til den næste.</p>
      <button className="btn btn-primary btn-lg" style={{ marginTop: 6 }} onClick={onFocus}>Tilføj første gæst</button>
    </div>
  );
}

function NoGroupsGate({ addGroup, goToSettings }) {
  const [name, setName] = useStateG('');
  const submit = () => { const n = name.trim(); if (!n) return; addGroup(n); setName(''); };
  return (
    <div className="scroll" style={{ height: '100%', background: 'var(--bg)' }}>
      <div className="col center anim-up" style={{ maxWidth: 460, margin: '0 auto', padding: '70px 24px', textAlign: 'center', gap: 16 }}>
        <div style={{ width: 84, height: 84, borderRadius: 28, background: 'var(--accent-tint)', display: 'grid', placeItems: 'center' }}>
          <Icon name="users" size={40} color="var(--accent)" sw={1.6} />
        </div>
        <h3 style={{ fontSize: 24 }}>Opret en gruppe først</h3>
        <p className="muted" style={{ fontSize: 17, lineHeight: 1.5 }}>
          Gæster inddeles i grupper — fx familie, venner eller brudens og gommens side.
          Opret din første gruppe, så kan du begynde at tilføje gæster.
        </p>
        <div className="row gap-2" style={{ width: '100%', marginTop: 6 }}>
          <input className="input" autoFocus placeholder="fx Familie" value={name}
            onChange={e => setName(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter') submit(); }}
            style={{ flex: 1 }} />
          <button className="btn btn-primary" disabled={!name.trim()} onClick={submit}>
            <Icon name="plus" size={18} /> Opret gruppe
          </button>
        </div>
        <button className="btn btn-ghost btn-sm" onClick={goToSettings} style={{ marginTop: 2 }}>
          Eller administrér grupper i Indstillinger
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { GuestList, GroupPicker, FilterChip });
