// tag-picker.jsx — chips + type-ahead for a template's destinations and
// holiday types. Shared by the builder's save dialog (app.jsx) and the
// launchpad's Edit details (operator-templates-table.jsx), so a tag is entered
// the same way wherever an operator meets it.
//
// Suggestions come from GET /email-builder/operator-templates/tag-options:
// what this operator already uses first, then the countries and holiday types
// on live offers — so operators converge on the words agents filter by. Free
// text is still allowed: "Greek Islands" is a real destination no offer field
// carries. The server cleans and caps whatever is sent (normaliseTags).
(function () {
  const MAX = 12;

  function TagPicker({ label, value, onChange, options, placeholder, id }) {
    const [text, setText] = React.useState('');
    const [open, setOpen] = React.useState(false);
    const [hi, setHi] = React.useState(0);
    const tags = Array.isArray(value) ? value : [];
    const has = (t) => tags.some((x) => x.toLowerCase() === t.toLowerCase());
    const q = text.trim().toLowerCase();
    const matches = (options || [])
      .filter((o) => !has(o) && (!q || o.toLowerCase().includes(q)))
      .slice(0, 8);

    const add = (raw) => {
      const t = String(raw || '').replace(/\s+/g, ' ').trim().slice(0, 40);
      if (!t || has(t) || tags.length >= MAX) { setText(''); setOpen(false); return; }
      onChange([...tags, t]);
      // Close after adding: an open list left behind covers the fields and
      // buttons below it. Typing (or the down arrow) opens it again.
      setText(''); setHi(0); setOpen(false);
    };
    const remove = (t) => onChange(tags.filter((x) => x !== t));

    const onKey = (e) => {
      if (e.key === 'Enter' || e.key === ',' || e.key === 'Tab') {
        if (!text.trim() && e.key === 'Tab') return;
        e.preventDefault();
        add(open && matches[hi] && q ? matches[hi] : text);
      } else if (e.key === 'ArrowDown') { e.preventDefault(); setOpen(true); setHi((h) => Math.min(h + 1, matches.length - 1)); }
      else if (e.key === 'ArrowUp') { e.preventDefault(); setHi((h) => Math.max(h - 1, 0)); }
      else if (e.key === 'Escape') { setOpen(false); }
      else if (e.key === 'Backspace' && !text && tags.length) { remove(tags[tags.length - 1]); }
    };

    const chip = {
      display: 'inline-flex', alignItems: 'center', gap: 4, padding: '3px 4px 3px 9px', borderRadius: 999,
      background: 'var(--tms-teal-50, #E6F4F5)', color: 'var(--tms-teal-700, #085858)', fontSize: 12.5, fontWeight: 600,
    };
    return (
      <div style={{ position: 'relative' }}>
        {label && <label htmlFor={id} style={{ fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 4 }}>{label}</label>}
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, alignItems: 'center', minHeight: 38, boxSizing: 'border-box',
                      padding: '4px 6px', border: '1px solid var(--product-border, #DDE1E6)', borderRadius: 8, background: '#fff' }}
             onClick={() => document.getElementById(id) && document.getElementById(id).focus()}>
          {tags.map((t) => (
            <span key={t} style={chip}>
              {t}
              <button type="button" aria-label={`Remove ${t}`} onClick={(e) => { e.stopPropagation(); remove(t); }}
                      style={{ border: 0, background: 'transparent', cursor: 'pointer', color: 'inherit', fontSize: 14, lineHeight: 1, padding: '0 3px' }}>×</button>
            </span>
          ))}
          <input id={id} value={text} placeholder={tags.length ? '' : placeholder}
                 role="combobox" aria-expanded={open && matches.length > 0} aria-autocomplete="list"
                 disabled={tags.length >= MAX}
                 onChange={(e) => { setText(e.target.value); setOpen(true); setHi(0); }}
                 onFocus={() => setOpen(true)}
                 onBlur={() => setTimeout(() => setOpen(false), 120)}
                 onKeyDown={onKey}
                 style={{ flex: 1, minWidth: 90, border: 0, outline: 'none', fontSize: 13, padding: '4px 2px', background: 'transparent' }} />
        </div>
        {open && matches.length > 0 && (
          <ul role="listbox" style={{ position: 'absolute', zIndex: 20, left: 0, right: 0, margin: '4px 0 0', padding: 4, listStyle: 'none',
                                      background: '#fff', border: '1px solid var(--product-border, #DDE1E6)', borderRadius: 8,
                                      boxShadow: '0 8px 24px rgba(0,0,0,0.12)', maxHeight: 220, overflowY: 'auto' }}>
            {matches.map((m, i) => (
              <li key={m} role="option" aria-selected={i === hi}
                  onMouseDown={(e) => { e.preventDefault(); add(m); }}
                  onMouseEnter={() => setHi(i)}
                  style={{ padding: '6px 9px', borderRadius: 6, fontSize: 13, cursor: 'pointer',
                           background: i === hi ? 'var(--tms-teal-50, #E6F4F5)' : 'transparent' }}>{m}</li>
            ))}
          </ul>
        )}
      </div>
    );
  }

  window.TagPicker = TagPicker;
})();
