import { useEffect, useRef, useState } from "react";
import { CheckCircle, MessageSquare, Loader2, Zap } from "lucide-react";
import chatskuLogo from "@/assets/chatsku-logo.png";
import Navbar from "@/components/Navbar";
import { getPartnerCode } from "@/hooks/use-partner-code";

const REVENUTIZE_TOKEN = "af175cab1678fbf8897bb299afc5d6fb92e8234926d5fd3bba6c62882ef17efe";
const REVENUTIZE_BASE = "https://revenutize.com";

const Signup = () => {
  const containerRef = useRef<HTMLDivElement>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    // Prevent duplicate injection
    if (container.querySelector('script')) {
      setLoading(false);
      return;
    }

    // Inject the original embed snippet as raw HTML so document.currentScript works
    const partnerCode = getPartnerCode();
    const partnerAttr = partnerCode ? ` data-partner-code="${partnerCode}"` : "";
    const wrapper = document.createElement("div");
    wrapper.innerHTML = `
      <div data-cf-token="${REVENUTIZE_TOKEN}"${partnerAttr}></div>
      <script>
        (function(){
          var t="${REVENUTIZE_TOKEN}",u="${REVENUTIZE_BASE}";
          var s=document.createElement("script");
          s.src=u+"/api/public/forms/widget.js";
          s.setAttribute("data-token",t);
          s.setAttribute("data-base-url",u);
          document.currentScript.parentNode.insertBefore(s,document.currentScript);
        })()
      <\/script>
    `;

    // Move children into container
    while (wrapper.firstChild) {
      container.appendChild(wrapper.firstChild);
    }

    // innerHTML doesn't execute scripts — we need to manually re-insert the script
    const inlineScript = container.querySelector('script');
    if (inlineScript) {
      const newScript = document.createElement('script');
      newScript.textContent = inlineScript.textContent;
      inlineScript.parentNode?.replaceChild(newScript, inlineScript);
    }

    // Wait for the widget to actually render before hiding loader
    const observer = new MutationObserver(() => {
      // Look for any substantial content the widget injects (beyond our initial div+script)
      const hasRendered = container.querySelector('form, iframe, input, select, button, label, .cf-turnstile, [class*="form"], [class*="widget"]');
      if (hasRendered || container.querySelectorAll('*').length > 5) {
        setLoading(false);
        observer.disconnect();
      }
    });
    observer.observe(container, { childList: true, subtree: true });

    // Fallback timeout so we don't spin forever
    const timeout = setTimeout(() => {
      setLoading(false);
      observer.disconnect();
    }, 8000);

    return () => {
      observer.disconnect();
      clearTimeout(timeout);
    };
  }, []);

  return (
    <div className="min-h-screen bg-background">
      <Navbar />
      <main className="pt-16 min-h-screen flex">
        {/* Widget Side */}
        <div className="flex-1 flex items-center justify-center px-4 sm:px-8 py-16">
          <div className="w-full max-w-md">
            <div className="mb-8">
              <h1 className="font-display font-bold text-3xl sm:text-4xl text-foreground mb-2">
                Start selling in minutes
              </h1>
              <p className="text-muted-foreground">
                Tell us a bit about your business and we'll get you set up.
              </p>
            </div>
            <div ref={containerRef} className="min-h-[400px] relative">
              {loading && (
                <div className="absolute inset-0 flex items-center justify-center">
                  <Loader2 className="w-8 h-8 text-primary animate-spin" />
                </div>
              )}
              
            </div>
          </div>
        </div>

        {/* Value Panel */}
        <div className="hidden lg:flex w-[420px] xl:w-[480px] flex-shrink-0 bg-card border-l border-border p-12 flex-col justify-center relative overflow-hidden">
          <div className="absolute inset-0 bg-radial-teal opacity-60" />
          <div className="relative">
            <div className="flex items-center gap-2 mb-8">
              <img src={chatskuLogo} alt="ChatSKU" className="h-8" />
            </div>
            <h2 className="font-display font-bold text-2xl text-foreground mb-2">
              Everything you need to start selling.
            </h2>
            <p className="text-sm text-muted-foreground mb-8">
              Join B2B businesses that are turning their static catalogs into live buying experiences.
            </p>
            <ul className="space-y-4">
              {[
                { icon: MessageSquare, text: "AI that knows your entire catalog from day one" },
                { icon: CheckCircle, text: "Most stores go live the same day they sign up" },
                { icon: Zap, text: "One line of code — no developers needed" },
              ].map(({ icon: Icon, text }) => (
                <li key={text} className="flex items-start gap-3">
                  <div className="w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0 mt-0.5">
                    <Icon className="w-4 h-4 text-primary" />
                  </div>
                  <span className="text-sm text-foreground leading-relaxed">{text}</span>
                </li>
              ))}
            </ul>
            <div className="mt-10 p-4 rounded-xl bg-primary/10 border border-primary/20">
              <div className="text-xs text-primary font-semibold mb-1">Free plan includes:</div>
              <div className="text-sm text-foreground">50 products · AI chat widget · Quote management · 1 admin user</div>
              <div className="text-xs text-muted-foreground mt-1.5">90 days or until your first quote — whichever comes first.</div>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
};

export default Signup;
