"use client";

import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
import {
  type CSSProperties,
  type FormEvent,
  type KeyboardEvent,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";

/**
 * ChatHiroInteractiveHero
 * A self-contained, selectable-text recreation of the supplied layered illustration.
 * Tailwind CSS + framer-motion. No icon, font or image dependency.
 *
 * This is a functional front-end demo, not a live chat service.
 * Supply onSendMessage to connect a real API; it may return a reply string.
 */

type Role = "bot" | "visitor" | "agent";

type ChatMessage = {
  id: number;
  role: Role;
  text: string;
  time: string;
};

export type ChatHiroInteractiveHeroProps = {
  /** Optional controlled color. Pair with onColorChange. */
  color?: string;
  /** Starting color when using the component without controlled state. */
  defaultColor?: string;
  onColorChange?: (hex: string) => void;
  /** Optional integration point. Return a string to display an agent/bot reply. */
  onSendMessage?: (
    message: string,
  ) => string | undefined | Promise<string | undefined>;
  brandName?: string;
  title?: string;
  subtitle?: string;
  showColorControls?: boolean;
  className?: string;
};

const PRESETS = [
  { name: "Violet", value: "#7C3AED" },
  { name: "Green", value: "#159914" },
  { name: "Red", value: "#B91C1C" },
  { name: "Gold", value: "#F5B400" },
];

const INITIAL_MESSAGES: ChatMessage[] = [
  {
    id: 1,
    role: "bot",
    text: "Hi! 👋 How can I help today—are you looking for Live Chat, an AI Agent, or AI Automation for a specific workflow?",
    time: "4:19 pm",
  },
  {
    id: 2,
    role: "visitor",
    text: "I want to see your pricing.",
    time: "4:19 pm",
  },
  {
    id: 3,
    role: "agent",
    text: "Hi, this is Sabbir. I'm here to assist you. Please share your query with us.",
    time: "4:19 pm",
  },
];

function validHex(value: string) {
  if (/^#[0-9a-f]{6}$/i.test(value)) return value.toUpperCase();
  if (/^#[0-9a-f]{3}$/i.test(value))
    return `#${value
      .slice(1)
      .split("")
      .map((c) => c + c)
      .join("")}`.toUpperCase();
  return "#7C3AED";
}

function rgb(hex: string) {
  const h = validHex(hex).slice(1);
  return {
    r: parseInt(h.slice(0, 2), 16),
    g: parseInt(h.slice(2, 4), 16),
    b: parseInt(h.slice(4, 6), 16),
  };
}

function rgba(hex: string, alpha: number) {
  const { r, g, b } = rgb(hex);
  return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}

function mixWhite(hex: string, amount: number) {
  const { r, g, b } = rgb(hex);
  const blend = (v: number) => Math.round(v + (255 - v) * amount);
  return `rgb(${blend(r)}, ${blend(g)}, ${blend(b)})`;
}

function inkFor(hex: string) {
  const { r, g, b } = rgb(hex);
  const luminance = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
  return luminance > 0.66 ? "#21182D" : "#FFFFFF";
}

function demoReply(message: string) {
  const lower = message.toLowerCase();
  if (
    lower.includes("pric") ||
    lower.includes("cost") ||
    lower.includes("plan")
  ) {
    return "Thanks! For current plans and pricing, connect this demo to your real pricing page or support API.";
  }
  if (
    lower.includes("human") ||
    lower.includes("agent") ||
    lower.includes("support")
  ) {
    return "You can connect this component to your support team using the onSendMessage prop.";
  }
  return "Thanks for your message! This is a demo response. Connect onSendMessage for real conversations.";
}

function RobotIcon({
  color = "currentColor",
  size = 24,
}: {
  color?: string;
  size?: number;
}) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 32 32"
      fill="none"
      aria-hidden="true"
    >
      <path
        d="M16 4V7M12.8 4H19.2"
        stroke={color}
        strokeWidth="2"
        strokeLinecap="round"
      />
      <rect
        x="4"
        y="8"
        width="24"
        height="18"
        rx="7"
        fill="white"
        stroke={color}
        strokeWidth="2.2"
      />
      <circle cx="12" cy="16" r="2.1" fill={color} />
      <circle cx="20" cy="16" r="2.1" fill={color} />
      <path
        d="M12 21C14.5 23 17.5 23 20 21M10 26L7 29V24"
        stroke={color}
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function PaletteIcon({
  color = "currentColor",
  size = 27,
}: {
  color?: string;
  size?: number;
}) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 32 32"
      fill="none"
      aria-hidden="true"
    >
      <path
        d="M16 3.5C8.8 3.5 3.5 8.6 3.5 15.4 3.5 22.5 9.1 28.5 16.5 28.5H18.3C21.5 28.5 22 24.2 19.6 23.3C18.2 22.7 18.2 20.8 19.6 20.2C21.2 19.6 23.7 22 26.2 20.8C28.1 19.9 28.5 17.2 28.5 15.3C28.5 8.6 23.1 3.5 16 3.5Z"
        stroke={color}
        strokeWidth="2.5"
        strokeLinejoin="round"
      />
      <circle cx="9.8" cy="14" r="2" fill={color} />
      <circle cx="14.3" cy="8.9" r="2" fill={color} />
      <circle cx="21" cy="10.4" r="2" fill={color} />
      <circle cx="24" cy="16.2" r="2" fill={color} />
    </svg>
  );
}

function ArrowIcon({ size = 19 }: { size?: number }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      aria-hidden="true"
    >
      <path
        d="M4 12H19M13 6L19 12L13 18"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function SendIcon() {
  return (
    <svg
      width="18"
      height="18"
      viewBox="0 0 24 24"
      fill="none"
      aria-hidden="true"
    >
      <path
        d="M21 3L10.5 13.5M21 3L14.5 21L10.5 13.5M21 3L3 9.5L10.5 13.5"
        stroke="currentColor"
        strokeWidth="1.9"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function ChevronLeftIcon({ size = 20 }: { size?: number }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      aria-hidden="true"
    >
      <path
        d="M15 6L9 12L15 18"
        stroke="currentColor"
        strokeWidth="2.2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function MoreIcon({ size = 20 }: { size?: number }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="currentColor"
      aria-hidden="true"
    >
      <circle cx="12" cy="5" r="1.7" />
      <circle cx="12" cy="12" r="1.7" />
      <circle cx="12" cy="19" r="1.7" />
    </svg>
  );
}

function PaperclipIcon({ size = 18 }: { size?: number }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      aria-hidden="true"
    >
      <path
        d="M21.44 11.05l-8.49 8.49a5.25 5.25 0 01-7.43-7.43l8.49-8.49a3.5 3.5 0 014.95 4.95l-8.49 8.49a1.75 1.75 0 01-2.47-2.47l7.78-7.78"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function SmileIcon({ size = 18 }: { size?: number }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      aria-hidden="true"
    >
      <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="1.8" />
      <path
        d="M8.5 10.2h.01M15.5 10.2h.01M8.2 14.2c1.1 1.3 2.5 1.9 3.8 1.9s2.7-.6 3.8-1.9"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function MicIcon({ size = 18 }: { size?: number }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      aria-hidden="true"
    >
      <rect
        x="9"
        y="3"
        width="6"
        height="11"
        rx="3"
        stroke="currentColor"
        strokeWidth="1.8"
      />
      <path
        d="M5.5 11a6.5 6.5 0 0013 0M12 17.5V21"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
      />
    </svg>
  );
}

const PERSON_STYLES = [
  "from-emerald-300 to-teal-600",
  "from-sky-300 to-indigo-600",
  "from-orange-300 to-rose-500",
  "from-fuchsia-300 to-purple-600",
  "from-amber-200 to-orange-600",
  "from-cyan-300 to-blue-600",
  "from-pink-300 to-red-600",
  "from-teal-300 to-emerald-700",
];
const PERSON_LABELS = ["S", "A", "M", "J", "L", "N", "R", "D"];

function Avatar({ index, size = 32 }: { index: number; size?: number }) {
  return (
    <div
      className={`flex shrink-0 items-center justify-center rounded-full border-2 border-white bg-linear-to-br font-bold text-white shadow-md ${PERSON_STYLES[index % PERSON_STYLES.length]}`}
      style={{ height: size, width: size, fontSize: size * 0.43 }}
      aria-label={`Team member ${index + 1}`}
      role="img"
    >
      {PERSON_LABELS[index % PERSON_LABELS.length]}
    </div>
  );
}

export default function ChatHiroInteractiveHero({
  color,
  defaultColor = "#7C3AED",
  onColorChange,
  onSendMessage,
  brandName = "ChatHiro",
  title = "Hi there! 👋 How can we help you today?",
  subtitle = "Our support team is here to assist you every day.",
  showColorControls = true,
  className = "",
}: ChatHiroInteractiveHeroProps) {
  const reduceMotion = Boolean(useReducedMotion());
  const [localColor, setLocalColor] = useState(validHex(defaultColor));
  const [pickerOpen, setPickerOpen] = useState(false);
  const [chatOpen, setChatOpen] = useState(true);
  const [teamSize, setTeamSize] = useState(5);
  const [messages, setMessages] = useState<ChatMessage[]>(INITIAL_MESSAGES);
  const [input, setInput] = useState("");
  const [typing, setTyping] = useState(false);
  const [isCompact, setIsCompact] = useState(true);
  const nextId = useRef(4);
  const inputRef = useRef<HTMLInputElement>(null);
  const messagesRef = useRef<HTMLDivElement>(null);
  const alive = useRef(true);
  const demoTimers = useRef<Array<ReturnType<typeof setTimeout>>>([]);

  const activeColor = validHex(color ?? localColor);
  const foreground = inkFor(activeColor);
  const light = useMemo(() => mixWhite(activeColor, 0.87), [activeColor]);
  const medium = useMemo(() => mixWhite(activeColor, 0.7), [activeColor]);

  const setTheme = (hex: string) => {
    const clean = validHex(hex);
    if (color === undefined) setLocalColor(clean);
    onColorChange?.(clean);
  };

  useEffect(() => {
    const media = window.matchMedia("(max-width: 1023px)");
    const sync = () => setIsCompact(media.matches);
    sync();
    media.addEventListener("change", sync);
    return () => media.removeEventListener("change", sync);
  }, []);

  useEffect(() => {
    alive.current = true;
    return () => {
      alive.current = false;
      demoTimers.current.forEach(clearTimeout);
      demoTimers.current = [];
    };
  }, []);

  // biome-ignore lint/correctness/useExhaustiveDependencies: scroll when messages/typing change
  useEffect(() => {
    if (chatOpen && messagesRef.current) {
      messagesRef.current.scrollTop = messagesRef.current.scrollHeight;
    }
  }, [messages, typing, chatOpen]);

  function openChat() {
    setChatOpen(true);
    // Delay focus to the next paint for the AnimatePresence mount.
    demoTimers.current.push(setTimeout(() => inputRef.current?.focus(), 180));
  }

  function addMessage(role: Role, text: string) {
    setMessages((previous) => [
      ...previous,
      {
        id: nextId.current++,
        role,
        text,
        time: new Date().toLocaleTimeString([], {
          hour: "numeric",
          minute: "2-digit",
        }),
      },
    ]);
  }

  async function sendMessage(event?: FormEvent<HTMLFormElement>) {
    event?.preventDefault();
    const text = input.trim();
    if (!text || typing) return;
    setInput("");
    addMessage("visitor", text);
    setTyping(true);

    try {
      if (!onSendMessage) {
        // A visible LOCAL demo reply; no external request is made.
        const timer = setTimeout(() => {
          if (alive.current) {
            addMessage("agent", demoReply(text));
            setTyping(false);
          }
        }, 900);
        demoTimers.current.push(timer);
      } else {
        const response = await onSendMessage(text);
        if (alive.current) {
          if (typeof response === "string" && response.trim())
            addMessage("agent", response.trim());
          setTyping(false);
        }
      }
    } catch {
      if (alive.current) {
        addMessage(
          "bot",
          "Sorry, the message could not be sent. Please try again.",
        );
        setTyping(false);
      }
    }
  }

  function onInputKeyDown(event: KeyboardEvent<HTMLInputElement>) {
    if (event.key === "Escape") inputRef.current?.blur();
  }

  const themeStyles = {
    "--ch-accent": activeColor,
    "--ch-pale": light,
    "--ch-medium": medium,
  } as CSSProperties;

  return (
    <section
      aria-label="Interactive support chat preview"
      className={`relative isolate mx-auto w-full overflow-hidden rounded-2xl text-[#17152C] sm:rounded-3xl lg:rounded-[36px] ${className}`}
      style={themeStyles}
    >
      {/* The scene stays responsive without relying on an external SVG/image. */}
      <div
        className="pointer-events-none absolute inset-0 overflow-hidden"
        aria-hidden="true"
      >
        <div
          className="absolute -left-24 top-40 h-90 w-90 rounded-full blur-[100px]"
          style={{ backgroundColor: rgba(activeColor, 0.095) }}
        />
        <div
          className="absolute -right-24 bottom-0 h-85 w-85 rounded-full blur-[110px]"
          style={{ backgroundColor: rgba(activeColor, 0.08) }}
        />
        <div className="absolute inset-0 opacity-[0.18] bg-[radial-gradient(#b2aabc_0.7px,transparent_0.7px)] bg-size-[22px_22px]" />
      </div>

      {/* Compact: stacked upright cards. Desktop: tilted cluster like the mock. */}
      <div className="relative mx-auto flex w-full max-w-250 flex-col gap-4 px-3 py-4 sm:gap-5 sm:px-5 sm:py-6 lg:block lg:h-200 lg:gap-0 lg:p-0">
        {/* Welcome card — upright on compact, tilted behind the chat on desktop. */}
        <motion.article
          className="relative z-10 mx-auto flex w-full max-w-md flex-col overflow-hidden rounded-[28px] border border-white/15 p-5 shadow-[0_26px_55px_rgba(42,28,86,.22)] sm:p-6 lg:absolute lg:top-[22%] lg:left-[12%] lg:mx-0 lg:h-115 lg:w-80 lg:max-w-none lg:p-6.5"
          style={{
            backgroundColor: activeColor,
            color: foreground,
            transformOrigin: "50% 50%",
          }}
          initial={reduceMotion ? false : { opacity: 0, y: 28 }}
          animate={{ opacity: 1, x: 0, y: 0, rotate: isCompact ? 0 : -24 }}
          whileHover={
            reduceMotion || isCompact ? undefined : { rotate: -18, scale: 1.02 }
          }
          transition={{ type: "spring", stiffness: 140, damping: 18 }}
        >
          <div
            className="absolute -right-20 -top-20 h-64 w-64 rounded-full bg-white/11"
            aria-hidden="true"
          />
          <div
            className="absolute -bottom-20 -left-20 h-60 w-60 rounded-full bg-black/10"
            aria-hidden="true"
          />
          <div className="relative flex items-center gap-2.5">
            <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-white shadow-sm">
              <RobotIcon color={activeColor} size={27} />
            </div>
            <span className="text-[21px] font-extrabold tracking-[-.7px]">
              {brandName}
            </span>
            <span
              role="img"
              className="ml-auto h-2.5 w-2.5 rounded-full bg-[#78F7B2] ring-4 ring-white/15"
              aria-label="Available"
            />
          </div>

          <div className="relative mt-6 flex flex-1 flex-col rounded-[25px] bg-white/12 px-4 pt-4 sm:mt-8 sm:px-5 sm:pt-6">
            <p className="text-[24px] font-extrabold leading-[1.16] tracking-tight sm:text-[30px]">
              {title}
            </p>
            <div className="mt-4 flex items-center gap-1.5 sm:mt-6">
              {Array.from({ length: teamSize }, (_, index) => (
                <motion.div
                  key={PERSON_LABELS[index]}
                  className={index ? "-ml-3" : ""}
                  initial={reduceMotion ? false : { opacity: 0, scale: 0 }}
                  animate={{ opacity: 1, scale: 1 }}
                  transition={{ type: "spring", delay: index * 0.055 }}
                >
                  <Avatar index={index} size={34} />
                </motion.div>
              ))}
              <button
                type="button"
                onClick={() =>
                  setTeamSize((size) =>
                    Math.min(size + 1, PERSON_LABELS.length),
                  )
                }
                disabled={teamSize >= PERSON_LABELS.length}
                aria-label="Add a team avatar to the preview"
                className="z-10 -ml-2 flex h-8.5 w-8.5 items-center justify-center rounded-full border-2 border-white/70 bg-white text-xl font-light text-[#201937] shadow-sm transition-transform hover:scale-110 disabled:cursor-default disabled:opacity-60"
              >
                +
              </button>
            </div>
            <p className="mt-3 text-xs leading-5 opacity-90 sm:mt-4 sm:text-[14px]">
              {subtitle}
            </p>
            <button
              type="button"
              onClick={openChat}
              className="mt-5 mb-4 inline-flex w-fit items-center gap-2 rounded-full bg-white px-4 py-2.5 text-[13px] font-bold shadow-md outline-none transition hover:shadow-lg focus-visible:ring-4 focus-visible:ring-white/50 sm:mt-auto sm:mb-5 sm:px-5 sm:py-3"
              style={{ color: activeColor }}
            >
              Start conversation <ArrowIcon size={15} />
            </button>
          </div>
        </motion.article>

        {/* Color swatches: horizontal row on compact, tilted column on desktop. */}
        {showColorControls && (
          <motion.div
            className="relative z-20 order-first mr-auto flex flex-row gap-2 rounded-[20px] bg-white/80 p-2 shadow-[0_12px_38px_rgba(25,18,54,.13)] ring-1 ring-white/80 backdrop-blur-md lg:absolute lg:top-[48%] lg:left-[5%] lg:order-0 lg:mr-0 lg:flex-col"
            initial={reduceMotion ? false : { opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0, rotate: isCompact ? 0 : -24 }}
            transition={{ delay: 0.25 }}
            role="group"
            aria-label="Choose preview theme color"
          >
            {PRESETS.map((preset) => (
              <motion.button
                key={preset.value}
                type="button"
                title={`${preset.name} theme`}
                aria-label={`Use ${preset.name} color`}
                aria-pressed={activeColor === preset.value}
                onClick={() => setTheme(preset.value)}
                className="relative h-9 w-9 rounded-xl border-[3px] border-white shadow-sm outline-none focus-visible:ring-2 focus-visible:ring-offset-2 sm:h-11 sm:w-11"
                style={{
                  backgroundColor: preset.value,
                  outlineColor: preset.value,
                }}
                whileHover={reduceMotion ? undefined : { scale: 1.12 }}
                whileTap={reduceMotion ? undefined : { scale: 0.93 }}
              >
                <span className="absolute inset-2 rounded-[7px] bg-white/30" />
                {activeColor === preset.value && (
                  <span className="absolute inset-0 flex items-center justify-center text-[20px] font-black text-white drop-shadow">
                    ✓
                  </span>
                )}
              </motion.button>
            ))}
          </motion.div>
        )}

        {/* Palette control — top-right on compact, far right of the cluster on desktop. */}
        {showColorControls && (
          <div className="absolute top-3 right-3 z-50 sm:top-4 sm:right-4 lg:top-22.5 lg:right-36">
            <motion.button
              type="button"
              onClick={() => setPickerOpen((value) => !value)}
              aria-expanded={pickerOpen}
              aria-label="Customize chat theme color"
              className="flex h-12 w-12 items-center justify-center rounded-[18px] bg-white/85 text-[#5F35F8] shadow-[0_10px_32px_rgba(35,18,74,.13)] ring-1 ring-white/80 outline-none backdrop-blur-md focus-visible:ring-4 sm:h-13 sm:w-13 lg:h-15 lg:w-15"
              style={{ color: activeColor }}
              whileHover={
                reduceMotion ? undefined : { rotate: 10, scale: 1.06 }
              }
              whileTap={reduceMotion ? undefined : { scale: 0.95 }}
            >
              <PaletteIcon size={isCompact ? 24 : 30} />
            </motion.button>
            <AnimatePresence>
              {pickerOpen && (
                <motion.div
                  role="group"
                  aria-label="Custom color picker"
                  initial={
                    reduceMotion ? false : { opacity: 0, scale: 0.9, y: -8 }
                  }
                  animate={{ opacity: 1, scale: 1, y: 0 }}
                  exit={
                    reduceMotion
                      ? undefined
                      : { opacity: 0, scale: 0.92, y: -8 }
                  }
                  transition={{ duration: 0.2 }}
                  className="absolute right-0 top-15 w-56 rounded-2xl bg-white p-4 shadow-[0_14px_40px_rgba(25,18,54,.16)] ring-1 ring-[#e7e1f0] sm:top-16 lg:top-19"
                >
                  <label
                    htmlFor="chathiro-custom-color"
                    className="mb-3 block text-xs font-bold text-slate-600"
                  >
                    Choose any accent color
                  </label>
                  <div className="flex items-center gap-3">
                    <input
                      id="chathiro-custom-color"
                      type="color"
                      value={activeColor}
                      onChange={(event) => setTheme(event.target.value)}
                      aria-label="Custom accent color"
                      className="h-10 w-12 cursor-pointer rounded border-0 bg-transparent p-0"
                    />
                    <span className="font-mono text-sm font-semibold text-slate-700">
                      {activeColor}
                    </span>
                  </div>
                  <p className="mt-2 text-xs text-slate-500">
                    All accent elements update instantly.
                  </p>
                </motion.div>
              )}
            </AnimatePresence>
          </div>
        )}

        {/* Chat — stacked below welcome on compact; upright on the right on desktop. */}
        <div className="relative z-30 mx-auto w-full max-w-md lg:absolute lg:top-22.5 lg:left-[38%] lg:mx-0 lg:w-92 lg:max-w-[calc(100%-24px)]">
          <AnimatePresence mode="wait">
            {chatOpen ? (
              <motion.div
                key="chat-window"
                initial={
                  reduceMotion ? false : { opacity: 0, y: 35, scale: 0.94 }
                }
                animate={{ opacity: 1, y: 0, scale: 1 }}
                exit={
                  reduceMotion ? undefined : { opacity: 0, y: 24, scale: 0.96 }
                }
                transition={{
                  type: "spring",
                  stiffness: 230,
                  damping: 25,
                  delay: 0.05,
                }}
                className="flex h-125 flex-col overflow-hidden rounded-3xl border border-[#e5dfef] bg-white shadow-[0_25px_70px_rgba(34,20,75,.24)] sm:h-140 lg:h-155"
              >
                <header
                  className="flex shrink-0 items-center gap-2.5 px-3.5 py-3.5"
                  style={{ backgroundColor: activeColor, color: foreground }}
                >
                  <button
                    type="button"
                    onClick={() => setChatOpen(false)}
                    title="Back"
                    aria-label="Close chat preview"
                    className="flex h-8 w-8 items-center justify-center rounded-lg transition-colors hover:bg-white/15 focus-visible:outline-2 focus-visible:outline-offset-2"
                  >
                    <ChevronLeftIcon />
                  </button>
                  <div className="relative flex h-10 w-10 items-center justify-center rounded-full bg-white">
                    <RobotIcon color={activeColor} size={28} />
                  </div>
                  <div className="min-w-0 flex-1">
                    <p className="truncate text-sm font-bold">
                      {brandName} AI Agent
                    </p>
                    <p className="text-[11px] opacity-80">Support Agent</p>
                  </div>
                  <button
                    type="button"
                    title="More options"
                    aria-label="More options"
                    className="flex h-8 w-8 items-center justify-center rounded-lg transition-colors hover:bg-white/15 focus-visible:outline-2 focus-visible:outline-offset-2"
                  >
                    <MoreIcon />
                  </button>
                </header>

                <div
                  ref={messagesRef}
                  role="log"
                  aria-label="Demo conversation"
                  aria-live="polite"
                  className="min-h-0 flex-1 space-y-4 overflow-y-auto bg-white px-4 py-5 [scrollbar-color:#DDD6E7_transparent] scrollbar-thin"
                >
                  {messages.map((message) => {
                    const outgoing = message.role === "visitor";
                    return (
                      <motion.div
                        key={message.id}
                        initial={
                          reduceMotion
                            ? false
                            : { opacity: 0, x: outgoing ? 20 : -20, y: 7 }
                        }
                        animate={{ opacity: 1, x: 0, y: 0 }}
                        transition={{
                          type: "spring",
                          stiffness: 270,
                          damping: 25,
                        }}
                        className={`flex items-end gap-2 ${outgoing ? "justify-end" : "justify-start"}`}
                      >
                        {!outgoing && (
                          <div
                            className="mb-1 flex h-7 w-7 shrink-0 items-center justify-center rounded-full"
                            style={{ backgroundColor: light }}
                          >
                            {message.role === "bot" ? (
                              <RobotIcon color={activeColor} size={22} />
                            ) : (
                              <Avatar index={0} size={26} />
                            )}
                          </div>
                        )}
                        <div
                          className={`max-w-[82%] ${outgoing ? "text-right" : "text-left"}`}
                        >
                          {!outgoing && (
                            <p className="mb-1 text-[10px] text-[#838095]">
                              {message.role === "bot"
                                ? `${brandName} AI Agent`
                                : "Sabbir · Support"}{" "}
                              · {message.time}
                            </p>
                          )}
                          <p
                            className={`whitespace-pre-wrap wrap-break-word rounded-2xl px-3.5 py-3 text-left text-[12.5px] leading-normal ${outgoing ? "rounded-br-[5px]" : "rounded-bl-[5px]"}`}
                            style={
                              outgoing
                                ? {
                                    backgroundColor: activeColor,
                                    color: foreground,
                                  }
                                : {
                                    backgroundColor: "#F2F2F7",
                                    color: "#283049",
                                  }
                            }
                          >
                            {message.text}
                          </p>
                          {outgoing && (
                            <p className="mt-1 text-[10px] text-[#918C9F]">
                              {message.time}
                            </p>
                          )}
                        </div>
                      </motion.div>
                    );
                  })}

                  {/* Rich demo message, recreated with HTML, not a baked screenshot. */}
                  <div className="ml-9 rounded-[17px] border border-[#efedf5] bg-[#f6f5f9] p-3">
                    <div
                      className="overflow-hidden rounded-[13px] p-3 text-center"
                      style={{
                        background: `linear-gradient(155deg, ${light} 0%, ${medium} 100%)`,
                      }}
                    >
                      <div
                        className="flex items-center justify-center gap-1.5 text-[11px] font-bold"
                        style={{ color: activeColor }}
                      >
                        <RobotIcon color={activeColor} size={18} /> {brandName}
                      </div>
                      <p className="mx-auto mt-2 max-w-50 text-[14px] font-extrabold leading-tight text-[#29213F]">
                        Everything your team needs, none of the bloat.
                      </p>
                      <div className="mt-3 flex items-end justify-center gap-2">
                        <div
                          className="flex h-14 w-12 items-center justify-center rounded-t-3xl bg-[#8F74C7] text-3xl"
                          aria-hidden="true"
                        >
                          👨🏻‍💻
                        </div>
                        <div
                          role="img"
                          className="w-25 rounded-lg border border-white/70 bg-white p-2 shadow-md"
                          aria-label="Illustration of a chat dashboard"
                        >
                          <div
                            className="mb-2 h-2 rounded-full"
                            style={{ backgroundColor: activeColor }}
                          />
                          <div className="mb-1 h-1.5 w-[80%] rounded-full bg-slate-200" />
                          <div
                            className="ml-auto mb-1 h-1.5 w-[60%] rounded-full"
                            style={{ backgroundColor: medium }}
                          />
                          <div className="mb-1 h-1.5 w-[70%] rounded-full bg-slate-200" />
                        </div>
                        <div
                          className="flex h-14 w-12 items-center justify-center rounded-t-3xl bg-[#E5A0B8] text-3xl"
                          aria-hidden="true"
                        >
                          👩🏻‍💻
                        </div>
                      </div>
                    </div>
                  </div>

                  <AnimatePresence>
                    {typing && (
                      <motion.div
                        key="typing"
                        initial={{ opacity: 0, y: 6 }}
                        animate={{ opacity: 1, y: 0 }}
                        exit={{ opacity: 0 }}
                        className="ml-9 flex w-fit items-center gap-1 rounded-2xl bg-[#F2F2F7] px-4 py-3"
                        aria-label="Agent is typing"
                      >
                        {[0, 1, 2].map((index) => (
                          <motion.span
                            key={index}
                            className="h-1.5 w-1.5 rounded-full"
                            style={{ backgroundColor: activeColor }}
                            animate={
                              reduceMotion
                                ? undefined
                                : { y: [0, -4, 0], opacity: [0.5, 1, 0.5] }
                            }
                            transition={{
                              repeat: Infinity,
                              duration: 0.75,
                              delay: index * 0.16,
                            }}
                          />
                        ))}
                      </motion.div>
                    )}
                  </AnimatePresence>
                </div>

                <form
                  onSubmit={sendMessage}
                  className="shrink-0 border-t border-[#f0eef5] bg-white px-3 pt-3 pb-1"
                >
                  <div className="flex items-center gap-2">
                    <button
                      type="button"
                      aria-label="Attach a file"
                      className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-[#8B879A] transition-colors hover:bg-[#F6F6FA] hover:text-[#5B5670]"
                    >
                      <PaperclipIcon />
                    </button>
                    <div className="relative min-w-0 flex-1">
                      <input
                        ref={inputRef}
                        value={input}
                        onChange={(event) => setInput(event.target.value)}
                        onKeyDown={onInputKeyDown}
                        type="text"
                        maxLength={2000}
                        aria-label="Type your message"
                        placeholder="Write your message..."
                        className="h-11 w-full rounded-full border border-[#eeecf3] bg-[#F6F6FA] py-2 pr-11 pl-4 text-[13px] text-[#292538] outline-none transition placeholder:text-[#9995A7] focus:border-(--ch-accent) focus:bg-white focus:ring-2 focus:ring-(--ch-pale)"
                      />
                      <span
                        className="pointer-events-none absolute top-1/2 right-3.5 -translate-y-1/2 text-[#8B879A]"
                        aria-hidden="true"
                      >
                        <SmileIcon />
                      </span>
                    </div>
                    {input.trim() ? (
                      <motion.button
                        type="submit"
                        aria-label="Send message"
                        disabled={typing}
                        className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full outline-none transition-opacity focus-visible:ring-4 disabled:cursor-not-allowed disabled:opacity-45"
                        style={{
                          backgroundColor: activeColor,
                          color: foreground,
                        }}
                        whileHover={reduceMotion ? undefined : { scale: 1.07 }}
                        whileTap={reduceMotion ? undefined : { scale: 0.92 }}
                      >
                        <SendIcon />
                      </motion.button>
                    ) : (
                      <button
                        type="button"
                        aria-label="Voice message"
                        className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full text-[#8B879A] transition-colors hover:bg-[#F6F6FA] hover:text-[#5B5670]"
                      >
                        <MicIcon />
                      </button>
                    )}
                  </div>
                  <p className="py-2 text-center text-[10px] text-[#78768B]">
                    Powered by{" "}
                    <strong className="text-[#34324D]">{brandName}</strong>
                  </p>
                </form>
              </motion.div>
            ) : (
              <motion.button
                key="chat-launcher"
                type="button"
                onClick={openChat}
                initial={reduceMotion ? false : { opacity: 0, scale: 0.7 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={reduceMotion ? undefined : { opacity: 0, scale: 0.8 }}
                whileHover={reduceMotion ? undefined : { scale: 1.04 }}
                className="mx-auto flex items-center gap-3 rounded-full px-5 py-3.5 text-sm font-semibold shadow-[0_17px_35px_rgba(24,14,49,.2)] focus-visible:outline-4 focus-visible:outline-offset-4 lg:mx-0 lg:ml-auto"
                style={{ backgroundColor: activeColor, color: foreground }}
              >
                <RobotIcon color={activeColor} size={26} />
                Open support chat
                <ArrowIcon size={17} />
              </motion.button>
            )}
          </AnimatePresence>
        </div>

        <div
          className="absolute bottom-3 left-1/2 z-0 h-6 w-44 -translate-x-1/2 rounded-full bg-[#3e265e]/10 blur-xl"
          aria-hidden="true"
        />
      </div>
    </section>
  );
}
