/* hub-social.jsx — plain JS, no JSX */
(function () {
  "use strict";

  const sb = window.sb;               // supabase client, may be null
  const cdeData = window.cdeData;     // { projectId(), … }

  /* ------------------------------------------------------------------ */
  /* 1) socialFor(keys)                                                  */
  /* ------------------------------------------------------------------ */
  async function socialFor(keys) {
    if (!sb || !Array.isArray(keys) || keys.length === 0) return {};

    try {
      // current user
      const { data: u } = await sb.auth.getUser();
      const uid = u && u.user && u.user.id;

      // fetch comments
      const { data: comments, error: errC } = await sb
        .from('activity_comments')
        .select('activity_key, author, body, created_at')
        .in('activity_key', keys);

      if (errC) throw errC;

      // fetch reactions
      const { data: reactions, error: errR } = await sb
        .from('activity_reactions')
        .select('activity_key, user_id')
        .in('activity_key', keys);

      if (errR) throw errR;

      // build lookup maps
      const reactionCount = {};
      const reactionUsers = {};
      const commentMap = {};

      for (const k of keys) {
        reactionCount[k] = 0;
        reactionUsers[k] = new Set();
        commentMap[k] = [];
      }

      if (reactions) {
        for (const r of reactions) {
          const k = r.activity_key;
          if (reactionCount[k] !== undefined) {
            reactionCount[k] += 1;
            reactionUsers[k].add(r.user_id);
          }
        }
      }

      if (comments) {
        for (const c of comments) {
          const k = c.activity_key;
          if (commentMap[k]) {
            commentMap[k].push({
              who: c.author,
              text: c.body,
              created_at: c.created_at,
            });
          }
        }
      }

      // sort comments by created_at ascending
      for (const k of keys) {
        commentMap[k].sort(
          (a, b) => new Date(a.created_at) - new Date(b.created_at)
        );
      }

      // assemble result
      const result = {};
      for (const k of keys) {
        result[k] = {
          count: reactionCount[k],
          liked: uid ? reactionUsers[k].has(uid) : false,
          comments: commentMap[k],
        };
      }

      return result;
    } catch (_) {
      return {};
    }
  }

  /* ------------------------------------------------------------------ */
  /* 2) addComment(key, body, author)                                    */
  /* ------------------------------------------------------------------ */
  async function addComment(key, body, author) {
    if (!sb) return null;

    try {
      const pid = await cdeData.projectId();
      const { data, error } = await sb
        .from('activity_comments')
        .insert({
          project_id: pid,
          activity_key: key,
          author: author || 'Bạn',
          body: body,
        })
        .select()
        .maybeSingle();

      if (error) throw error;
      return data;
    } catch (_) {
      return null;
    }
  }

  /* ------------------------------------------------------------------ */
  /* 3) toggleReaction(key, wantLike)                                    */
  /* ------------------------------------------------------------------ */
  async function toggleReaction(key, wantLike) {
    if (!sb) return 0;

    try {
      const { data: u } = await sb.auth.getUser();
      const uid = u && u.user && u.user.id;
      if (!uid) return 0;

      const pid = await cdeData.projectId();

      if (wantLike) {
        // insert, ignore duplicate PK
        try {
          await sb.from('activity_reactions').insert({
            project_id: pid,
            activity_key: key,
            user_id: uid,
          });
        } catch (_) {
          // duplicate key – ignore
        }
      } else {
        await sb
          .from('activity_reactions')
          .delete()
          .eq('activity_key', key)
          .eq('user_id', uid);
      }

      // count remaining reactions for this key
      const { count, error } = await sb
        .from('activity_reactions')
        .select('*', { count: 'exact', head: true })
        .eq('activity_key', key);

      if (error) throw error;
      return count || 0;
    } catch (_) {
      return 0;
    }
  }

  /* ------------------------------------------------------------------ */
  /* expose                                                              */
  /* ------------------------------------------------------------------ */
  window.cdeHub = {
    socialFor,
    addComment,
    toggleReaction,
  };
})();
