/* global React */
(function(){
/* =============================================================
   RichText.jsx — render body text with clickable #tags + @users
   --------------------------------------------------------------
   Every #hashtag links to its TagPage (via the global
   "kd-open-tag" event the app listens for). @mentions are
   highlighted (and clickable → user profile). Used by captions,
   comments, post bodies — anywhere user-written text appears.

   <RichText text="..." />
   ============================================================= */
window.RichText = function RichText({ text = "" }) {
  // split on whitespace but keep the separators so spacing survives
  const parts = String(text).split(/(\s+)/);
  return (
    <React.Fragment>
      {parts.map((p, i) => {
        const tag = p.match(/^#([\u0600-\u06FF\w._]+)$/);
        if (tag) {
          return (
            <button
              key={i}
              type="button"
              className="kd-rich-tag"
              onClick={(e) => {
                e.stopPropagation();
                window.dispatchEvent(new CustomEvent("kd-open-tag", { detail: { tag: tag[1] } }));
              }}>
              {p}
            </button>
          );
        }
        const at = p.match(/^@([\u0600-\u06FF\w._]+)$/);
        if (at) {
          return (
            <button
              key={i}
              type="button"
              className="kd-rich-at"
              onClick={(e) => {
                e.stopPropagation();
                window.dispatchEvent(new CustomEvent("kd-open-user", { detail: { handle: at[1] } }));
              }}>
              {p}
            </button>
          );
        }
        return p;
      })}
    </React.Fragment>
  );
};
})();
