/* AIWine CRM — shared rich-text editor + email signature helpers.
   RichEditor: a contentEditable surface with a small formatting toolbar that
   emits an HTML string. Used by the 1:1 email composer and the campaign builder.
   Plain, dependency-free (uses document.execCommand — widely supported). */

(function () {
  const TOOLBAR = [
    { cmd: 'bold', label: 'B', style: { fontWeight: 800 }, title: 'Bold' },
    { cmd: 'italic', label: 'I', style: { fontStyle: 'italic' }, title: 'Italic' },
    { cmd: 'underline', label: 'U', style: { textDecoration: 'underline' }, title: 'Underline' },
    { sep: true },
    { cmd: 'insertUnorderedList', label: '• List', title: 'Bullet list' },
    { cmd: 'insertOrderedList', label: '1. List', title: 'Numbered list' },
    { sep: true },
    { cmd: 'createLink', label: 'Link', title: 'Insert link', link: true },
    { cmd: 'removeFormat', label: 'Clear', title: 'Clear formatting' },
  ];

  // value/onChange are HTML strings. placeholder shown when empty.
  function RichEditor({ value, onChange, minHeight, placeholder }) {
    const ref = React.useRef(null);
    const last = React.useRef(value || '');

    // set initial / external HTML without clobbering the caret on each keystroke
    React.useEffect(() => {
      if (ref.current && (value || '') !== last.current) {
        ref.current.innerHTML = value || '';
        last.current = value || '';
      }
    }, [value]);

    const emit = () => {
      const html = ref.current ? ref.current.innerHTML : '';
      last.current = html;
      onChange && onChange(html);
    };

    const run = (item) => {
      if (!ref.current) return;
      ref.current.focus();
      if (item.link) {
        const url = window.prompt('Link URL (https://…)');
        if (url) document.execCommand('createLink', false, /^https?:/i.test(url) ? url : 'https://' + url);
      } else {
        document.execCommand(item.cmd, false, null);
      }
      emit();
    };

    return (
      React.createElement('div', { style: { border: '1px solid var(--line)', borderRadius: 4, background: 'var(--card-2)', overflow: 'hidden' } },
        React.createElement('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 2, padding: '6px 8px', borderBottom: '1px solid var(--line-soft)', background: 'var(--bone-alt)' } },
          TOOLBAR.map((it, i) => it.sep
            ? React.createElement('span', { key: i, style: { width: 1, background: 'var(--line)', margin: '2px 4px' } })
            : React.createElement('button', {
                key: i, type: 'button', title: it.title, onMouseDown: (e) => { e.preventDefault(); run(it); },
                style: Object.assign({ border: 'none', background: 'transparent', cursor: 'pointer', fontSize: 12, padding: '4px 8px', borderRadius: 3, color: 'var(--ink-soft)', fontFamily: 'var(--font-mono, monospace)' }, it.style || {}),
              }, it.label)
          )
        ),
        React.createElement('div', {
          ref, contentEditable: true, onInput: emit, onBlur: emit,
          'data-placeholder': placeholder || 'Write your message…',
          className: 'rt-edit',
          style: { minHeight: minHeight || 180, padding: '14px 16px', fontSize: 14, lineHeight: 1.6, color: 'var(--ink)', outline: 'none', fontFamily: 'var(--font-sans, system-ui, sans-serif)' },
        })
      )
    );
  }

  // strip HTML → plain text (for the email-history preview + logging)
  function htmlToText(html) {
    const d = document.createElement('div');
    d.innerHTML = html || '';
    return (d.textContent || d.innerText || '').replace(/\n{3,}/g, '\n\n').trim();
  }

  // ---- signature (per-browser; keyed so a shared machine can differ by login) ----
  function sigKey() {
    const u = (window.CRMStore && window.CRMStore.user && window.CRMStore.user.email) || 'default';
    return 'aiwine-crm:signature:' + u;
  }
  function getSignature() {
    try { return localStorage.getItem(sigKey()) || ''; } catch (e) { return ''; }
  }
  function setSignature(html) {
    try { localStorage.setItem(sigKey(), html || ''); } catch (e) {}
  }

  // plain text → simple HTML (paragraphs + line breaks); pass-through if already HTML
  function textToHtml(s) {
    const esc = (x) => String(x == null ? '' : x).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    if (/<[a-z][\s\S]*>/i.test(s || '')) return s;
    return (s || '').split(/\n{2,}/).map((p) => '<p>' + esc(p).replace(/\n/g, '<br>') + '</p>').join('');
  }

  Object.assign(window, { RichEditor, htmlToText, textToHtml, getSignature, setSignature });
})();
