// rich-editor.jsx — Lightweight rich text editor with formatting + emoji pickers.
// Stores HTML strings via contentEditable. Toolbar: B, I, U, lists, link, emoji picker, game emoji picker.

const STANDARD_EMOJI = [
  '😀','😄','😁','😆','😊','😎','😍','🥳','🤩','🙃','😉','🙂','🤔',
  '😂','😭','😅','😬','😮','😱','🤯','🥶','🥵','🤬','😡','😤','😈',
  '👍','👎','👏','🙌','🙏','💪','👀','🫡','✊','🤝','👋','🫶','💯',
  '❤️','🧡','💛','💚','💙','💜','🖤','🤍','💔','💖','💞','💫','✨',
  '🔥','⚡','💥','💎','💰','🏆','🥇','🎉','🎊','🎁','📣','📢','📌',
  '✅','❌','⚠️','❓','❗','💡','📍','📅','🕐','🌟','⭐','☃️','❄️',
];

// "Game emojis" — WoS-themed unicode icons. Picker labels them so officers
// know which event/concept each maps to. (Real in-game emote sprites would
// load from R2 once Dave provides assets.)
const GAME_EMOJI = [
  { e: '🐻', l: 'Bear Hunt' },
  { e: '🐻‍❄️', l: 'Polar Bear' },
  { e: '🎯', l: 'Crazy Joe' },
  { e: '⚔️', l: 'Canyon Clash' },
  { e: '🔥', l: 'Foundry' },
  { e: '👹', l: 'Merc Boss' },
  { e: '🏆', l: 'KvK' },
  { e: '🛡️', l: 'SVS' },
  { e: '👑', l: 'Sup. President' },
  { e: '❄️', l: 'Frostlands' },
  { e: '🏰', l: 'Castle' },
  { e: '🚩', l: 'Banner / Rally' },
  { e: '⚔', l: 'Fight' },
  { e: '🛠️', l: 'Furnace' },
  { e: '🐺', l: 'Wolves' },
  { e: '💎', l: 'Frost Stars' },
  { e: '🧊', l: 'Ice / Cold' },
  { e: '📜', l: 'Decree' },
  { e: '🤝', l: 'NAP' },
  { e: '⚡', l: 'Speedup' },
];

function RichTextEditor({ value, onChange, placeholder, minHeight = 110 }) {
  const editorRef = React.useRef(null);
  const [pickerOpen, setPickerOpen] = React.useState(null); // 'emoji' | 'game' | null
  const lastValue = React.useRef(value);

  // Initialize content once
  React.useEffect(() => {
    const el = editorRef.current;
    if (!el) return;
    if (el.innerHTML !== (value || '')) {
      el.innerHTML = value || '';
      lastValue.current = value || '';
    }
  }, []); // intentionally on mount only

  // Sync external value updates
  React.useEffect(() => {
    if (!editorRef.current) return;
    if (value !== lastValue.current && value !== editorRef.current.innerHTML) {
      editorRef.current.innerHTML = value || '';
      lastValue.current = value || '';
    }
  }, [value]);

  const cmd = (command, arg) => {
    editorRef.current?.focus();
    document.execCommand(command, false, arg);
    emit();
  };

  const emit = () => {
    const html = editorRef.current?.innerHTML || '';
    lastValue.current = html;
    onChange?.(html);
  };

  const insertAtCursor = (text) => {
    editorRef.current?.focus();
    document.execCommand('insertText', false, text);
    emit();
  };

  const insertLink = () => {
    const url = window.prompt('Enter URL:');
    if (url) cmd('createLink', url);
  };

  return (
    <div className="rte">
      <div className="rte-toolbar" role="toolbar" aria-label="Text formatting">
        <button type="button" onClick={() => cmd('bold')} title="Bold (Ctrl+B)"><b>B</b></button>
        <button type="button" onClick={() => cmd('italic')} title="Italic (Ctrl+I)"><i>I</i></button>
        <button type="button" onClick={() => cmd('underline')} title="Underline (Ctrl+U)"><u>U</u></button>
        <span className="rte-sep" />
        <button type="button" onClick={() => cmd('insertUnorderedList')} title="Bullet list">•</button>
        <button type="button" onClick={() => cmd('insertOrderedList')} title="Numbered list">1.</button>
        <button type="button" onClick={insertLink} title="Insert link">🔗</button>
        <span className="rte-sep" />
        <button type="button"
                className={pickerOpen === 'emoji' ? 'on' : ''}
                onClick={() => setPickerOpen(pickerOpen === 'emoji' ? null : 'emoji')}
                title="Insert emoji">😀</button>
        <button type="button"
                className={pickerOpen === 'game' ? 'on' : ''}
                onClick={() => setPickerOpen(pickerOpen === 'game' ? null : 'game')}
                title="Insert WoS game emoji">🎮</button>
      </div>

      {pickerOpen === 'emoji' && (
        <div className="rte-picker">
          {STANDARD_EMOJI.map((e) => (
            <button key={e} type="button"
                    className="rte-emoji"
                    onClick={() => { insertAtCursor(e); setPickerOpen(null); }}>
              {e}
            </button>
          ))}
        </div>
      )}

      {pickerOpen === 'game' && (
        <div className="rte-picker game">
          {GAME_EMOJI.map((g) => (
            <button key={g.e} type="button"
                    className="rte-emoji game-emoji"
                    title={g.l}
                    onClick={() => { insertAtCursor(g.e); setPickerOpen(null); }}>
              <span className="ge">{g.e}</span>
              <span className="gl">{g.l}</span>
            </button>
          ))}
        </div>
      )}

      <div ref={editorRef}
           className="rte-content"
           contentEditable
           role="textbox"
           aria-multiline="true"
           data-placeholder={placeholder || 'Start typing…'}
           style={{ minHeight }}
           onInput={emit}
           onBlur={emit}
           suppressContentEditableWarning
      />
    </div>
  );
}

Object.assign(window, { RichTextEditor, STANDARD_EMOJI, GAME_EMOJI });
