<?php
/**
 * VMO Premium Shell
 *
 * Wraps AI-generated page HTML in the modern front-end runtime
 * (Inter font, Tailwind, GSAP + ScrollTrigger, Lenis smooth scroll,
 * Swiper, AOS) plus the base styles and initialization scripts the
 * generated markup relies on. This is applied unconditionally to every
 * generated website so the output always renders with its intended
 * design system — it replaces the old GrapesJS composer shell, which
 * was gated behind an editor key and therefore frequently left
 * generated sites without their CSS/JS runtime.
 *
 * @since 9.3.0
 */
if (!defined('ABSPATH')) exit;

class VMO_Premium_Shell {

    /* ────────────────── CDN CONFIGURATION ────────────────── */

    const CDN = [
        'font'          => 'https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap',
        'tailwind'      => 'https://cdn.tailwindcss.com',
        'gsap'          => 'https://unpkg.com/gsap@3.12.5/dist/gsap.min.js',
        'scrolltrigger' => 'https://unpkg.com/gsap@3.12.5/dist/ScrollTrigger.min.js',
        'lenis'         => 'https://cdn.jsdelivr.net/npm/lenis@1.1.13/dist/lenis.min.js',
        'swiper_css'    => 'https://unpkg.com/swiper@11/swiper-bundle.min.css',
        'swiper_js'     => 'https://unpkg.com/swiper@11/swiper-bundle.min.js',
        'aos_css'       => 'https://unpkg.com/aos@2.3.4/dist/aos.css',
        'aos_js'        => 'https://unpkg.com/aos@2.3.4/dist/aos.js',
    ];

    /**
     * Wrap raw page HTML in the premium runtime shell.
     *
     * @param string $html Raw page HTML from AI generation.
     * @param array  $meta Optional: primary_color, accent_color, tech_stack, business_name.
     * @return string Full HTML with CDN references, base styles, and initialization scripts.
     */
    public static function wrap($html, $meta = []) {
        $html    = self::sanitize_output_html($html);
        $primary = esc_attr($meta['primary_color'] ?? '#0f172a');
        $accent  = esc_attr($meta['accent_color']  ?? '#0ea5e9');
        $biz     = esc_attr($meta['business_name']  ?? '');
        $tech    = is_array($meta['tech_stack'] ?? null) ? $meta['tech_stack'] : ['Tailwind CSS', 'GSAP', 'Lenis'];

        $cdn_head     = self::build_cdn_head($tech, $primary, $accent);
        $base_css     = self::build_base_css($primary, $accent);
        $init_scripts = self::build_init_scripts();

        return $cdn_head
            . "\n<style data-vmo-premium=\"base\">" . $base_css . "</style>\n"
            . '<div id="vmo-page" class="vmo-page font-[Inter,system-ui,sans-serif]" '
            . 'data-vmo-generated="premium-shell" data-business="' . $biz . '">' . "\n"
            . $html . "\n"
            . "</div>\n"
            . $init_scripts;
    }

    private static function sanitize_output_html($html) {
        $html = (string) $html;
        if ($html === '') {
            return '';
        }
        $html = preg_replace('/<!--.*?-->/s', '', $html);
        $html = preg_replace('/AI\s+Image\s+Generating\.\.\./i', '', $html);
        $html = preg_replace('/AI\s+Video\s+Generating\.\.\./i', '', $html);
        $html = preg_replace('/A professional (image|video) will appear here/i', '', $html);
        return is_string($html) ? $html : '';
    }

    private static function build_cdn_head($tech, $primary = '#0f172a', $accent = '#0ea5e9') {
        $out  = '<link rel="preconnect" href="https://fonts.googleapis.com">';
        $out .= '<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>';
        $out .= '<link rel="stylesheet" href="' . self::CDN['font'] . '">';
        $out .= '<script src="' . self::CDN['tailwind'] . '"></script>';
        $out .= '<script>tailwind.config={theme:{extend:{colors:{primary:"' . $primary . '",accent:"' . $accent . '"},fontFamily:{sans:["Inter","system-ui","sans-serif"]}}}}</script>';
        $out .= '<link rel="stylesheet" href="' . self::CDN['swiper_css'] . '">';
        $out .= '<link rel="stylesheet" href="' . self::CDN['aos_css'] . '">';
        return $out . "\n";
    }

