"use client";

import React, { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { motion, AnimatePresence, useReducedMotion } from "motion/react";
import {
  Globe,
  Sparkles,
  Bot,
  Check,
  CheckCheck,
  Send,
  ArrowRight,
  Rocket,
} from "lucide-react";
import { SectionHeader } from "@/components/section-header";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

/**
 * QutoChatbotSection (§24–27) — homepage feature for the "Quto Chatbot Agent".
 *
 * Story: the customer's OWN website is the knowledge source.
 *   URL → Quto reads & understands the site → that context powers the agent
 *   → the agent is ready → it chats with the customer's visitors.
 *
 * Pure black/white (tokens only). Motion is subtle (a connector pulse + chat
 * typing-in) and fully reduced-motion safe: under prefers-reduced-motion the
 * "built" state is shown immediately with no looping animation.
 *
 * The page wraps this in <Section><Container>, so no Container here.
 */

const EASE_OUT = [0.22, 1, 0.36, 1] as const;

const KNOWLEDGE = [
  "Products & services",
  "Pricing",
  "FAQs",
  "Opening hours",
  "Delivery & returns",
  "Contact details",
] as const;

type ChatMsg = { from: "visitor" | "agent"; text: string; grounded?: boolean };

// The first exchange animates in on build; the final agent reply arrives after
// a short "typing" beat to sell the live-conversation feel.
const CHAT: ChatMsg[] = [
  { from: "visitor", text: "Do you deliver same-day in my area?" },
  {
    from: "agent",
    text: "Yes — same-day within the city on orders placed before 4pm. Want me to check your postcode?",
    grounded: true,
  },
  { from: "visitor", text: "And what are your Sunday hours?" },
];

const FINAL_AGENT: ChatMsg = {
  from: "agent",
  text: "We're open 10am–4pm on Sundays. Anything else I can help with?",
  grounded: true,
};

export function QutoChatbotSection({ className }: { className?: string }) {
  const reduce = useReducedMotion();

  const [url, setUrl] = useState("yourbusiness.com");
  const [built, setBuilt] = useState(false);
  const [buildKey, setBuildKey] = useState(0);

  // Chat reveal state (final agent reply gated behind a typing indicator).
  const [typing, setTyping] = useState(false);
  const [showFinal, setShowFinal] = useState(false);

  const rootRef = useRef<HTMLDivElement>(null);

  // Reduced motion: land in the finished state with no animation.
  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect -- intentional: reduced-motion shortcut lands the section in its finished state on mount
    if (reduce) setBuilt(true);
  }, [reduce]);

  // Auto-run the build when the section scrolls into view, so visitors who
  // never click still see the full story. Guarded if IO is unavailable.
  useEffect(() => {
    if (typeof IntersectionObserver === "undefined") {
      // eslint-disable-next-line react-hooks/set-state-in-effect -- intentional: fallback reveal when IntersectionObserver is unavailable (SSR/old browsers)
      setBuilt(true);
      return;
    }
    const el = rootRef.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        if (entries.some((e) => e.isIntersecting)) {
          setBuilt(true);
          io.disconnect();
        }
      },
      { rootMargin: "0px 0px -15% 0px" },
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);

  // Drive the chat's typing → final-reply sequence off the build state.
  useEffect(() => {
    if (!built) {
      // eslint-disable-next-line react-hooks/set-state-in-effect -- intentional: clears the chat reveal when build state resets
      setTyping(false);
      setShowFinal(false);
      return;
    }
    if (reduce) {
      setTyping(false);
      setShowFinal(true);
      return;
    }
    setShowFinal(false);
    const start = window.setTimeout(() => setTyping(true), 1100);
    const finish = window.setTimeout(() => {
      setTyping(false);
      setShowFinal(true);
    }, 2600);
    return () => {
      window.clearTimeout(start);
      window.clearTimeout(finish);
    };
  }, [built, buildKey, reduce]);

  // "Build my agent" — demo only. Replays the build animation on each click.
  const handleBuild = () => {
    if (reduce) {
      setBuilt(true);
      return;
    }
    setBuilt(false);
    requestAnimationFrame(() => {
      setBuilt(true);
      setBuildKey((k) => k + 1);
    });
  };

  return (
    <div
      ref={rootRef}
      className={cn("mx-auto w-full max-w-6xl", className)}
    >
      <SectionHeader
        align="center"
        eyebrow="Introducing Quto Talk"
        title={
          <>
            Meet <span className="font-extrabold text-gradient-brand">Quto Talk</span> — an AI chatbot that
            <br className="hidden sm:block" /> understands your website.
          </>
        }
        lead="Give Quto Talk the website you already have. It reads and understands your pages, then answers your visitors — grounded in your own content, not generic guesses."
      />

      {/* Demo card: left = build pipeline, right = live chat result. */}
      <div className="mt-12 overflow-hidden rounded-3xl border border-border bg-card shadow-sm">
        <div className="grid gap-8 p-6 sm:p-8 lg:grid-cols-2 lg:gap-10">
          {/* ── Build pipeline (vertical timeline) ───────────────────── */}
          <div className="flex flex-col">
            {/* Stage 1 — Share your website */}
            <Stage
              index={1}
              icon={<Globe className="size-5 text-[#4FDAF1]" strokeWidth={1.5} />}
              title="Share your website"
              desc="Point Quto at the site you already have."
              connect={!reduce && built}
              accentColor="cyan"
            >
              <BrowserMock
                url={url}
                onUrlChange={setUrl}
                onBuild={handleBuild}
                scanning={!reduce && built}
                buildKey={buildKey}
              />
            </Stage>

            {/* Stage 2 — Quto reads & understands it */}
            <Stage
              index={2}
              icon={<Sparkles className="size-5 text-[#F79C09]" strokeWidth={1.5} />}
              title="Quto reads & understands it"
              desc="It studies your pages and builds context from your own content."
              connect={!reduce && built}
              accentColor="gold"
            >
              <motion.ul
                key={`chips-${buildKey}`}
                className="flex flex-wrap gap-2"
                initial={reduce ? false : "hidden"}
                animate={reduce ? false : built ? "show" : "hidden"}
                variants={{
                  hidden: {},
                  show: { transition: { staggerChildren: 0.07 } },
                }}
              >
                {KNOWLEDGE.map((chip) => (
                  <motion.li
                    key={chip}
                    variants={{
                      hidden: { opacity: 0, y: 6 },
                      show: {
                        opacity: 1,
                        y: 0,
                        transition: { duration: 0.35, ease: EASE_OUT },
                      },
                    }}
                    className={cn(
                      "inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium transition-colors",
                      built
                        ? "border-[#4FDAF1]/40 bg-[#4FDAF1]/10 text-foreground font-semibold"
                        : "border-dashed border-border bg-foreground/[0.03] text-muted-foreground",
                    )}
                  >
                    <Check
                      className={cn(
                        "size-3 transition-colors",
                        built ? "text-[#4FDAF1] opacity-100" : "opacity-40",
                      )}
                      strokeWidth={2}
                      aria-hidden
                    />
                    {chip}
                  </motion.li>
                ))}
              </motion.ul>
            </Stage>

            {/* Stage 3 — Agent ready */}
            <Stage
              index={3}
              icon={<Bot className="size-5 text-[#E26B0B]" strokeWidth={1.5} />}
              title="Your chatbot agent is ready"
              desc="Grounded in your website, it answers visitors in your voice."
              connect={false}
              accentColor="orange"
            >
              <div className="flex items-center gap-3 rounded-xl border border-border bg-background px-4 py-3">
                <span className="flex size-9 shrink-0 items-center justify-center rounded-full bg-gradient-brand text-white [&_svg]:text-white shadow-xs">
                  <Bot className="size-5" strokeWidth={1.5} aria-hidden />
                </span>
                <div className="min-w-0 flex-1">
                  <p className="truncate text-sm font-medium text-foreground">
                    Quto Talk
                  </p>
                  <p className="truncate text-xs text-muted-foreground">
                    Built from {url || "your website"}
                  </p>
                </div>
                <span
                  className={cn(
                    "inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-semibold transition-colors",
                    built
                      ? "border-[#4FDAF1]/40 bg-[#4FDAF1]/10 text-[#020202] dark:text-[#4FDAF1]"
                      : "border-border bg-foreground/[0.03] text-muted-foreground",
                  )}
                >
                  <span className="relative flex size-2">
                    {built && !reduce && (
                      <span className="absolute inline-flex size-full animate-ping rounded-full bg-[#4FDAF1]/60 motion-reduce:hidden" />
                    )}
                    <span
                      className={cn(
                        "relative inline-flex size-2 rounded-full",
                        built ? "bg-[#4FDAF1]" : "bg-muted-foreground/50",
                      )}
                    />
                  </span>
                  {built ? "Ready" : "Idle"}
                </span>
              </div>
            </Stage>
          </div>

          {/* ── Right: Step 4 + live chat result (§35–§37) ───────────── */}
          <div className="flex flex-col gap-6">
            {/* Stage 4 — implementation / go-live */}
            <div className="flex gap-4">
              <span className="relative flex size-10 shrink-0 items-center justify-center rounded-xl bg-gradient-brand text-white [&_svg]:text-white shadow-sm glow-brand">
                <Rocket className="size-5" strokeWidth={1.5} aria-hidden />
                <span className="absolute -right-1.5 -top-1.5 flex size-5 items-center justify-center rounded-full bg-[#020202] text-[10px] font-bold text-[#4FDAF1] border border-[#4FDAF1]/40">
                  4
                </span>
              </span>
              <div className="flex-1">
                <p className="text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground">
                  Step 4
                </p>
                <h3 className="mt-0.5 font-display text-base font-medium text-foreground">
                  Quto Talk goes live on your website
                </h3>
                <p className="mt-1 max-w-sm text-sm text-muted-foreground">
                  We implement Quto Talk and take it live — ready to answer your
                  visitors, right on your site.
                </p>
              </div>
            </div>

            {/* Live chat result */}
            <div className="flex w-full flex-col overflow-hidden rounded-2xl border border-border bg-background">
              {/* Chat header */}
              <div className="flex items-center gap-3 border-b border-border bg-secondary/50 px-4 py-3">
                <span className="flex size-8 shrink-0 items-center justify-center rounded-full bg-[#4FDAF1]/15 text-[#4FDAF1]">
                  <Bot className="size-4.5" strokeWidth={1.5} aria-hidden />
                </span>
                <div className="min-w-0 flex-1">
                  <p className="truncate text-sm font-medium text-foreground">
                    Quto Talk
                  </p>
                  <p className="flex items-center gap-1.5 text-xs text-muted-foreground">
                    <span className="size-1.5 rounded-full bg-[#4FDAF1] animate-pulse" />
                    Online · answering as your business
                  </p>
                </div>
              </div>

              {/* Messages */}
              <motion.div
                key={`chat-${buildKey}`}
                className="flex flex-1 flex-col gap-3 bg-muted/30 p-4 sm:min-h-[280px]"
                initial={reduce ? false : "hidden"}
                animate={reduce ? false : built ? "show" : "hidden"}
                variants={{
                  hidden: {},
                  show: { transition: { staggerChildren: 0.18, delayChildren: 0.15 } },
                }}
              >
                {CHAT.map((m, i) => (
                  <ChatBubble key={i} msg={m} reduce={!!reduce} />
                ))}

                {/* Final agent reply arrives after a typing beat. */}
                <AnimatePresence initial={false} mode="wait">
                  {typing ? (
                    <motion.div
                      key="typing"
                      initial={{ opacity: 0, y: 6 }}
                      animate={{ opacity: 1, y: 0 }}
                      exit={{ opacity: 0 }}
                      transition={{ duration: 0.25, ease: EASE_OUT }}
                      className="flex justify-start"
                    >
                      <div className="flex items-center gap-1.5 rounded-2xl rounded-bl-sm border border-border bg-card px-4 py-3">
                        {[0, 1, 2].map((d) => (
                          <motion.span
                            key={d}
                            className="size-1.5 rounded-full bg-muted-foreground"
                            animate={{ opacity: [0.3, 1, 0.3] }}
                            transition={{
                              duration: 0.9,
                              repeat: Infinity,
                              ease: "easeInOut",
                              delay: d * 0.18,
                            }}
                          />
                        ))}
                      </div>
                    </motion.div>
                  ) : showFinal ? (
                    <ChatBubble key="final" msg={FINAL_AGENT} reduce={!!reduce} />
                  ) : null}
                </AnimatePresence>
              </motion.div>

              {/* Composer (decorative) */}
              <div className="flex items-center gap-2 border-t border-border bg-background px-3 py-2.5">
                <div className="flex flex-1 items-center rounded-full border border-border bg-muted/40 px-3.5 py-2 text-xs text-muted-foreground">
                  Ask about your business…
                </div>
                <span
                  aria-hidden
                  className="flex size-9 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground transition-colors hover:bg-[#1F1C1A]"
                >
                  <Send className="size-4 text-[#4FDAF1]" strokeWidth={1.75} />
                </span>
              </div>
            </div>
          </div>
        </div>

        {/* Honest guardrail note */}
        <div className="border-t border-border bg-secondary/30 px-6 py-4 sm:px-8">
          <p className="flex items-start gap-2 text-xs leading-relaxed text-muted-foreground">
            <CheckCheck
              className="mt-0.5 size-4 shrink-0 text-[#4FDAF1]"
              strokeWidth={2}
              aria-hidden
            />
            Quto answers from the content on your website. When something isn&apos;t
            covered, it says so or hands off to your team — no guessing, no
            made-up facts.
          </p>
        </div>
      </div>

      {/* CTA */}
      <div className="mt-10 flex flex-col items-center gap-3 text-center">
        <Button variant="accent" size="pill-lg" asChild>
          <Link href="/contact">
            Get your chatbot agent
            <ArrowRight aria-hidden />
          </Link>
        </Button>
        <p className="text-sm text-muted-foreground">
          No code to write — share your URL and we handle the rest.
        </p>
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────────── */

/**
 * A single vertical-timeline stage: numbered node + title/desc, with an
 * optional pulsing connector running down to the next stage.
 */
function Stage({
  index,
  icon,
  title,
  desc,
  connect,
  accentColor = "cyan",
  children,
}: {
  index: number;
  icon: React.ReactNode;
  title: string;
  desc: string;
  connect: boolean;
  accentColor?: "cyan" | "gold" | "orange";
  children: React.ReactNode;
}) {
  const badgeColors = {
    cyan: "bg-[#4FDAF1] text-[#020202]",
    gold: "bg-[#F79C09] text-[#020202]",
    orange: "bg-[#E26B0B] text-white",
  };

  const nodeBorderColors = {
    cyan: "border-[#4FDAF1]/30 shadow-[0_0_12px_-2px_rgba(79,218,241,0.25)]",
    gold: "border-[#F79C09]/30 shadow-[0_0_12px_-2px_rgba(247,156,9,0.25)]",
    orange: "border-[#E26B0B]/30 shadow-[0_0_12px_-2px_rgba(226,107,11,0.25)]",
  };

  return (
    <div className="flex gap-4">
      {/* Gutter: node + connector */}
      <div className="flex flex-col items-center">
        <span className={cn("relative flex size-10 shrink-0 items-center justify-center rounded-xl border bg-background text-foreground transition-shadow", nodeBorderColors[accentColor])}>
          {icon}
          <span className={cn("absolute -right-1.5 -top-1.5 flex size-5 items-center justify-center rounded-full text-[10px] font-bold shadow-xs", badgeColors[accentColor])}>
            {index}
          </span>
        </span>
        <div className="relative mt-2 w-0.5 flex-1 bg-gradient-to-b from-[#4FDAF1]/40 via-[#F79C09]/40 to-[#E26B0B]/40">
          {connect && (
            <motion.span
              aria-hidden
              className="absolute left-1/2 size-2 -translate-x-1/2 rounded-full bg-[#4FDAF1] shadow-[0_0_10px_#4FDAF1] motion-reduce:hidden"
              initial={{ top: "0%", opacity: 0 }}
              animate={{ top: ["0%", "100%"], opacity: [0, 1, 1, 0] }}
              transition={{
                duration: 1.8,
                repeat: Infinity,
                ease: "easeInOut",
              }}
            />
          )}
        </div>
      </div>

      {/* Content */}
      <div className="flex-1 pb-8">
        <p className="text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground">
          Step {index}
        </p>
        <h3 className="mt-0.5 font-display text-base font-bold text-foreground">
          {title}
        </h3>
        <p className="mt-1 mb-3 max-w-sm text-sm text-muted-foreground">
          {desc}
        </p>
        {children}
      </div>
    </div>
  );
}

/**
 * A compact, monochrome browser mock with an editable-looking URL field and a
 * non-functional "Build my agent" button (demo only). An optional scan sweep
 * runs across the page skeleton after a build.
 */
function BrowserMock({
  url,
  onUrlChange,
  onBuild,
  scanning,
  buildKey,
}: {
  url: string;
  onUrlChange: (v: string) => void;
  onBuild: () => void;
  scanning: boolean;
  buildKey: number;
}) {
  return (
    <div className="overflow-hidden rounded-xl border border-border bg-background shadow-sm">
      {/* Chrome bar */}
      <div className="flex items-center gap-2 border-b border-border bg-secondary/60 px-3 py-2">
        <div className="hidden gap-1.5 sm:flex">
          <span className="size-2.5 rounded-full bg-foreground/15" />
          <span className="size-2.5 rounded-full bg-foreground/15" />
          <span className="size-2.5 rounded-full bg-foreground/15" />
        </div>
        <div className="flex min-w-0 flex-1 items-center gap-2 rounded-md border border-border bg-background px-2 py-1">
          <Globe
            className="size-3.5 shrink-0 text-muted-foreground"
            strokeWidth={1.5}
            aria-hidden
          />
          <input
            value={url}
            onChange={(e) => onUrlChange(e.target.value)}
            spellCheck={false}
            aria-label="Your website URL"
            placeholder="yourbusiness.com"
            className="min-w-0 flex-1 bg-transparent text-[13px] text-foreground outline-none placeholder:text-muted-foreground"
          />
        </div>
        <button
          type="button"
          onClick={onBuild}
          className="shrink-0 rounded-md bg-gradient-brand px-3 py-1 text-[11px] font-bold text-white shadow-xs glow-brand transition-opacity hover:opacity-95 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background active:translate-y-px motion-reduce:transition-none motion-reduce:active:translate-y-0"
        >
          Build my agent
        </button>
      </div>

      {/* Page skeleton with scan sweep */}
      <div className="relative overflow-hidden px-3 py-3">
        <div className="flex items-center gap-2">
          <span className="size-6 rounded-md bg-foreground/10" />
          <span className="h-2 w-20 rounded-full bg-foreground/10" />
          <span className="ml-auto h-2 w-10 rounded-full bg-foreground/[0.06]" />
        </div>
        <div className="mt-3 space-y-1.5">
          <span className="block h-2 w-3/4 rounded-full bg-foreground/10" />
          <span className="block h-2 w-full rounded-full bg-foreground/[0.07]" />
          <span className="block h-2 w-2/3 rounded-full bg-foreground/[0.07]" />
        </div>
        <div className="mt-3 grid grid-cols-3 gap-1.5">
          <span className="h-8 rounded-md bg-foreground/[0.06]" />
          <span className="h-8 rounded-md bg-foreground/[0.06]" />
          <span className="h-8 rounded-md bg-foreground/[0.06]" />
        </div>

        {scanning && (
          <motion.span
            key={`scan-${buildKey}`}
            aria-hidden
            className="pointer-events-none absolute inset-x-0 h-8 bg-linear-to-b from-transparent via-foreground/15 to-transparent motion-reduce:hidden"
            initial={{ top: "-2rem", opacity: 0 }}
            animate={{ top: ["-2rem", "100%"], opacity: [0, 1, 1, 0] }}
            transition={{ duration: 1.4, ease: "easeInOut" }}
          />
        )}
      </div>
    </div>
  );
}

/** A single chat bubble — visitor (right, primary) or agent (left, card). */
function ChatBubble({ msg, reduce }: { msg: ChatMsg; reduce: boolean }) {
  const isVisitor = msg.from === "visitor";
  return (
    <motion.div
      variants={
        reduce
          ? undefined
          : {
              hidden: { opacity: 0, y: 8 },
              show: {
                opacity: 1,
                y: 0,
                transition: { duration: 0.4, ease: EASE_OUT },
              },
            }
      }
      className={cn("flex", isVisitor ? "justify-end" : "justify-start")}
    >
      <div
        className={cn(
          "max-w-[85%] rounded-2xl px-3.5 py-2.5 text-sm leading-relaxed",
          isVisitor
            ? "rounded-br-sm bg-primary text-primary-foreground"
            : "rounded-bl-sm border border-border bg-card text-foreground",
        )}
      >
        <p>{msg.text}</p>
        {msg.grounded && (
          <p className="mt-1.5 flex items-center gap-1 text-[11px] text-muted-foreground">
            <Sparkles className="size-3 text-[#4FDAF1]" strokeWidth={1.5} aria-hidden />
            Answered from your website
          </p>
        )}
      </div>
    </motion.div>
  );
}
