// CourseCheckoutService.jsx — contact submission and Hotmart Checkout Widget helpers.
const courseCheckoutConfig = window.CourseFunnelData.config;
const COURSE_BUYER_STORAGE_KEY = 'anthony-course-buyer';
const HOTMART_WIDGET_SCRIPT_ID = 'course-hotmart-widget';
const HOTMART_WIDGET_STYLES_ID = 'course-hotmart-widget-styles';
const HOTMART_WIDGET_SCRIPT_URL = 'https://static.hotmart.com/checkout/widget.min.js';
const HOTMART_WIDGET_STYLES_URL = 'https://static.hotmart.com/css/hotmart-fb.min.css';

function createCourseRequestId() {
  if (window.crypto?.randomUUID) return window.crypto.randomUUID();
  return `course-${Date.now()}-${Math.random().toString(16).slice(2)}`;
}

function isValidCourseEmail(value) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(value || '').trim());
}

function normalizeCourseBuyer(buyer) {
  return {
    name: String(buyer?.name || '').trim().slice(0, 100),
    email: String(buyer?.email || '').trim().toLowerCase().slice(0, 160),
    whatsapp: String(buyer?.whatsapp || '').trim().slice(0, 40),
    idea: String(buyer?.idea || '').trim().slice(0, 1200),
  };
}

function getStoredCourseBuyer() {
  try {
    const storedBuyer = JSON.parse(sessionStorage.getItem(COURSE_BUYER_STORAGE_KEY));
    const buyer = normalizeCourseBuyer(storedBuyer);
    return buyer.name && isValidCourseEmail(buyer.email) ? buyer : null;
  } catch {
    return null;
  }
}

function storeCourseBuyer(buyer) {
  const normalizedBuyer = normalizeCourseBuyer(buyer);
  sessionStorage.setItem(COURSE_BUYER_STORAGE_KEY, JSON.stringify(normalizedBuyer));
  return normalizedBuyer;
}

function isCourseLocalPreview() {
  return ['localhost', '127.0.0.1'].includes(window.location.hostname);
}

async function submitCourseLead(buyer) {
  const normalizedBuyer = normalizeCourseBuyer(buyer);
  const payload = {
    ...normalizedBuyer,
    website: String(buyer?.website || ''),
    consent: Boolean(buyer?.consent),
    requestId: createCourseRequestId(),
    source: 'course_checkout',
  };

  if (isCourseLocalPreview()) {
    await new Promise((resolve) => window.setTimeout(resolve, 260));
    return { ok: true, preview: true, buyer: normalizedBuyer };
  }

  const controller = new AbortController();
  const timeoutId = window.setTimeout(() => controller.abort(), 12000);

  try {
    const response = await fetch(courseCheckoutConfig.contactEndpoint, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
      signal: controller.signal,
    });

    const result = await response.json().catch(() => ({}));
    if (!response.ok || !result.ok) {
      throw new Error(result.message || 'No pudimos guardar tus datos.');
    }

    return { ...result, buyer: normalizedBuyer };
  } catch (error) {
    if (error.name === 'AbortError') {
      throw new Error('La conexión tardó demasiado. Probá nuevamente.');
    }
    throw error;
  } finally {
    window.clearTimeout(timeoutId);
  }
}

function buildCoursePaymentUrl() {
  if (!courseCheckoutConfig.checkoutUrl) return '';

  try {
    return new URL(courseCheckoutConfig.checkoutUrl, window.location.origin).toString();
  } catch {
    return '';
  }
}

function loadHotmartCheckoutWidget() {
  if (!document.getElementById(HOTMART_WIDGET_STYLES_ID)) {
    const stylesheet = document.createElement('link');
    stylesheet.id = HOTMART_WIDGET_STYLES_ID;
    stylesheet.rel = 'stylesheet';
    stylesheet.type = 'text/css';
    stylesheet.href = HOTMART_WIDGET_STYLES_URL;
    document.head.appendChild(stylesheet);
  }

  const existingScript = document.getElementById(HOTMART_WIDGET_SCRIPT_ID);
  if (existingScript) return Promise.resolve();

  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.id = HOTMART_WIDGET_SCRIPT_ID;
    script.src = HOTMART_WIDGET_SCRIPT_URL;
    script.async = true;
    script.onload = resolve;
    script.onerror = () => reject(new Error('No se pudo cargar el checkout embebido de Hotmart.'));
    document.head.appendChild(script);
  });
}

Object.assign(window, {
  isValidCourseEmail,
  getStoredCourseBuyer,
  storeCourseBuyer,
  submitCourseLead,
  buildCoursePaymentUrl,
  loadHotmartCheckoutWidget,
});
