// Contact — light-mode interactive finale. Mouse-scrubbed background video
// (drag your pointer horizontally to play the film), typewriter headline,
// and multi-select service pills that build a pre-filled email.

const CONTACT_VIDEO =
  "https://d8j0ntlcm91z4.cloudfront.net/user_38xzZboKViGWJOttwIXH07lWA1P/hf_20260601_110537_3a579fa0-7bbc-4d94-9d25-0e816c7840f5.mp4";

const SERVICE_OPTIONS = ["Website", "App", "Product Design", "Social Media", "Music", "Other"];

const CONTACT_EMAIL = "nguyenthaiduybusiness@gmail.com";

// Builds a string slice by slice: { displayed, done }.
function useTypewriter(text, speed = 38, startDelay = 600, start = true) {
  const [displayed, setDisplayed] = React.useState("");
  const [done, setDone] = React.useState(false);

  React.useEffect(() => {
    if (!start) return;
    let interval = null;
    const timeout = setTimeout(() => {
      let i = 0;
      interval = setInterval(() => {
        i += 1;
        setDisplayed(text.slice(0, i));
        if (i >= text.length) {
          clearInterval(interval);
          setDone(true);
        }
      }, speed);
    }, startDelay);
    return () => {
      clearTimeout(timeout);
      if (interval) clearInterval(interval);
    };
  }, [text, speed, startDelay, start]);

  return { displayed, done };
}

function CheckIcon({ className = "w-4 h-4" }) {
  return (
    <svg
      className={className}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="3"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M20 6L9 17l-5-5" />
    </svg>
  );
}

