/* Wa by Elivate - WhatsApp text composer */

const WA_FORMATS = [
  { id: "bold", label: <b>B</b>, title: "Bold", prefix: "*", suffix: "*", sample: "bold text" },
  { id: "italic", label: <i>I</i>, title: "Italic", prefix: "_", suffix: "_", sample: "italic text" },
  { id: "strike", label: <span style={{ textDecoration: "line-through" }}>S</span>, title: "Strikethrough", prefix: "~", suffix: "~", sample: "struck text" },
  { id: "code", label: <code>{`<>`}</code>, title: "Inline code", prefix: "`", suffix: "`", sample: "code" },
  { id: "mono", label: "Mono", title: "Monospace block", prefix: "```", suffix: "```", sample: "monospace text" },
];

function MessageComposer({
  value,
  onChange,
  placeholder = "Write your message...",
  minHeight = 130,
  preview = true,
  previewTitle = "WhatsApp preview",
}) {
  const ref = React.useRef(null);

  const updateText = (next, selectionStart, selectionEnd) => {
    onChange(next);
    window.setTimeout(() => {
      if (!ref.current) return;
      ref.current.focus();
      ref.current.setSelectionRange(selectionStart, selectionEnd);
    }, 0);
  };

  const wrapSelection = ({ prefix, suffix, sample }) => {
    const el = ref.current;
    const start = el?.selectionStart ?? value.length;
    const end = el?.selectionEnd ?? value.length;
    const selected = value.slice(start, end) || sample;
    const next = value.slice(0, start) + prefix + selected + suffix + value.slice(end);
    updateText(next, start + prefix.length, start + prefix.length + selected.length);
  };

  const applyBlock = (kind) => {
    const el = ref.current;
    const start = el?.selectionStart ?? value.length;
    const end = el?.selectionEnd ?? value.length;
    const selected = value.slice(start, end) || (kind === "quote" ? "Quoted message" : "List item");
    const lines = selected.split("\n");
    const nextBlock = lines.map((line, index) => {
      if (kind === "quote") return `> ${line.replace(/^>\s?/, "")}`;
      if (kind === "number") return `${index + 1}. ${line.replace(/^\d+\.\s?/, "")}`;
      return `- ${line.replace(/^[-*]\s?/, "")}`;
    }).join("\n");
    const next = value.slice(0, start) + nextBlock + value.slice(end);
    updateText(next, start, start + nextBlock.length);
  };

  return (
    <div className="message-composer">
      <div className="format-toolbar" aria-label="WhatsApp formatting controls">
        {WA_FORMATS.map((format) => (
          <button key={format.id} type="button" className="format-btn" title={format.title} onClick={() => wrapSelection(format)}>
            {format.label}
          </button>
        ))}
        <span className="format-divider"></span>
        <button type="button" className="format-btn" title="Quote" onClick={() => applyBlock("quote")}>Quote</button>
        <button type="button" className="format-btn" title="Bullet list" onClick={() => applyBlock("bullet")}>List</button>
        <button type="button" className="format-btn" title="Numbered list" onClick={() => applyBlock("number")}>1.</button>
      </div>

      <textarea
        ref={ref}
        className="textarea message-textarea"
        style={{ minHeight }}
        placeholder={placeholder}
        value={value}
        onChange={(e) => onChange(e.target.value)}
      ></textarea>

      <div className="format-help">
        WhatsApp renders <code>*bold*</code>, <code>_italic_</code>, <code>~strike~</code>, <code>`code`</code>, <code>&gt; quotes</code>, and lists.
      </div>

      {preview && <div className="composer-preview">
        <div className="composer-preview-title">{previewTitle}</div>
        <WhatsAppTextPreview text={value} />
      </div>}
    </div>
  );
}

function WhatsAppTextPreview({ text, empty = "Your message will appear here..." }) {
  return (
    <div className="wa-rendered" dangerouslySetInnerHTML={{ __html: renderWhatsAppText(text || empty) }}></div>
  );
}

function renderWhatsAppText(input) {
  const escaped = escapePreviewHtml(input)
    .replace(/```([\s\S]*?)```/g, (_match, text) => `<code class="wa-code-block">${text}</code>`)
    .replace(/`([^`\n]+)`/g, "<code>$1</code>")
    .replace(/\*([^*\n]+)\*/g, "<strong>$1</strong>")
    .replace(/_([^_\n]+)_/g, "<em>$1</em>")
    .replace(/~([^~\n]+)~/g, "<s>$1</s>");

  return escaped.split("\n").map((line) => {
    if (!line) return `<div class="wa-line"><br></div>`;
    const quote = line.match(/^&gt;\s?(.*)$/);
    if (quote) return `<div class="wa-line wa-quote">${quote[1] || "<br>"}</div>`;
    const bullet = line.match(/^[-*]\s+(.*)$/);
    if (bullet) return `<div class="wa-line wa-list"><span class="wa-list-mark">•</span><span>${bullet[1]}</span></div>`;
    const numbered = line.match(/^(\d+\.)\s+(.*)$/);
    if (numbered) return `<div class="wa-line wa-list"><span class="wa-list-mark">${numbered[1]}</span><span>${numbered[2]}</span></div>`;
    return `<div class="wa-line">${line}</div>`;
  }).join("");
}

function escapePreviewHtml(value) {
  return String(value)
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;");
}

window.MessageComposer = MessageComposer;
window.WhatsAppTextPreview = WhatsAppTextPreview;
