// ===== Shared parts for Peeka v2 =====
const { useState, useEffect, useRef, useMemo } = React;

const rupiah = (n) => "Rp " + n.toLocaleString("id-ID");

const toPascal = (s) =>
  s
    .split("-")
    .map((w) => w[0].toUpperCase() + w.slice(1))
    .join("");
const Icon = ({ name, className = "", size = 20, strokeWidth = 2 }) => {
  const ref = useRef(null);
  useEffect(() => {
    if (ref.current && window.lucide) {
      ref.current.innerHTML = "";
      const svg = window.lucide.createElement(
        window.lucide[toPascal(name)] || window.lucide.Circle,
      );
      svg.setAttribute("width", size);
      svg.setAttribute("height", size);
      svg.setAttribute("stroke-width", strokeWidth);
      svg.setAttribute("class", className);
      ref.current.appendChild(svg);
    }
  }, [name, className, size, strokeWidth]);
  return <span ref={ref} className="inline-flex" />;
};

// ===== Fireflies =====
const Fireflies = ({ count = 14 }) => {
  const flies = useMemo(
    () =>
      Array.from({ length: count }, () => ({
        top: Math.random() * 90 + 2,
        left: Math.random() * 95 + 2,
        delay: Math.random() * 3,
        driftDelay: Math.random() * 9,
        scale: 0.5 + Math.random() * 1.2,
      })),
    [count],
  );
  return (
    <div
      className="absolute inset-0 overflow-hidden pointer-events-none"
      aria-hidden="true"
    >
      {flies.map((f, i) => (
        <span
          key={i}
          className="firefly"
          style={{
            top: f.top + "%",
            left: f.left + "%",
            transform: `scale(${f.scale})`,
            animationDelay: `${f.delay}s, ${f.driftDelay}s`,
          }}
        />
      ))}
    </div>
  );
};

// ===== Reveal on scroll =====
const useReveal = () => {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) e.target.classList.add("in");
        });
      },
      { threshold: 0.12 },
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
};

// ===== Logo =====
const Logo = ({ light = false }) => (
  <div className="flex items-center gap-2">
    <div className="relative w-10 h-10 flex-shrink-0">
      <div className="absolute inset-0 rounded-full bg-glow-400/30 blur-lg pulse-glow"></div>
      <img
        src="peeka-logo.png"
        alt="Peeka"
        className="relative w-full h-full object-contain"
      />
    </div>
    <span
      className={`font-extrabold text-xl tracking-tight ${light ? "text-white" : "text-navy-900"}`}
    >
      Peeka
    </span>
  </div>
);

// ===== Telegram Chat Bubble — native feel =====
// Telegram uses: sky-blue user bubbles (right), white bot bubbles (left), rounded 18px, tail on last bubble
const ChatBubble = ({
  side = "bot",
  children,
  time,
  tail = true,
  delay = 0,
  avatar = null,
  name = null,
}) => {
  const [show, setShow] = useState(delay === 0);
  useEffect(() => {
    if (delay > 0) {
      const t = setTimeout(() => setShow(true), delay);
      return () => clearTimeout(t);
    }
  }, [delay]);
  if (!show) return null;
  const isUser = side === "user";
  return (
    <div
      className={`flex gap-2 ${isUser ? "justify-end" : "justify-start"}`}
      style={{ animation: "bubbleIn .35s cubic-bezier(.2,.8,.2,1)" }}
    >
      {!isUser && avatar && (
        <div className="w-7 h-7 rounded-full bg-gradient-to-br from-glow-300 to-glow-500 flex items-center justify-center text-navy-900 font-extrabold text-xs flex-shrink-0 self-end">
          {avatar}
        </div>
      )}
      <div
        className={`
        relative max-w-[82%] px-3 py-2 text-[13px] leading-snug
        ${
          isUser
            ? "bg-[#EFFDDE] text-navy-900 rounded-2xl rounded-br-md"
            : "bg-white text-navy-900 rounded-2xl rounded-bl-md shadow-sm"
        }
      `}
      >
        {!isUser && name && (
          <div className="text-[11px] font-semibold text-teal-600 mb-0.5">
            {name}
          </div>
        )}
        <div className="whitespace-pre-line">{children}</div>
        {time && (
          <div
            className={`flex items-center justify-end gap-0.5 mt-0.5 text-[10px] ${isUser ? "text-teal-700/70" : "text-navy-900/40"}`}
          >
            <span>{time}</span>
            {isUser && (
              <Icon name="check-check" size={10} className="text-sky-500" />
            )}
          </div>
        )}
        {tail && (
          <span
            className={`absolute bottom-0 ${isUser ? "right-[-5px]" : "left-[-5px]"} w-2.5 h-3`}
            style={{
              background: isUser ? "#EFFDDE" : "white",
              clipPath: isUser
                ? "polygon(0 0, 100% 100%, 0 100%)"
                : "polygon(100% 0, 100% 100%, 0 100%)",
            }}
          ></span>
        )}
      </div>
    </div>
  );
};