function Contact() {
  const { motion, AnimatePresence } = window.Motion;
  const sectionRef = React.useRef(null);
  const videoRef = React.useRef(null);
  const inViewRef = React.useRef(false);
  const [inView, setInView] = React.useState(false);
  const [services, setServices] = React.useState([]);

  // Start the typewriter (and enable scrubbing) once the section is visible.
  React.useEffect(() => {
    const el = sectionRef.current;
    if (!el) return;
    const observer = new IntersectionObserver(
      ([entry]) => {
        inViewRef.current = entry.isIntersecting;
        if (entry.isIntersecting) setInView(true);
      },
      { threshold: 0.15 }
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, []);

  const { displayed, done } = useTypewriter(
    "i'd love to\nhear from you!",
    38,
    600,
    inView
  );

  // Desktop: native scrubbing — horizontal mouse movement drives playback.
  // Mobile (<1024px): scrubbing disabled, plain autoplay loop instead.
  React.useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    if (window.innerWidth < 1024) {
      video.autoplay = true;
      video.loop = true;
      video.play().catch(() => {});
      return;
    }

    let target = 0;
    let prevX = null;
    let seeking = false;

    const onMove = (e) => {
      if (window.innerWidth < 1024) return;
      if (!inViewRef.current || !video.duration) return;
      if (prevX === null) {
        prevX = e.clientX;
        return;
      }
      const delta = e.clientX - prevX;
      prevX = e.clientX;
      target = Math.max(
        0,
        Math.min(video.duration, target + (delta / window.innerWidth) * 0.8 * video.duration)
      );
      if (!seeking) {
        seeking = true;
        video.currentTime = target;
      }
    };

    // Keep chasing the target frame to frame for smooth tracking.
    const onSeeked = () => {
      if (Math.abs(video.currentTime - target) > 0.01) {
        video.currentTime = target;
      } else {
        seeking = false;
      }
    };

    window.addEventListener("mousemove", onMove);
    video.addEventListener("seeked", onSeeked);
    return () => {
      window.removeEventListener("mousemove", onMove);
      video.removeEventListener("seeked", onSeeked);
    };
  }, []);

  const mailto =
    "mailto:" +
    CONTACT_EMAIL +
    "?subject=" +
    encodeURIComponent("Inquiry: " + services.join(", "));

  return (
    <section
      id="contact"
      ref={sectionRef}
      className="relative bg-white text-neutral-900 font-inter selection:bg-[#EAECE9] selection:text-[#1C2E1E] antialiased overflow-x-hidden flex flex-col lg:block lg:min-h-screen"
    >
      {/* Background video — scrubbed by mouse on desktop */}
      <div className="order-last lg:order-none relative lg:absolute lg:inset-0 lg:z-0 overflow-hidden pointer-events-none w-full aspect-square md:aspect-video lg:aspect-auto lg:h-full bg-neutral-50 lg:bg-transparent">
        <video
          ref={videoRef}
          src={CONTACT_VIDEO}
          muted
          playsInline
          preload="auto"
          className="w-full h-full object-cover object-right lg:object-right-bottom"
        />
      </div>

      {/* Content layer */}
      <div className="relative z-10 flex flex-col order-first lg:order-none w-full bg-white lg:bg-transparent pb-8 lg:pb-0 lg:min-h-screen">
        <div
          id="spade-hero"
          className="w-full max-w-7xl mx-auto px-6 py-12 flex-1 flex flex-col justify-center"
        >
          {/* Typewriter headline */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.6 }}
          >
            <h1 className="text-5xl md:text-6xl lg:text-[76px] font-normal tracking-tight text-black leading-[1.08] mb-8 select-none w-full whitespace-pre-wrap">
              {displayed}
              {!done && (
                <span className="inline-block w-[2px] h-[1.1em] bg-black align-middle ml-[2px] animate-blink" />
              )}
            </h1>
          </motion.div>

          {/* Secondary description */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.6, delay: 0.1 }}
          >
            <p className="text-lg md:text-xl text-[#5A635A] leading-relaxed font-normal mb-14 max-w-2xl">
              Whether you have a question, a project, or just an idea, <br />
              drop me a message and I'll get back to you as soon as I can.
            </p>
          </motion.div>

          {/* Multi-select service pills */}
          <h2 className="text-2xl font-medium tracking-tight mb-2">What sort of service?</h2>
          <p className="opacity-85 text-[#738273] mb-8">Select all that apply</p>

          <div className="flex flex-wrap gap-3 max-w-2xl">
            {SERVICE_OPTIONS.map((opt) => {
              const active = services.includes(opt);
              return (
                <motion.button
                  key={opt}
                  whileTap={{ scale: 0.96 }}
                  onClick={() =>
                    setServices((prev) =>
                      prev.includes(opt) ? prev.filter((s) => s !== opt) : [...prev, opt]
                    )
                  }
                  className={
                    "rounded-full px-5 py-2.5 text-base font-medium flex items-center gap-2 transition-colors duration-200 " +
                    (active
                      ? "bg-[#1C2E1E] text-white shadow-md shadow-emerald-950/5 transform"
                      : "bg-white text-[#1C2E1E] border border-[#F1F3F1] hover:bg-[#F1F3F1]/55")
                  }
                >
                  {active && (
                    <motion.span
                      initial={{ scale: 0, y: -8 }}
                      animate={{ scale: 1, y: 0 }}
                      transition={{ type: "spring", stiffness: 300, damping: 20 }}
                      className="inline-flex"
                    >
                      <CheckIcon />
                    </motion.span>
                  )}
                  {opt}
                </motion.button>
              );
            })}
          </div>

          {/* Contingent feedback banner */}
          <div className="mt-6 max-w-2xl">
            <AnimatePresence mode="wait">
              {services.length === 0 ? (
                <motion.p
                  key="empty"
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 0.5 }}
                  exit={{ opacity: 0 }}
                  className="italic text-xs text-[#5A635A]"
                >
                  Please click to select services above.
                </motion.p>
              ) : (
                <motion.div
                  key="selected"
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: "auto" }}
                  exit={{ opacity: 0, height: 0 }}
                  transition={{ type: "spring", stiffness: 260, damping: 26 }}
                  className="overflow-hidden"
                >
                  <div className="bg-[#FAFBF9] border border-[#F1F3F1] rounded-2xl px-5 py-4 flex items-center justify-between gap-4">
                    <span className="text-sm text-[#1C2E1E]">
                      Ready to inquire about: <strong>{services.join(", ")}</strong>
                    </span>
                    <a
                      href={mailto}
                      className="text-[#4D6D47] uppercase text-xs font-semibold tracking-wide flex items-center gap-1.5 whitespace-nowrap hover:opacity-60 transition-opacity"
                    >
                      Let's Go
                      <span aria-hidden="true">→</span>
                    </a>
                  </div>
                </motion.div>
              )}
            </AnimatePresence>
          </div>

          {/* Direct email fallback */}
          <p className="mt-10 text-xs text-[#738273]">
            Or email me directly:{" "}
            <a href={"mailto:" + CONTACT_EMAIL} className="underline underline-offset-2 hover:opacity-60 transition-opacity">
              {CONTACT_EMAIL}
            </a>{" "}
            · Based in Vienna, Austria (CET)
          </p>
        </div>
      </div>
    </section>
  );
}

window.Contact = Contact;
