// guestsource.jsx — drag-kilde med ikke-placerede gæster (i bordplan-editoren)
const { useState: useStateGS, useMemo: useMemoGS } = React;

function GuestSource({ project, startGuestDrag, dragging, onAutoPlace, autoBusy }) {
  const [tab, setTab] = useStateGS('unplaced'); // unplaced | all
  const [q, setQ] = useStateGS('');
  const groups = project.groups;
  const gById = (id) => groups.find(g => g.id === id);

  const list = useMemoGS(() => {
    let l = project.guests;
    if (tab === 'unplaced') l = l.filter(g => !g.seat);
    if (q.trim()) l = l.filter(g => g.name.toLowerCase().includes(q.toLowerCase()));
    return l;
  }, [project.guests, tab, q]);

  const grouped = useMemoGS(() => {
    const m = {}; list.forEach(g => { (m[g.group] = m[g.group] || []).push(g); });
    return groups.map(gr => ({ gr, items: m[gr.id] || [] })).filter(x => x.items.length);
  }, [list, groups]);

  const unplaced = project.guests.filter(g => !g.seat).length;
  const total = project.guests.length;

  return (
    <div className="col tp-sidebar" data-unseat-zone style={{
      width: 300, flex: 'none', borderRight: '1px solid var(--line)', background: 'var(--surface)', height: '100%',
      boxShadow: dragging ? 'inset -3px 0 0 var(--accent-soft)' : 'none', transition: 'box-shadow .2s',
    }}>
      <div style={{ padding: '16px 16px 12px', borderBottom: '1px solid var(--line)' }}>
        <div className="row" style={{ justifyContent: 'space-between', marginBottom: 12 }}>
          <h3 style={{ fontSize: 18 }}>Gæster</h3>
          <span className="chip" style={{ background: 'var(--surface-2)' }}>{unplaced} mangler</span>
        </div>
        <div className="row" style={{ background: 'var(--surface-2)', borderRadius: 999, padding: 3, border: '1.5px solid var(--line)', marginBottom: 10 }}>
          {[['unplaced', `Mangler (${unplaced})`], ['all', `Alle (${total})`]].map(([id, lbl]) => (
            <button key={id} onClick={() => setTab(id)} style={{ flex: 1, minHeight: 34, borderRadius: 999, fontFamily: 'var(--font-disp)', fontWeight: 500, fontSize: 14, background: tab === id ? 'var(--surface)' : 'transparent', color: tab === id ? 'var(--ink)' : 'var(--ink-soft)', boxShadow: tab === id ? 'var(--shadow-sm)' : 'none' }}>{lbl}</button>
          ))}
        </div>
        <div className="row" style={{ background: 'var(--surface)', border: '1.5px solid var(--line-2)', borderRadius: 999, paddingLeft: 12 }}>
          <Icon name="search" size={17} color="var(--ink-faint)" />
          <input className="input" style={{ border: 'none', background: 'transparent', boxShadow: 'none', minHeight: 38, fontSize: 15 }} placeholder="Søg gæst…" value={q} onChange={e => setQ(e.target.value)} />
        </div>
      </div>

      <div className="scroll" style={{ flex: 1, padding: '6px 12px 16px' }}>
        {list.length === 0 && (
          <div className="col center" style={{ padding: '50px 16px', textAlign: 'center', gap: 10, color: 'var(--ink-faint)' }}>
            {tab === 'unplaced' ? <><Icon name="check" size={38} color="var(--sage-deep)" /><p style={{ fontWeight: 800, color: 'var(--sage-deep)', fontSize: 16 }}>Alle er placeret!</p><p style={{ fontSize: 14 }}>Flot — hele gæstelisten sidder ved et bord.</p></> : <p style={{ fontSize: 15 }}>Ingen gæster matcher.</p>}
          </div>
        )}
        {grouped.map(({ gr, items }) => (
          <div key={gr.id} style={{ marginTop: 14 }}>
            <div className="row gap-2" style={{ marginBottom: 7, paddingLeft: 2 }}>
              <span className={"dot gc-" + gr.color} style={{ width: 9, height: 9, borderRadius: '50%' }}></span>
              <span style={{ fontSize: 13.5, fontWeight: 800, color: 'var(--ink-soft)' }}>{gr.name}</span>
              <span className="faint" style={{ fontSize: 12.5, fontWeight: 700 }}>{items.length}</span>
            </div>
            <div className="col gap-2">
              {items.map(g => (
                <div key={g.id}
                  onPointerDown={(e) => startGuestDrag(e, g, g.seat || null)}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', borderRadius: 13,
                    background: g.seat ? 'var(--surface-2)' : 'var(--surface)', border: '1px solid var(--line)',
                    boxShadow: 'var(--shadow-sm)', cursor: 'grab', touchAction: 'none', userSelect: 'none',
                    opacity: g.seat ? 0.62 : 1,
                  }}>
                  <Avatar name={g.name} group={gr.color} size={34} child={g.child} />
                  <div className="col" style={{ flex: 1, minWidth: 0, gap: 1 }}>
                    <span style={{ fontWeight: 800, fontSize: 15, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{g.name}</span>
                    {(g.plusOne || g.diet.length > 0) && (
                      <span className="row gap-2" style={{ fontSize: 11.5, fontWeight: 800, color: 'var(--ink-faint)' }}>
                        {g.plusOne && <span>+1</span>}
                        {g.diet.length > 0 && <span className="row gap-2" style={{ color: 'var(--sage-deep)' }}><Icon name="leaf" size={12} />{g.diet.length}</span>}
                      </span>
                    )}
                  </div>
                  {!g.seat && <Icon name="grid" size={16} color="var(--ink-faint)" style={{ opacity: .6 }} />}
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      <div style={{ padding: 14, borderTop: '1px solid var(--line)' }}>
        <button className="btn btn-sage" style={{ width: '100%' }} onClick={onAutoPlace} disabled={unplaced === 0 || autoBusy}>
          <Icon name="sparkle" size={19} /> {autoBusy ? 'Placerer…' : 'Auto-placér resten'}
        </button>
        <p className="faint" style={{ fontSize: 12.5, textAlign: 'center', marginTop: 8, fontWeight: 700, lineHeight: 1.4 }}>Foreslår pladser ud fra grupper og regler — du kan altid rette efter.</p>
      </div>
    </div>
  );
}

Object.assign(window, { GuestSource });
