/* global React */
// =============================================================================
// BWAY PROD — Tour interactivo step-by-step
// Componente que sobrepone un spotlight + tooltip animado sobre cualquier elemento.
// Definiciones de tours por rol más abajo (TOURS = { admin: [...], cliente: [...] })
// =============================================================================

(function () {
  const { useState, useEffect, useRef, useCallback } = React;
  const e = React.createElement;

  // -----------------------------------------------------------
  // Persistencia: qué tours ha completado el usuario
  // -----------------------------------------------------------
  function getTourState() {
    try {
      return JSON.parse(localStorage.getItem("bway_tours") || "{}");
    } catch { return {}; }
  }
  function markTourCompleted(tourId) {
    const s = getTourState();
    s[tourId] = { completed_at: Date.now() };
    localStorage.setItem("bway_tours", JSON.stringify(s));
  }
  function isTourCompleted(tourId) {
    return !!getTourState()[tourId];
  }
  function resetTour(tourId) {
    const s = getTourState();
    delete s[tourId];
    localStorage.setItem("bway_tours", JSON.stringify(s));
  }

  // -----------------------------------------------------------
  // Helper: encontrar el elemento del DOM con scroll automático
  // -----------------------------------------------------------
  function waitForElement(selector, timeout = 4000) {
    return new Promise((resolve) => {
      const el = document.querySelector(selector);
      if (el) return resolve(el);
      const start = Date.now();
      const obs = new MutationObserver(() => {
        const found = document.querySelector(selector);
        if (found) {
          obs.disconnect();
          resolve(found);
        } else if (Date.now() - start > timeout) {
          obs.disconnect();
          resolve(null);
        }
      });
      obs.observe(document.body, { childList: true, subtree: true });
    });
  }

  // -----------------------------------------------------------
  // Componente principal del Tour
  // -----------------------------------------------------------
  function Tour({ steps, onClose, tourId }) {
    const [idx, setIdx] = useState(0);
    const [rect, setRect] = useState(null);
    const [tooltipPos, setTooltipPos] = useState({ top: 0, left: 0, placement: "bottom" });
    const tooltipRef = useRef(null);

    const step = steps[idx];
    const isLast = idx === steps.length - 1;

    // Calcular posición del spotlight + tooltip
    const updatePosition = useCallback(async () => {
      if (!step) return;
      if (step.action_before) {
        try { await step.action_before(); } catch (e) { /* ignore */ }
      }

      if (!step.target) {
        // Step sin target = modal centrado en pantalla
        setRect(null);
        setTooltipPos({
          top: window.innerHeight / 2 - 120,
          left: window.innerWidth / 2 - 200,
          placement: "center"
        });
        return;
      }

      const el = await waitForElement(step.target, 2500);
      if (!el) {
        // Target no encontrado — mostrar tooltip centrado en lugar de saltar silenciosamente
        setRect(null);
        setTooltipPos({
          top: window.innerHeight / 2 - 140,
          left: window.innerWidth / 2 - 200,
          placement: "center"
        });
        return;
      }

      // Scroll al elemento
      el.scrollIntoView({ behavior: "smooth", block: "center", inline: "center" });
      await new Promise(r => setTimeout(r, 380));

      const r = el.getBoundingClientRect();
      setRect({
        top: r.top - 8,
        left: r.left - 8,
        width: r.width + 16,
        height: r.height + 16,
      });

      // Calcular posición del tooltip
      const tooltipW = 380;
      const tooltipH = 200;
      const margin = 20;
      const vw = window.innerWidth;
      const vh = window.innerHeight;

      let placement = step.placement || "auto";
      if (placement === "auto") {
        const spaceBelow = vh - r.bottom;
        const spaceAbove = r.top;
        const spaceRight = vw - r.right;
        const spaceLeft = r.left;
        if (spaceBelow >= tooltipH + margin) placement = "bottom";
        else if (spaceAbove >= tooltipH + margin) placement = "top";
        else if (spaceRight >= tooltipW + margin) placement = "right";
        else if (spaceLeft >= tooltipW + margin) placement = "left";
        else placement = "bottom";
      }

      let top = 0, left = 0;
      switch (placement) {
        case "top":
          top = r.top - tooltipH - margin;
          left = Math.max(margin, Math.min(vw - tooltipW - margin, r.left + r.width / 2 - tooltipW / 2));
          break;
        case "bottom":
          top = r.bottom + margin;
          left = Math.max(margin, Math.min(vw - tooltipW - margin, r.left + r.width / 2 - tooltipW / 2));
          break;
        case "left":
          top = Math.max(margin, Math.min(vh - tooltipH - margin, r.top + r.height / 2 - tooltipH / 2));
          left = r.left - tooltipW - margin;
          break;
        case "right":
          top = Math.max(margin, Math.min(vh - tooltipH - margin, r.top + r.height / 2 - tooltipH / 2));
          left = r.right + margin;
          break;
      }

      setTooltipPos({ top, left, placement });
    }, [step, idx, isLast]);

    useEffect(() => {
      updatePosition();
    }, [updatePosition]);

    useEffect(() => {
      const onResize = () => updatePosition();
      window.addEventListener("resize", onResize);
      window.addEventListener("scroll", onResize, true);
      return () => {
        window.removeEventListener("resize", onResize);
        window.removeEventListener("scroll", onResize, true);
      };
    }, [updatePosition]);

    // Keyboard navigation
    useEffect(() => {
      const onKey = (ev) => {
        if (ev.key === "Escape") finish(false);
        else if (ev.key === "ArrowRight" || ev.key === "Enter") next();
        else if (ev.key === "ArrowLeft") prev();
      };
      window.addEventListener("keydown", onKey);
      return () => window.removeEventListener("keydown", onKey);
    }, [idx, isLast]);

    function next() {
      if (isLast) finish(true);
      else setIdx(idx + 1);
    }
    function prev() {
      if (idx > 0) setIdx(idx - 1);
    }
    function finish(completed) {
      if (completed && tourId) markTourCompleted(tourId);
      onClose && onClose(completed);
    }

    if (!step) return null;
    const pct = Math.round(((idx + 1) / steps.length) * 100);

    return e(React.Fragment, null,
      // Spotlight overlay con clip-path
      e("div", {
        className: "tour-overlay" + (rect ? " has-spotlight" : ""),
        style: rect ? {
          clipPath: `polygon(
            0 0, 100% 0, 100% 100%, 0 100%, 0 0,
            ${rect.left}px ${rect.top}px,
            ${rect.left}px ${rect.top + rect.height}px,
            ${rect.left + rect.width}px ${rect.top + rect.height}px,
            ${rect.left + rect.width}px ${rect.top}px,
            ${rect.left}px ${rect.top}px
          )`
        } : null,
        onClick: () => finish(false)
      }),

      // Ring dorado alrededor del target
      rect ? e("div", {
        className: "tour-ring",
        style: {
          top: rect.top + "px",
          left: rect.left + "px",
          width: rect.width + "px",
          height: rect.height + "px",
        }
      }) : null,

      // Tooltip
      e("div", {
        ref: tooltipRef,
        className: "tour-tooltip tour-tooltip-" + tooltipPos.placement,
        style: { top: tooltipPos.top + "px", left: tooltipPos.left + "px" },
        onClick: (ev) => ev.stopPropagation()
      },
        e("div", { className: "tour-progress" },
          e("div", { className: "tour-progress-fill", style: { width: pct + "%" } })
        ),
        e("button", { className: "tour-close", onClick: () => finish(false), "aria-label": "Cerrar tour" }, "×"),
        e("div", { className: "tour-step-meta" },
          e("span", { className: "tour-step-num" }, String(idx + 1).padStart(2, "0"), " / ", String(steps.length).padStart(2, "0")),
          step.kicker ? e("span", { className: "tour-step-kicker" }, step.kicker) : null
        ),
        e("h4", { className: "tour-tooltip-title" }, step.title),
        e("p", { className: "tour-tooltip-body" }, step.body),
        step.tip ? e("div", { className: "tour-tip" }, e("b", null, "Tip · "), step.tip) : null,
        e("div", { className: "tour-actions" },
          e("button", {
            className: "tour-btn tour-btn-skip",
            onClick: () => finish(false)
          }, "Saltar"),
          idx > 0 ? e("button", { className: "tour-btn tour-btn-ghost", onClick: prev }, "← Anterior") : null,
          e("button", {
            className: "tour-btn tour-btn-gold",
            onClick: next
          }, isLast ? "Terminar ✓" : "Siguiente →")
        )
      )
    );
  }

  // -----------------------------------------------------------
  // Selector de tours: menú que aparece con el botón "?"
  // -----------------------------------------------------------
  function TourSelector({ tours, onStart, onClose }) {
    return e("div", { className: "tour-selector-backdrop", onClick: (ev) => { if (ev.target === ev.currentTarget) onClose(); } },
      e("div", { className: "tour-selector" },
        e("button", { className: "tour-close", onClick: onClose, "aria-label": "Cerrar" }, "×"),
        e("div", { className: "tour-selector-head" },
          e("span", { className: "tour-selector-kicker" }, "/ TUTORIALES INTERACTIVOS"),
          e("h3", null, "Aprendé paso a paso"),
          e("p", null, "Elegí un tour para conocer las funcionalidades del sistema con un recorrido guiado.")
        ),
        e("div", { className: "tour-selector-list" },
          tours.map((t) => {
            const done = isTourCompleted(t.id);
            return e("button", {
              key: t.id,
              className: "tour-selector-item" + (done ? " is-done" : ""),
              onClick: () => onStart(t)
            },
              e("div", { className: "tour-selector-icon" }, t.icon || "▶"),
              e("div", { className: "tour-selector-info" },
                e("div", { className: "tour-selector-name" }, t.name, done ? e("span", { className: "tour-selector-done" }, " ✓") : null),
                e("div", { className: "tour-selector-desc" }, t.description),
                e("div", { className: "tour-selector-meta" },
                  e("span", null, t.steps.length + " pasos"),
                  e("span", null, "·"),
                  e("span", null, t.duration || "2-3 min")
                )
              ),
              e("span", { className: "tour-selector-arrow" }, "→")
            );
          })
        )
      )
    );
  }

  // -----------------------------------------------------------
  // Floating help button
  // -----------------------------------------------------------
  function TourHelpButton({ onClick }) {
    return e("button", {
      className: "tour-help-btn",
      onClick,
      title: "Ver tutoriales",
      "aria-label": "Abrir tutoriales"
    },
      e("span", { className: "tour-help-icon" }, "?"),
      e("span", { className: "tour-help-pulse", "aria-hidden": "true" })
    );
  }

  // -----------------------------------------------------------
  // TOURS — Definiciones por rol
  // -----------------------------------------------------------
  const TOURS = {
    landing: [
      {
        id: "landing_basics",
        name: "Recorrido del landing",
        icon: "🎬",
        description: "Conocé las 13 secciones del sitio público y cómo se cuenta la historia de BWAY.",
        duration: "2 min",
        steps: [
          {
            title: "Bienvenido a BWAY PROD",
            kicker: "Landing público",
            body: "Vas a recorrer las secciones del sitio público. Cada una es una pieza de la historia que cuenta tu marca.",
            placement: "center"
          },
          {
            target: "nav, .nav, header.nav",
            title: "Navegación",
            body: "Desde acá llegás rápido a Origen, Portafolio, Herbosías, Tienda y al login. El logo está al centro.",
            placement: "bottom",
            tip: "Hacé scroll y la nav se contrae para no estorbar."
          },
          {
            target: ".bn-hero, .hero, section.hero",
            title: "Hero — Mensaje principal",
            body: "El valor no está en lo que dura el evento, está en lo que queda después. Esta es la primera impresión de tu marca.",
            placement: "auto"
          },
          {
            target: "#origen, .origen, section[id='origen']",
            title: "Origen",
            body: "La historia del estudio con tipografía editorial. Acá explicás de dónde venís y por qué.",
            placement: "auto"
          },
          {
            target: ".pf2, #portafolio, .portfolio-section",
            title: "Portafolio",
            body: "Casos de éxito interactivos. Cada card se puede abrir en popup con detalles del proyecto.",
            placement: "auto",
            tip: "Las cards tienen efecto 3D al hacer hover."
          },
          {
            target: ".bw-shop, #tienda",
            title: "Tienda digital",
            body: "Productos descargables: LUTs, presets, templates. Los compradores los descargan al instante.",
            placement: "auto"
          },
          {
            target: "#cta, .cta",
            title: "El CTA — Captación de leads",
            body: "Acá los visitantes solicitan su cotización personalizada. Cada solicitud llega a tu bandeja en /dashboard/admin/requests.",
            placement: "top",
            tip: "El form tiene 5 capas de protección anti-spam invisibles."
          }
        ]
      }
    ],
    admin: [
      {
        id: "admin_overview",
        name: "Tour general del admin",
        icon: "🛡",
        description: "Conocé las 8 secciones del dashboard admin y cómo navegarlas.",
        duration: "3 min",
        steps: [
          {
            title: "Bienvenido al control center",
            kicker: "Admin",
            body: "Vas a recorrer las herramientas que tenés como admin: proyectos, cotizaciones, solicitudes, métricas y más.",
            placement: "center"
          },
          {
            target: ".dash-side, .dash-side-nav",
            title: "Sidebar de navegación",
            body: "Acá vivís el 80% del tiempo. Cada ícono lleva a una sección distinta: dashboard, métricas, solicitudes, proyectos, cotizaciones, colaboradores, tienda, invitaciones.",
            placement: "right"
          },
          {
            target: ".dash-main, main.dash-main, .dash-content, .dash-shell",
            title: "Área de trabajo",
            body: "Acá renderiza la sección actual. Empieza siempre en el Dashboard ejecutivo.",
            placement: "auto"
          },
          {
            target: "a[href*='quotes'], a[href='#/dashboard/admin/quotes']",
            title: "Cotizaciones — el corazón comercial",
            body: "El Quote Builder con 85 servicios del catálogo MUSA en 19 categorías. Es donde vas a pasar más tiempo creando propuestas.",
            placement: "right"
          },
          {
            target: "a[href*='requests']",
            title: "Solicitudes del CTA",
            body: "Cada vez que alguien llena el form del landing, llega acá. Podés aprobar (envía magic link + crea quote draft), marcar como contactado, o rechazar.",
            placement: "right"
          },
          {
            target: "a[href*='stats']",
            title: "Métricas",
            body: "Funnel de conversión, ingresos mensuales últimos 6 meses, top categorías más vendidas. Tu termómetro de negocio.",
            placement: "right"
          }
        ]
      },
      {
        id: "admin_quote_builder",
        name: "Cómo crear una cotización",
        icon: "✎",
        description: "Tutorial completo del editor 3D — desde elegir cliente hasta enviar el PDF.",
        duration: "4 min",
        steps: [
          {
            title: "Vamos a armar una cotización",
            kicker: "Quote Builder",
            body: "Te muestro paso a paso cómo construir una cotización profesional usando el catálogo MUSA.",
            placement: "center",
            action_before: async () => {
              if (!location.hash.includes("/dashboard/admin/quotes")) {
                location.hash = "#/dashboard/admin/quotes";
                await new Promise(r => setTimeout(r, 1500));
              }
            }
          },
          {
            target: ".qb2-cta-new, button[class*='cta-new']",
            title: "Nueva cotización",
            body: "Click acá para empezar desde cero. Si tenés una plantilla guardada, podés cargarla después.",
            placement: "auto"
          },
          {
            target: ".qb2-filters, .qb-list-filters",
            title: "Filtros de status",
            body: "Mientras estás en el listado, podés filtrar por borradores, enviadas, aprobadas o rechazadas.",
            placement: "auto"
          },
          {
            target: ".qb2-stats",
            title: "KPIs en vivo",
            body: "Total facturable, monto aprobado, tasa de conversión y cuántas tenés en vuelo. Se actualizan al instante.",
            placement: "auto"
          },
          {
            target: ".qb2-grid, .qb2-empty",
            title: "Cards estilo cinta de film",
            body: "Cada cotización es una card. La barra superior es el color del status. Click para entrar al editor.",
            placement: "top"
          }
        ]
      },
      {
        id: "admin_templates",
        name: "Plantillas reusables",
        icon: "★",
        description: "Guardá paquetes pre-armados que usás seguido para crear quotes en 1 click.",
        duration: "1 min",
        steps: [
          {
            title: "Plantillas — el truco de los pros",
            kicker: "Templates",
            body: "Si armás seguido el mismo paquete (Plan FLOW, Boda Premium, etc.) podés guardarlo como plantilla y aplicarlo en 1 click.",
            placement: "center"
          },
          {
            title: "Cómo guardar una plantilla",
            kicker: "Paso 1",
            body: "Armá una cotización completa con sus line items, descuento, impuesto y notas. Después click en '★ Guardar como plantilla', ponele nombre y descripción.",
            placement: "center"
          },
          {
            title: "Cómo aplicarla",
            kicker: "Paso 2",
            body: "En una cotización nueva, click '✦ Plantillas' en el header. Elegí una de la lista (ordenadas por más usadas) y se llena el carrito automático.",
            placement: "center",
            tip: "Las plantillas se ordenan por más usadas — las más populares quedan arriba."
          }
        ]
      },
      {
        id: "admin_share",
        name: "Compartir cotización por WhatsApp",
        icon: "🔗",
        description: "Generá un link público para clientes que prefieren no loguearse.",
        duration: "1 min",
        steps: [
          {
            title: "Link público de cotización",
            kicker: "Share",
            body: "Algunos clientes no quieren registrarse. Para ellos, podés generar un link público que muestra la cotización en vista editorial premium.",
            placement: "center"
          },
          {
            title: "Cómo generar el link",
            kicker: "Cómo",
            body: "Abrí cualquier cotización en estado 'sent' o 'approved'. En el header, click '🔗 Compartir link'. Se copia al portapapeles automáticamente.",
            placement: "center",
            tip: "El link no incluye email del cliente ni datos internos por seguridad."
          },
          {
            title: "Tracking de vistas",
            kicker: "Bonus",
            body: "Cada vez que alguien abre el link, se incrementa un contador. Así sabés cuántas veces lo miraron antes de decidir.",
            placement: "center"
          }
        ]
      },
      {
        id: "admin_requests",
        name: "Bandeja de solicitudes",
        icon: "✦",
        description: "Cómo procesar las solicitudes del CTA del landing.",
        duration: "2 min",
        steps: [
          {
            title: "Bandeja del CTA",
            kicker: "Solicitudes",
            body: "Cada vez que alguien llena el form del landing, llega acá. Tu trabajo es aprobar, contactar o rechazar.",
            placement: "center",
            action_before: async () => {
              if (!location.hash.includes("/dashboard/admin/requests")) {
                location.hash = "#/dashboard/admin/requests";
                await new Promise(r => setTimeout(r, 1500));
              }
            }
          },
          {
            target: ".qb-list-filters, .qb2-filters",
            title: "Filtros por status",
            body: "Pendiente, Contactado, Aprobado, Rechazado. Empezá siempre por Pendientes.",
            placement: "auto"
          },
          {
            target: ".qb-client-card:first-of-type, .qb-client-card",
            title: "Card de solicitud",
            body: "Tenés todos los datos: nombre, empresa, email, teléfono, brief del proyecto y rango de presupuesto declarado.",
            placement: "auto"
          },
          {
            title: "Acción 1 — Aprobar e invitar",
            kicker: "Recomendado",
            body: "Click ✓ Aprobar e invitar → pide notas opcionales → manda magic link al solicitante → marca como aprobado → CREA AUTOMÁTICAMENTE una cotización en draft asociada al nuevo cliente.",
            placement: "center",
            tip: "El auto-quote draft te ahorra clicks: cuando entrás a Cotizaciones, ya está lista para editar."
          },
          {
            title: "Acción 2 — Marcar como contactado",
            kicker: "Alternativa",
            body: "Si ya hablaste por WhatsApp o llamada, marcalo como contactado para trackear sin enviar magic link aún.",
            placement: "center"
          },
          {
            title: "Acción 3 — Rechazar",
            kicker: "Cuando no aplica",
            body: "Si no es un fit, rechazá con motivo interno (no se le manda nada al cliente). Sirve para limpiar la bandeja.",
            placement: "center"
          }
        ]
      }
    ],
    cliente: [
      {
        id: "cliente_dashboard",
        name: "Tour de tu dashboard",
        icon: "🎯",
        description: "Conocé cómo ver tus proyectos, el avance del Método MUSA y tus cotizaciones.",
        duration: "2 min",
        steps: [
          {
            title: "Bienvenido a tu estudio",
            kicker: "Cliente",
            body: "Acá ves el avance de tus producciones en tiempo real. El equipo BWAY actualiza el dashboard mientras trabaja.",
            placement: "center"
          },
          {
            target: ".kpi-grid, .client-kpi-grid",
            title: "Tus KPIs",
            body: "Proyectos activos, progreso promedio, en producción y próxima entrega. Un vistazo del estado general.",
            placement: "auto"
          },
          {
            target: ".client-pulse, .dash-card:has(.client-pulse-tag), section.dash-card",
            title: "Pulso del estudio",
            body: "La actualización más reciente del equipo BWAY. Si está en verde 'EN VIVO', algo se actualizó en las últimas horas.",
            placement: "auto"
          },
          {
            target: ".project-card, .client-project-card",
            title: "Cards de proyectos",
            body: "Cada card es un proyecto activo. Mostramos el avance dentro del Método MUSA: Invocación → Canalización → Manifestación → Alquimia → Eternización.",
            placement: "auto",
            tip: "Click en una card para ver bitácora completa con fotos, links y videos."
          },
          {
            target: ".qb-client-card, [class*='client-card']",
            title: "Cotizaciones recibidas",
            body: "Acá aparecen las propuestas que te enviamos. Las podés aprobar, rechazar o descargar como PDF.",
            placement: "auto"
          }
        ]
      },
      {
        id: "cliente_quotes",
        name: "Cómo aprobar/rechazar una cotización",
        icon: "✓",
        description: "El flujo para responder propuestas recibidas del estudio.",
        duration: "1 min",
        steps: [
          {
            title: "Cómo responder cotizaciones",
            kicker: "Cliente",
            body: "Cuando el equipo BWAY te envía una cotización, aparece en tu dashboard. Tenés 3 acciones disponibles.",
            placement: "center"
          },
          {
            title: "Revisá los detalles",
            kicker: "Paso 1",
            body: "Cada cotización muestra el título, los servicios incluidos, descuento, impuesto, total destacado en oro y notas del estudio.",
            placement: "center",
            tip: "Si tu cotización tiene muchos items, hacé scroll dentro de la card."
          },
          {
            title: "Aprobar ✓",
            kicker: "Opción A",
            body: "Si te gusta, click ✓ Aprobar. Te pide un comentario opcional (ej: 'coordinamos por WhatsApp'). El equipo recibe email automático con tu respuesta.",
            placement: "center"
          },
          {
            title: "Rechazar ✕",
            kicker: "Opción B",
            body: "Si querés ajustes, click ✕ Rechazar y dejá el motivo. El equipo BWAY puede armar una versión nueva basada en tu feedback.",
            placement: "center"
          },
          {
            title: "Descargar PDF",
            kicker: "Opción C",
            body: "Click '⬇ Descargar PDF' en cualquier momento para tener una copia editorial premium para tus archivos o para compartir internamente.",
            placement: "center"
          }
        ]
      }
    ],
    usuario: [
      {
        id: "usuario_dashboard",
        name: "Tour del colaborador",
        icon: "🎬",
        description: "Cómo ver tus proyectos asignados y subir actualizaciones.",
        duration: "2 min",
        steps: [
          {
            title: "Bienvenido al equipo",
            kicker: "Colaborador",
            body: "Como colaborador BWAY, ves los proyectos donde estás asignado y podés subir actualizaciones de las etapas que trabajaste.",
            placement: "center"
          },
          {
            target: ".project-list, .dash-content",
            title: "Tus proyectos",
            body: "Solo ves los proyectos donde el admin te asignó. Click en cualquiera para abrir el detalle.",
            placement: "auto"
          },
          {
            title: "Cómo subir una actualización",
            kicker: "Workflow",
            body: "Abrí un proyecto → buscá la etapa actual del Método MUSA → click 'Subir actualización' → adjuntá fotos, videos o links de Drive/Vimeo.",
            placement: "center",
            tip: "Marcá la etapa como completada solo cuando esté lista para revisión del admin."
          }
        ]
      }
    ]
  };

  // -----------------------------------------------------------
  // Controlador global del tour — expone API window.bwayTour
  // -----------------------------------------------------------
  window.BwayTours = {
    Tour, TourSelector, TourHelpButton,
    TOURS,
    getTourState, markTourCompleted, isTourCompleted, resetTour,
  };
})();