    private static function build_base_css($primary, $accent) {
        return <<<CSS
:root{--vmo-primary:{$primary};--vmo-accent:{$accent};}
html{scroll-behavior:smooth;}
body{margin:0;font-family:Inter,system-ui,-apple-system,sans-serif;-webkit-font-smoothing:antialiased;}
[data-vmo-animate]{opacity:0;transform:translateY(32px);transition:opacity .7s cubic-bezier(.16,1,.3,1),transform .7s cubic-bezier(.16,1,.3,1);}
[data-vmo-animate].vmo-visible{opacity:1;transform:translateY(0);}
.swiper-pagination-bullet-active{background:var(--vmo-accent)!important;}
.vmo-overlay-container{position:absolute;inset:0;pointer-events:none;overflow:hidden;z-index:1;}
CSS;
    }

    private static function build_init_scripts() {
        return '<script src="' . self::CDN['gsap'] . '"></script>'
            . '<script src="' . self::CDN['scrolltrigger'] . '"></script>'
            . '<script src="' . self::CDN['lenis'] . '"></script>'
            . '<script src="' . self::CDN['swiper_js'] . '"></script>'
            . '<script src="' . self::CDN['aos_js'] . '"></script>'
            . '<script>'
            . self::build_init_js()
            . '</script>' . "\n";
    }

    private static function build_init_js() {
        return <<<'JS'
(function(){
  "use strict";

  /* ── Lenis smooth scroll ── */
  if(window.Lenis){
    var lenis=new Lenis({duration:1.2,easing:function(t){return Math.min(1,1.001-Math.pow(2,-10*t))},smoothWheel:true});
    function raf(time){lenis.raf(time);requestAnimationFrame(raf);}
    requestAnimationFrame(raf);
    if(window.gsap&&window.ScrollTrigger){
      lenis.on("scroll",function(){window.ScrollTrigger.update();});
      window.gsap.ticker.add(function(time){lenis.raf(time*1000);});
      window.gsap.ticker.lagSmoothing(0);
    }
  }

  /* ── GSAP ScrollTrigger reveal ── */
  if(window.gsap&&window.ScrollTrigger){
    window.gsap.registerPlugin(window.ScrollTrigger);
    document.querySelectorAll("[data-vmo-animate]").forEach(function(el){
      window.gsap.fromTo(el,{opacity:0,y:40},{opacity:1,y:0,duration:0.8,ease:"power3.out",scrollTrigger:{trigger:el,start:"top 88%",once:true}});
    });
  }else{
    /* Fallback: IntersectionObserver */
    var obs=new IntersectionObserver(function(entries){entries.forEach(function(e){if(e.isIntersecting){e.target.classList.add("vmo-visible");obs.unobserve(e.target);}});},{threshold:0.1});
    document.querySelectorAll("[data-vmo-animate]").forEach(function(el){obs.observe(el);});
  }

  /* ── AOS init ── */
  if(window.AOS){window.AOS.init({once:true,duration:700});}

  /* ── Swiper carousels ── */
  if(window.Swiper){
    document.querySelectorAll(".vmo-testimonial-swiper").forEach(function(el){
      new Swiper(el,{slidesPerView:1,spaceBetween:24,pagination:{el:el.querySelector(".swiper-pagination"),clickable:true},breakpoints:{768:{slidesPerView:2},1024:{slidesPerView:3}}});
    });
  }

  /* ── Media replace buttons ── */
  document.querySelectorAll(".vmo-replace-btn").forEach(function(btn){
    btn.addEventListener("click",function(e){
      e.preventDefault();
      e.stopPropagation();
      var mediaId=btn.getAttribute("data-replace-media");
      if(window.vmoOpenMediaPicker){window.vmoOpenMediaPicker(mediaId);}
      else if(window.parent&&window.parent.vmoOpenMediaPicker){window.parent.vmoOpenMediaPicker(mediaId);}
    });
  });

  /* ── Overlay containers ── */
  document.querySelectorAll("[data-vmo-section-type='hero']").forEach(function(hero){
    if(!hero.querySelector(".vmo-overlay-container")){
      var c=document.createElement("div");c.className="vmo-overlay-container";c.setAttribute("data-vmo-overlay-slot","hero");
      hero.insertBefore(c,hero.firstChild);
    }
  });

  /* ── VMO Pay buttons ── */
  document.querySelectorAll(".vmo-pay-btn").forEach(function(btn){
    btn.addEventListener("click",function(e){
      e.preventDefault();
      var product=btn.getAttribute("data-vmo-product")||"Product";
      if(window.vmoPayCheckout){window.vmoPayCheckout(product);}
      else{alert("VMO Pay checkout for: "+product);}
    });
  });

})();
JS;
    }
}
