// main.el -- Share page voting, copy-for-platform social sharing.
// Compiled with: elc --target=js --bundle --minify --obfuscate
//
// Required globals: window.NEURON_CFG.id, window.NEURON_CFG.card_url
// Exposed globals: copyForPlatform(platform, btn)

fn main() -> Void {
    native_js("(function() {
  var cfg      = window.NEURON_CFG || {};
  var shareId  = cfg.id       || '';
  var cardUrl  = cfg.card_url || '';

  // Copy-for-platform: format and copy share text for different social platforms
  window.copyForPlatform = function(platform, btn) {
    var text = '';
    var url  = window.location.href;
    if (platform === 'tiktok') {
      text = 'Neuron said something interesting. Watch this. ' + url;
    } else if (platform === 'snapchat') {
      text = url;
    } else {
      text = url;
    }
    navigator.clipboard.writeText(text).then(function() {
      if (btn) {
        btn.classList.add('copied');
        setTimeout(function() { btn.classList.remove('copied'); }, 1500);
      }
    }).catch(function() {});
  };

  // Vote buttons on share page
  var voteUp    = document.getElementById('vote-up');
  var voteDown  = document.getElementById('vote-down');
  var voteScore = document.getElementById('vote-score');
  var voted     = null;

  function updateVoteUI(direction, score) {
    if (voteUp)    voteUp.classList.toggle('voted-up',   direction === 'up');
    if (voteDown)  voteDown.classList.toggle('voted-down', direction === 'down');
    if (voteScore && score != null) voteScore.textContent = score;
  }

  function castVote(direction) {
    var next = voted === direction ? 'none' : direction;
    voted = next === 'none' ? null : next;
    fetch('/api/vote', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({ id: shareId, direction: next })
    }).then(function(r) { return r.json(); }).then(function(d) {
      if (d.ok) updateVoteUI(next === 'none' ? null : next, d.score);
    }).catch(function() {});
  }

  if (voteUp)   voteUp.addEventListener('click',   function() { castVote('up'); });
  if (voteDown) voteDown.addEventListener('click', function() { castVote('down'); });

  // Load initial vote state
  if (shareId) {
    fetch('/api/vote-state/' + shareId)
      .then(function(r) { return r.json(); })
      .then(function(d) { updateVoteUI(d.user_vote || null, d.score); })
      .catch(function() {});
  }
})()")
}
