(() => {
  try {
    const currentScript = document.currentScript;
    if (!currentScript) return;

    let widgetId = currentScript.dataset.widgetId;
    const explicitWhatsappUrl = currentScript.dataset.whatsappUrl || '';

    if (!widgetId) {
      const rootEl = document.getElementById('vf_root_') || document.querySelector('div#vf_root_');
      if (rootEl) {
        widgetId = rootEl.getAttribute('data-id') || rootEl.dataset.id || '';
      }
    }

    if (!widgetId) {
      return;
    }

    const container =
      document.querySelector(`div#vf_root_[data-id="${widgetId}"]`) ||
      document.getElementById('vf_root_');
    if (!container) return;

    const scriptUrl = new URL(currentScript.src, window.location.href);
    const baseUrl = `${scriptUrl.protocol}//${scriptUrl.host}`;

    const fetchWidgetDetails = async () => {
      try {
        const res = await fetch(`${baseUrl}/api/widgets/${encodeURIComponent(widgetId)}`, {
          credentials: 'omit',
        });
        if (!res.ok) {
          return null;
        }
        return await res.json();
      } catch {
        return null;
      }
    };

    const buildWhatsappUrl = (apiData) => {
      if (explicitWhatsappUrl) return explicitWhatsappUrl;

      try {
        const data = apiData && apiData.data ? apiData.data : apiData;
        if (!data) return '';

        const phone =
          data.whatsapp_phone_number ||
          data.phone ||
          data.phone_number ||
          '';

        const message = data.default_user_message || data.welcome_text || '';
        if (!phone) return '';

        const encodedMessage = encodeURIComponent(message);
        return `https://api.whatsapp.com/send?phone=${encodeURIComponent(phone)}&text=${encodedMessage}`;
      } catch {
        return '';
      }
    };

    /* ── SVG Icons ──────────────────────────────────────────── */
    const chatIconSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>`;
    const closeIconSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>`;
    const closeLargeSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>`;

    /* ── Inject keyframes once ──────────────────────────────── */
    if (!document.getElementById('vf_widget_styles')) {
      const styleEl = document.createElement('style');
      styleEl.id = 'vf_widget_styles';
      styleEl.textContent = `
        @keyframes vfPulse {
          0%, 100% { opacity: 1; }
          50% { opacity: 0.5; }
        }
        @keyframes vfSlideUp {
          from { opacity: 0; transform: translateY(30px) scale(0.95); }
          to { opacity: 1; transform: translateY(0) scale(1); }
        }
        @keyframes vfSlideDown {
          from { opacity: 1; transform: translateY(0) scale(1); }
          to { opacity: 0; transform: translateY(30px) scale(0.95); }
        }
      `;
      document.head.appendChild(styleEl);
    }

    const renderWidget = (apiData) => {
      const data = apiData?.data || apiData || {};

      /* ── Extract config ──────────────────────────────────── */
      const headerText = data.header_text || "Chat with us";
      const headerBg = data.header_background_color || data.widget_color || "#059669";
      const headerTextColor = data.header_text_color || "#ffffff";

      const bodyBgImage = data.body_background_image || "";
      const bodyBgColor = data.body_background_color || "#f0faf6";

      const welcome = data.welcome_text || "Welcome! How can we help you today?";
      const welcomeColor = data.welcome_text_color || "#1a2a2a";
      const welcomeBg = data.welcome_text_background || "#ffffff";

      const btnText = data.start_chat_button_text || "Start Chat on WhatsApp";
      const btnBg = data.start_chat_button_background || headerBg;
      const btnTextColor = data.start_chat_button_text_color || "#ffffff";

      const widgetColor = data.widget_color || headerBg;
      const logo = data.widget_image_url || "";
      const autoOpen = data.default_open_popup || false;

      const whatsappUrl = buildWhatsappUrl(apiData);
      const time = new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });

      /* ── Wrapper (fixed position) ────────────────────────── */
      const wrapper = document.createElement("div");
      const pos = (data.widget_position || "bottom-right").toLowerCase();

      wrapper.style.cssText = `
        position: fixed;
        z-index: 999999;
        font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        display: flex;
        flex-direction: column;
        align-items: ${pos.includes("left") ? "flex-start" : "flex-end"};
        gap: 8px;
      `;

      if (pos === "top-left") { wrapper.style.top = "20px"; wrapper.style.left = "20px"; }
      else if (pos === "top-right") { wrapper.style.top = "20px"; wrapper.style.right = "20px"; }
      else if (pos === "bottom-left") { wrapper.style.bottom = "20px"; wrapper.style.left = "20px"; }
      else { wrapper.style.bottom = "20px"; wrapper.style.right = "20px"; }

      /* ── Chat Card ───────────────────────────────────────── */
      const card = document.createElement("div");
      card.style.cssText = `
        width: 320px;
        height: 450px;
        border-radius: 16px;
        overflow: hidden;
        box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25);
        border: 1px solid rgba(0,0,0,0.08);
        display: flex;
        flex-direction: column;
        background: #fff;
        transform-origin: bottom ${pos.includes("left") ? "left" : "right"};
      `;

      let isOpen = autoOpen;
      if (!isOpen) {
        card.style.display = "none";
        card.style.opacity = "0";
        card.style.transform = "translateY(30px) scale(0.95)";
      } else {
        card.style.display = "flex";
        card.style.animation = "vfSlideUp 0.35s cubic-bezier(0.34,1.56,0.64,1) forwards";
      }

      /* ── Header ──────────────────────────────────────────── */
      const header = document.createElement("div");
      header.style.cssText = `
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 16px;
        flex-shrink: 0;
        background: ${headerBg};
        color: ${headerTextColor};
      `;

      // Avatar in header
      const avatarWrap = document.createElement("div");
      avatarWrap.style.cssText = `
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background: rgba(255,255,255,0.2);
        border: 1px solid rgba(255,255,255,0.2);
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
        overflow: hidden;
        position: relative;
      `;

      if (logo) {
        const avatarImg = document.createElement("img");
        avatarImg.src = logo;
        avatarImg.alt = "logo";
        avatarImg.style.cssText = "width:100%;height:100%;object-fit:cover;";
        avatarWrap.appendChild(avatarImg);
      } else {
        avatarWrap.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>`;
      }
      header.appendChild(avatarWrap);

      // Title + subtitle
      const titleWrap = document.createElement("div");
      titleWrap.style.cssText = "flex:1;min-width:0;";
      titleWrap.innerHTML = `
        <p style="font-weight:700;font-size:14px;line-height:1.2;margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${headerText}</p>
        <p style="font-size:10px;opacity:0.8;margin:2px 0 0;font-weight:500;">Welcome to our live chat</p>
      `;
      header.appendChild(titleWrap);

      // Close button in header
      const closeBtn = document.createElement("button");
      closeBtn.style.cssText = `
        width: 28px;
        height: 28px;
        border-radius: 50%;
        border: none;
        background: transparent;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        color: ${headerTextColor};
        transition: background 0.2s;
        padding: 0;
      `;
      closeBtn.innerHTML = closeIconSvg;
      closeBtn.onmouseenter = () => { closeBtn.style.background = "rgba(0,0,0,0.1)"; };
      closeBtn.onmouseleave = () => { closeBtn.style.background = "transparent"; };
      header.appendChild(closeBtn);

      /* ── Body ─────────────────────────────────────────────── */
      const body = document.createElement("div");
      body.style.cssText = `
        flex: 1;
        padding: 16px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        overflow: auto;
        background-color: ${bodyBgColor};
        ${bodyBgImage ? `background-image: url(${bodyBgImage}); background-size: cover; background-position: center;` : ""}
      `;

      // Chat bubble
      const bubble = document.createElement("div");
      bubble.style.cssText = `
        border-radius: 16px;
        border-top-left-radius: 0;
        padding: 12px 16px;
        font-size: 13px;
        line-height: 1.6;
        box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        max-width: 90%;
        border: 1px solid rgba(0,0,0,0.05);
        background: ${welcomeBg};
        color: ${welcomeColor};
        word-break: break-word;
        white-space: pre-wrap;
      `;

      const bubbleText = document.createElement("p");
      bubbleText.style.cssText = "margin:0;font-weight:500;";
      bubbleText.textContent = welcome;
      bubble.appendChild(bubbleText);

      const bubbleTime = document.createElement("p");
      bubbleTime.style.cssText = "text-align:right;font-size:9px;opacity:0.4;margin:4px 0 0;font-weight:700;";
      bubbleTime.textContent = time;
      bubble.appendChild(bubbleTime);

      body.appendChild(bubble);

      // Bottom section (button + powered by)
      const bottomSection = document.createElement("div");
      bottomSection.style.cssText = "padding-top:8px;flex-shrink:0;";

      const startBtn = document.createElement("button");
      startBtn.style.cssText = `
        width: 100%;
        padding: 12px 24px;
        border-radius: 12px;
        border: none;
        font-weight: 700;
        font-size: 14px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        cursor: pointer;
        transition: filter 0.2s, transform 0.1s;
        box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1);
        background: ${btnBg};
        color: ${btnTextColor};
      `;
      startBtn.textContent = btnText;

      startBtn.onmouseenter = () => { startBtn.style.filter = "brightness(1.1)"; };
      startBtn.onmouseleave = () => { startBtn.style.filter = "brightness(1)"; };
      startBtn.onmousedown = () => { startBtn.style.transform = "scale(0.98)"; };
      startBtn.onmouseup = () => { startBtn.style.transform = "scale(1)"; };
      startBtn.onclick = () => {
        if (whatsappUrl) window.open(whatsappUrl, "_blank");
      };

      bottomSection.appendChild(startBtn);

      const poweredBy = document.createElement("p");
      poweredBy.style.cssText = "text-align:center;font-size:10px;margin:6px 0 0;font-weight:600;color:#6b7280;";
      poweredBy.innerHTML = `⚡ by <span style="color:${headerBg};">WhatsDesk</span>`;
      bottomSection.appendChild(poweredBy);

      body.appendChild(bottomSection);

      /* ── Toggle Button ───────────────────────────────────── */
      const toggleBtn = document.createElement("div");
      toggleBtn.style.cssText = `
        width: 56px;
        height: 56px;
        border-radius: 50%;
        box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25);
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        position: relative;
        border: 2px solid #fff;
        transition: transform 0.2s;
        background: ${widgetColor};
        color: #fff;
        ${pos.includes("left") ? "margin-right:auto;" : "margin-left:auto;"}
      `;

      // Inner content for toggle (icon or image)
      const toggleContent = document.createElement("div");
      toggleContent.style.cssText = "display:flex;align-items:center;justify-content:center;transition:transform 0.2s,opacity 0.2s;";

      const updateToggleContent = () => {
        toggleContent.innerHTML = "";
        if (isOpen) {
          toggleContent.innerHTML = closeLargeSvg;
        } else {
          if (logo) {
            const tImg = document.createElement("img");
            tImg.src = logo;
            tImg.alt = "widget";
            tImg.style.cssText = "width:40px;height:40px;border-radius:50%;object-fit:cover;";
            toggleContent.appendChild(tImg);
          } else {
            toggleContent.innerHTML = chatIconSvg;
          }
        }
      };
      updateToggleContent();
      toggleBtn.appendChild(toggleContent);

      // Green pulse dot
      const pulseDot = document.createElement("span");
      pulseDot.style.cssText = `
        position: absolute;
        top: 0;
        right: 0;
        width: 14px;
        height: 14px;
        background: #34d399;
        border-radius: 50%;
        border: 3px solid #fff;
        animation: vfPulse 2s cubic-bezier(0.4,0,0.6,1) infinite;
        display: ${isOpen ? "none" : "block"};
      `;
      toggleBtn.appendChild(pulseDot);

      // Hover
      toggleBtn.onmouseenter = () => { toggleBtn.style.transform = "scale(1.05)"; };
      toggleBtn.onmouseleave = () => { toggleBtn.style.transform = "scale(1)"; };

      /* ── Toggle logic ────────────────────────────────────── */
      const openWidget = () => {
        isOpen = true;
        card.style.display = "flex";
        card.style.animation = "vfSlideUp 0.35s cubic-bezier(0.34,1.56,0.64,1) forwards";
        pulseDot.style.display = "none";
        updateToggleContent();
      };

      const closeWidget = () => {
        isOpen = false;
        card.style.animation = "vfSlideDown 0.25s ease-in forwards";
        pulseDot.style.display = "block";
        updateToggleContent();
        setTimeout(() => {
          if (!isOpen) {
            card.style.display = "none";
          }
        }, 250);
      };

      toggleBtn.onclick = () => {
        if (isOpen) closeWidget();
        else openWidget();
      };

      closeBtn.onclick = () => {
        closeWidget();
      };

      /* ── Assemble ────────────────────────────────────────── */
      card.appendChild(header);
      card.appendChild(body);

      wrapper.appendChild(card);
      wrapper.appendChild(toggleBtn);

      container.innerHTML = "";
      container.appendChild(wrapper);
    };

    (async () => {
      const apiData = await fetchWidgetDetails();
      renderWidget(apiData || {});
    })();
  } catch {
  }
})();
