// guesteditor.jsx — rediger en gæst + regler
const { useState: useStateGE } = React;

function Toggle({ on, onChange }) {
  return (
    <button onClick={() => onChange(!on)} style={{
      width: 52, height: 30, borderRadius: 999, background: on ? 'var(--sage)' : 'var(--line-2)',
      position: 'relative', transition: 'background .18s var(--ease)', flex: 'none',
    }}>
      <span style={{ position: 'absolute', top: 3, left: on ? 25 : 3, width: 24, height: 24, borderRadius: '50%', background: '#fff', boxShadow: '0 1px 3px rgba(0,0,0,.25)', transition: 'left .2s var(--ease)' }}></span>
    </button>
  );
}

function GuestEditor({ guest, project, onClose, updateGuest, removeGuest, addRule, removeRule }) {
  const DIET = window.PlaniqData.DIET_TYPES;
  const [g, setG] = useStateGE({ ...guest });
  const [confirmDel, setConfirmDel] = useStateGE(false);
  const [ruleMode, setRuleMode] = useStateGE(null); // 'together' | 'apart'

  const patch = (p) => setG(prev => { const n = { ...prev, ...p }; updateGuest(guest.id, p); return n; });
  const toggleDiet = (d) => { const has = g.diet.includes(d); patch({ diet: has ? g.diet.filter(x => x !== d) : [...g.diet, d] }); };

  const groups = project.groups;
  const myRules = project.rules.filter(r => r.a === guest.id || r.b === guest.id);
  const otherOf = (r) => project.guests.find(x => x.id === (r.a === guest.id ? r.b : r.a));
  const ruleableGuests = project.guests.filter(x => x.id !== guest.id && !myRules.some(r => r.a === x.id || r.b === x.id));

  return (
    <Modal onClose={onClose} maxWidth={480}>
      <div className="row gap-3" style={{ marginBottom: 20 }}>
        <Avatar name={g.name} group={groups.find(x=>x.id===g.group)?.color} size={52} child={g.child} />
        <div style={{ flex: 1 }}>
          <input className="input" style={{ fontSize: 20, fontWeight: 800, fontFamily: 'var(--font-disp)', minHeight: 44 }} value={g.name} onChange={e => patch({ name: e.target.value })} />
        </div>
      </div>

      <div className="scroll" style={{ maxHeight: '54vh', margin: '0 -6px', padding: '0 6px' }}>
        {/* group */}
        <div className="field" style={{ marginBottom: 16 }}><label>Gruppe</label>
          <div className="row gap-2" style={{ flexWrap: 'wrap' }}>
            {groups.map(gr => (
              <button key={gr.id} onClick={() => patch({ group: gr.id })} className="row gap-2" style={{
                height: 38, padding: '0 14px', borderRadius: 999, fontSize: 14, fontWeight: 800,
                border: `1.5px solid ${g.group === gr.id ? 'transparent' : 'var(--line)'}`,
                background: g.group === gr.id ? `var(--grp-${gr.color})` : 'var(--surface)',
                color: g.group === gr.id ? '#fff' : 'var(--ink-soft)',
              }}>
                {g.group !== gr.id && <span className={"dot gc-" + gr.color} style={{ width: 9, height: 9, borderRadius: '50%' }}></span>}
                {gr.name}
              </button>
            ))}
          </div>
        </div>

        {/* +1 & child */}
        <div className="col gap-2" style={{ marginBottom: 16 }}>
          <div className="row" style={{ justifyContent: 'space-between', padding: '10px 14px', background: 'var(--surface-2)', borderRadius: 14 }}>
            <span className="row gap-2" style={{ fontWeight: 700, fontSize: 16 }}><Icon name="user" size={20} /> Ledsager (+1)</span>
            <Toggle on={g.plusOne} onChange={v => patch({ plusOne: v })} />
          </div>
          {g.plusOne && <input className="input anim-up" placeholder="Ledsagers navn (valgfrit)" value={g.plusOneName} onChange={e => patch({ plusOneName: e.target.value })} />}
          <div className="row" style={{ justifyContent: 'space-between', padding: '10px 14px', background: 'var(--surface-2)', borderRadius: 14 }}>
            <span className="row gap-2" style={{ fontWeight: 700, fontSize: 16 }}><Icon name="baby" size={20} /> Barn</span>
            <Toggle on={g.child} onChange={v => patch({ child: v })} />
          </div>
        </div>

        {/* diet */}
        <div className="field" style={{ marginBottom: 16 }}><label>Kosthensyn</label>
          <div className="row gap-2" style={{ flexWrap: 'wrap' }}>
            {DIET.map(d => {
              const on = g.diet.includes(d.id);
              return <button key={d.id} onClick={() => toggleDiet(d.id)} className="row gap-2" style={{
                height: 38, padding: '0 14px', borderRadius: 999, fontSize: 14, fontWeight: 800,
                border: `1.5px solid ${on ? 'transparent' : 'var(--line)'}`,
                background: on ? 'var(--sage)' : 'var(--surface)', color: on ? '#fff' : 'var(--ink-soft)',
              }}>{on && <Icon name="check" size={15} />}{d.label}</button>;
            })}
          </div>
        </div>

        {/* note */}
        <div className="field" style={{ marginBottom: 18 }}><label>Notat</label>
          <textarea className="input" placeholder="fx kørestolsbruger, skal sidde nær udgang…" value={g.note} onChange={e => patch({ note: e.target.value })} />
        </div>

        {/* rules */}
        <div className="field" style={{ marginBottom: 6 }}>
          <label>Placeringsregler</label>
          <div className="col gap-2">
            {myRules.map(r => {
              const other = otherOf(r);
              const apart = r.type === 'apart';
              return (
                <div key={r.id} className="row gap-2" style={{ padding: '9px 12px', borderRadius: 12, background: apart ? 'var(--warn-soft)' : 'var(--ok-soft)' }}>
                  <Icon name={apart ? 'unlink' : 'link'} size={18} color={apart ? 'var(--warn)' : 'var(--ok)'} />
                  <span style={{ fontWeight: 800, fontSize: 14.5, color: apart ? 'var(--warn)' : 'var(--sage-deep)' }}>{apart ? 'Må ikke sidde med' : 'Skal sidde med'}</span>
                  <span style={{ fontWeight: 700, fontSize: 14.5, flex: 1 }}>{other ? other.name : '—'}</span>
                  <button className="btn-ghost" style={{ minHeight: 0, padding: 4 }} onClick={() => removeRule(r.id)}><Icon name="x" size={16} /></button>
                </div>
              );
            })}
            {!ruleMode && (
              <div className="row gap-2">
                <button className="btn btn-sm" style={{ flex: 1 }} onClick={() => setRuleMode('together')}><Icon name="link" size={16} /> Skal sidde med…</button>
                <button className="btn btn-sm" style={{ flex: 1 }} onClick={() => setRuleMode('apart')}><Icon name="unlink" size={16} /> Må ikke…</button>
              </div>
            )}
            {ruleMode && (
              <div className="card anim-up" style={{ padding: 8, maxHeight: 180, overflowY: 'auto', boxShadow: 'none', background: 'var(--surface-2)' }}>
                <p className="muted" style={{ fontSize: 13, fontWeight: 800, padding: '4px 8px' }}>{ruleMode === 'apart' ? 'Må ikke sidde sammen med:' : 'Skal sidde sammen med:'}</p>
                {ruleableGuests.length === 0 && <p className="faint" style={{ padding: 8, fontSize: 14 }}>Ingen flere gæster.</p>}
                {ruleableGuests.map(o => (
                  <button key={o.id} className="row gap-2" style={{ width: '100%', padding: '9px 10px', borderRadius: 10, justifyContent: 'flex-start', fontWeight: 700, fontSize: 15 }}
                    onClick={() => { addRule({ type: ruleMode, a: guest.id, b: o.id }); setRuleMode(null); }}
                    onMouseEnter={e => e.currentTarget.style.background = 'var(--surface)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                    <Avatar name={o.name} group={groups.find(x=>x.id===o.group)?.color} size={30} /> {o.name}
                  </button>
                ))}
                <button className="btn btn-sm btn-ghost" style={{ width: '100%', marginTop: 4 }} onClick={() => setRuleMode(null)}>Annullér</button>
              </div>
            )}
          </div>
        </div>
      </div>

      <div className="row" style={{ justifyContent: 'space-between', marginTop: 20, paddingTop: 16, borderTop: '1px solid var(--line)' }}>
        <button className="btn btn-ghost" style={{ color: 'var(--warn)' }} onClick={() => setConfirmDel(true)}><Icon name="trash" size={18} /> Slet gæst</button>
        <button className="btn btn-sage" onClick={onClose}><Icon name="check" size={18} /> Færdig</button>
      </div>

      {confirmDel && <Confirm title={`Slet ${guest.name}?`} body="Gæsten fjernes fra listen og bordplanen." danger confirmLabel="Slet" onConfirm={() => { removeGuest(guest.id); onClose(); }} onClose={() => setConfirmDel(false)} />}
    </Modal>
  );
}

Object.assign(window, { GuestEditor, Toggle });