// ===== Telegram Window frame =====
const TelegramWindow = ({
  children,
  botName = "Peeka Bot",
  subtitle = "bot",
}) => (
  <div className="relative bg-white rounded-[22px] shadow-2xl ring-1 ring-black/5 overflow-hidden w-full max-w-[400px] mx-auto">
    {/* Header */}
    <div className="bg-gradient-to-b from-[#517DA2] to-[#4A7296] text-white px-4 py-3 flex items-center gap-3">
      <Icon name="chevron-left" size={18} className="opacity-70" />
      <div className="relative w-9 h-9 rounded-full bg-gradient-to-br from-glow-300 to-glow-500 flex items-center justify-center flex-shrink-0">
        <span className="text-navy-900 font-extrabold text-sm">P</span>
      </div>
      <div className="flex-1 min-w-0">
        <div className="font-semibold text-sm leading-tight truncate">
          {botName}
        </div>
        <div className="text-[11px] text-white/70">{subtitle}</div>
      </div>
      <Icon name="search" size={16} className="opacity-70" />
      <Icon name="more-vertical" size={16} className="opacity-70" />
    </div>
    {/* Chat body */}
    <div
      className="relative px-3 py-4 space-y-2 min-h-[380px]"
      style={{
        background: "linear-gradient(135deg, #E6E9F0 0%, #D7E3F0 100%)",
        backgroundImage:
          "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='60' height='60'><g fill='%23c3cfe0' opacity='0.4'><circle cx='15' cy='15' r='2'/><circle cx='45' cy='30' r='1.5'/><circle cx='30' cy='50' r='1'/></g></svg>\"), linear-gradient(135deg, #E6E9F0 0%, #D7E3F0 100%)",
      }}
    >
      {children}
    </div>
    {/* Composer */}
    <div className="bg-white px-3 py-2.5 flex items-center gap-2 border-t border-navy-900/5">
      <Icon name="paperclip" size={18} className="text-navy-900/40" />
      <div className="flex-1 text-[12px] text-navy-900/40">Message</div>
      <Icon name="smile" size={18} className="text-navy-900/40" />
      <Icon name="mic" size={18} className="text-[#517DA2]" />
    </div>
  </div>
);

// ===== Nav =====
const Nav = () => {
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <header
      className={`fixed top-0 inset-x-0 z-50 transition-all ${scrolled ? "bg-navy-900/85 backdrop-blur-md border-b border-white/10" : "bg-transparent"}`}
    >
      <div className="max-w-7xl mx-auto px-5 sm:px-8 h-16 flex items-center justify-between">
        <Logo light />
        <nav className="hidden md:flex items-center gap-8 text-sm text-white/80">
          <a href="#fitur" className="hover:text-white">
            Fitur
          </a>
          <a href="#cara-pakai" className="hover:text-white">
            Cara Pakai
          </a>
          <a href="#menu-bot" className="hover:text-white">
            Menu Bot
          </a>
          <a href="#harga" className="hover:text-white">
            Harga
          </a>
          <a href="#umkm" className="hover:text-white">
            UMKM
          </a>
        </nav>
        <div className="hidden md:flex items-center gap-3">
          <a
            href="https://t.me/peeka_id_bot?start=mulai_sekarang"
            className="inline-flex items-center gap-2 bg-glow-400 hover:bg-glow-300 text-navy-900 font-semibold text-sm px-4 py-2 rounded-full shadow-glow-sm"
          >
            <Icon name="send" size={14} /> Coba di Telegram
          </a>
        </div>
        <button
          onClick={() => setOpen(!open)}
          className="md:hidden text-white p-2"
          aria-label="Menu"
        >
          <Icon name={open ? "x" : "menu"} size={22} />
        </button>
      </div>
      {open && (
        <div className="md:hidden bg-navy-900/95 backdrop-blur-md border-t border-white/10 px-6 py-5 space-y-4 text-white/90">
          <a href="#fitur" onClick={() => setOpen(false)} className="block">
            Fitur
          </a>
          <a
            href="#cara-pakai"
            onClick={() => setOpen(false)}
            className="block"
          >
            Cara Pakai
          </a>
          <a href="#menu-bot" onClick={() => setOpen(false)} className="block">
            Menu Bot
          </a>
          <a href="#harga" onClick={() => setOpen(false)} className="block">
            Harga
          </a>
          <a href="#umkm" onClick={() => setOpen(false)} className="block">
            UMKM
          </a>
          <a
            href="#cta"
            onClick={() => setOpen(false)}
            className="block bg-glow-400 text-navy-900 font-semibold text-center py-2.5 rounded-full"
          >
            Coba di Telegram
          </a>
        </div>
      )}
    </header>
  );
};

Object.assign(window, {
  rupiah,
  Icon,
  Fireflies,
  useReveal,
  Logo,
  ChatBubble,
  TelegramWindow,
  Nav,
});
