import { simpleNotification } from '../z_comps/notify.js';

// Limpia el /src/... si ya viene en la URL
let baseUrl = window.location.href.replace(/\/src\/\w+$/, '');

function encode_url(redoSocial = '') {
  let finalUrl = baseUrl;
  if (redoSocial !== '') {
    finalUrl += `/src/${redoSocial}`;
  }
  return encodeURIComponent(finalUrl);
}

function openShareWindow(shareUrl) {
  window.open(shareUrl, '_blank', 'width=600,height=400,noopener,noreferrer');
}

// Copiar al portapapeles
const btn_copy = document.querySelector("button.copy");
if (btn_copy) {
  btn_copy.addEventListener("click", async () => {
    try {
      await navigator.clipboard.writeText(baseUrl);
      simpleNotification("URL Copiada", "URL copiada", "success");
    } catch (err) {
      console.error('Error al copiar: ', err);
    }
  });
}

// LinkedIn
const btn_in = document.querySelector("button.in");
if (btn_in) {
  btn_in.addEventListener("click", () => {
    const linkedInUrl = `https://www.linkedin.com/sharing/share-offsite/?url=${encode_url('li')}`;
    openShareWindow(linkedInUrl);
  });
}

// Facebook
const btn_fb = document.querySelector("button.fb");
if (btn_fb) {
  btn_fb.addEventListener("click", () => {
    const fbShareUrl = `https://www.facebook.com/sharer/sharer.php?u=${encode_url('fb')}`;
    openShareWindow(fbShareUrl);
  });
}

// X / Twitter
const btn_x = document.querySelector("button.tw");
if (btn_x) {
  btn_x.addEventListener("click", () => {
    const tweetText = encodeURIComponent("Mira este post interesante:");
    const xShareUrl = `https://twitter.com/intent/tweet?url=${encode_url('x')}&text=${tweetText}`;
    openShareWindow(xShareUrl);
  });
}

// compartir por whatsapp
// WhatsApp
const btn_wa = document.querySelector("button.wa");
if (btn_wa) {
  btn_wa.addEventListener("click", () => {
    const whatsappText = encodeURIComponent("Mira este post interesante:");
    const whatsappUrl = `https://api.whatsapp.com/send?text=${whatsappText}%20${encode_url('wa')}`;
    openShareWindow(whatsappUrl);
  });
}

// compartir por email
// email
const btn_mail = document.querySelector("button.mail");
if (btn_mail) {
  btn_mail.addEventListener("click", () => {
    const subject = encodeURIComponent("¡Mira este post interesante!");
    const body = encodeURIComponent(`Te comparto este enlace que creo que te gustará:\n\n${encode_url('mail')}`);
    const mailUrl = `mailto:?subject=${subject}&body=${body}`;
    window.location.href = mailUrl;
  });
}


