"use client";

import React, { useEffect, useRef, useState } from "react";
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";

if (typeof window !== "undefined") {
  gsap.registerPlugin(ScrollTrigger);
}

const PILLS: { value: string; label: string }[] = [
  { value: "100%", label: "Electric Fleet" },
  { value: "Live", label: "Route Sync" },
  { value: "Real-time", label: "Battery Monitoring" },
];

const MINI_STATS: { value: number; decimals?: number; suffix: string; label: string }[] = [
  { value: 94, suffix: "K+", label: "Routes Optimised" },
  { value: 23, suffix: "%", label: "Avg Battery Saved" },
  { value: 1.4, decimals: 1, suffix: "x", label: "Charging Stops Saved" },
];

const FEATURES: { icon: string; title: string; desc: string }[] = [
  {
    icon: "⚡",
    title: "Battery-Aware Routing",
    desc: "Battery level, health, and degradation are first-class inputs to route optimization — not afterthoughts.",
  },
  {
    icon: "🔌",
    title: "Charging Integration",
    desc: "Seamlessly integrate charging stops without compromising delivery windows or SLA commitments.",
  },
  {
    icon: "⛰",
    title: "Energy-Optimized Paths",
    desc: "Factor in elevation, speed limits, payload weight, and live weather for maximum range efficiency.",
  },
  {
    icon: "🛡",
    title: "Predictable Operations",
    desc: "EVs become predictable assets, not operational risks. Full visibility from depot to doorstep.",
  },
];

const BOTTOM_STATS: { value: number; decimals?: number; suffix: string; label: string }[] = [
  { value: 120, suffix: "K+", label: "Deliveries Completed" },
  { value: 98, suffix: "%", label: "On-Time Rate" },
  { value: 31, suffix: "%", label: "Range Efficiency Gain" },
  { value: 340, suffix: "ms", label: "Avg Route Calc Time" },
];

/** Count-up that fires once when scrolled ~20% into view (ease-out cubic). */
function CountUp({
  value,
  decimals = 0,
  suffix = "",
  duration = 1700,
  className,
}: {
  value: number;
  decimals?: number;
  suffix?: string;
  duration?: number;
  className?: string;
}) {
  const [n, setN] = useState(0);
  const ref = useRef<HTMLElement>(null);
  const done = useRef(false);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const reduced = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
    if (reduced) {
      requestAnimationFrame(() => setN(value));
      return;
    }
    const io = new IntersectionObserver(
      (entries) => {
        for (const e of entries) {
          if (e.isIntersecting && !done.current) {
            done.current = true;
            const start = performance.now();
            const ease = (t: number) => 1 - Math.pow(1 - t, 3);
            const tick = (now: number) => {
              const p = Math.min(1, (now - start) / duration);
              setN(value * ease(p));
              if (p < 1) requestAnimationFrame(tick);
              else setN(value);
            };
            requestAnimationFrame(tick);
            io.disconnect();
          }
        }
      },
      { threshold: 0.2 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, [value, duration]);

  return (
    <b ref={ref as React.RefObject<HTMLElement>} className={className}>
      {n.toFixed(decimals)}
      {suffix}
    </b>
  );
}

export default function EVSection() {
  const bannerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // Banner Scroll-Triggered Parallax (Replicating background_image_parallax from theme.js exactly)
    const banner = bannerRef.current;
    if (!banner) return;

    const parallaxTrigger = ScrollTrigger.create({
      trigger: banner,
      start: "top bottom",
      end: "bottom top",
      scrub: true,
      onUpdate: () => {
        if (window.innerWidth >= 1021) {
          const scrollTop = window.scrollY;
          const rect = banner.getBoundingClientRect();
          const offsetTop = rect.top + scrollTop;
          const from_top = scrollTop - offsetTop;
          const yOffset = 0.3 * from_top;
          gsap.set(banner, { backgroundPosition: `center ${yOffset}px` });
        } else {
          gsap.set(banner, { backgroundPosition: "" });
        }
      },
    });

    return () => parallaxTrigger?.kill();
  }, []);

  return (
    <>
      <style dangerouslySetInnerHTML={{ __html: `
        /* ============================================================
           EV-Native Design — redesigned section
           bg #0d0d0d · red #dc2626 / #ef4444 · Syne + DM Sans
           ============================================================ */

        #evnd, #evnd * { font-family: "Manrope", Sans-serif !important; }

        .evnd {
            position: relative;
            isolation: isolate;
            overflow: hidden;
            background: #0d0d0d;
            /* flat top so it connects seamlessly to the banner above; rounded
               bottom only, and no top margin so there is no white gap */
            border-radius: 0 0 clamp(16px, 2vw, 28px) clamp(16px, 2vw, 28px);
            margin: 0 0 clamp(28px, 5vw, 64px);
            padding: 56px 48px 64px;
        }
        /* subtle diagonal light band for depth (matches reference) */
        .evnd::before {
            content: '';
            position: absolute;
            inset: 0;
            z-index: 0;
            pointer-events: none;
            background: linear-gradient(120deg, transparent 28%, rgba(255,255,255,0.025) 50%, transparent 72%);
        }
        .evnd__canvas {
            position: absolute;
            inset: 0;
            width: 100%;
            height: 100%;
            z-index: 0;
            pointer-events: none;
        }
        .evnd__inner { position: relative; z-index: 1; max-width: 1280px; margin: 0 auto; }

        /* ---- TOP ROW ---- */
        .evnd__top {
            display: grid;
            grid-template-columns: 1.5fr 1fr;
            gap: 44px;
            align-items: center;
            margin-bottom: 48px;
        }
        .evnd__eyebrow {
            display: inline-flex;
            align-items: center;
            gap: 12px;
            color: #dc2626 !important;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.16em;
            font-size: 13px;
            margin-bottom: 16px;
        }
        .evnd__eyebrow::before { content: ''; width: 24px; height: 2px; background: #dc2626; }
        .evnd__title {
            color: #fff !important;
            font-weight: 800 !important;
            font-size: clamp(30px, 4.4vw, 56px) !important;
            line-height: 1.04 !important;
            letter-spacing: -0.01em;
            margin: 0;
        }
        .evnd__title .accent { color: #ef4444 !important; }

        .evnd__pills { display: flex; flex-direction: column; gap: 12px; }
        .evnd__pill {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 13px 20px;
            background: rgba(255,255,255,0.04);
            border: 1px solid rgba(255,255,255,0.08);
            border-radius: 100px;
        }
        .evnd__pill .dot {
            flex: 0 0 auto;
            width: 8px; height: 8px;
            border-radius: 50%;
            background: #22c55e;
            box-shadow: 0 0 8px #22c55e;
            animation: evndBlink 1.4s ease-in-out infinite;
        }
        .evnd__pill b { color: #ef4444 !important; font-weight: 800; font-size: 15px; }
        .evnd__pill span { color: rgba(255,255,255,0.62) !important; font-size: 13px; }

        /* ---- MAIN GRID ---- */
        .evnd__grid { display: grid; grid-template-columns: 1fr 1fr; gap: 40px; align-items: start; }

        .evnd__media { position: relative; }
        .evnd__glow {
            position: absolute;
            left: 50%; bottom: -4%;
            width: 72%; height: 64px;
            transform: translateX(-50%);
            background: radial-gradient(50% 50% at 50% 50%, rgba(220,38,38,0.5), transparent 72%);
            filter: blur(30px);
            z-index: 0;
            animation: evndGlow 4s ease-in-out infinite;
        }
        .evnd__imgwrap { position: relative; z-index: 1; animation: evndFloat 7s ease-in-out infinite; will-change: transform; }
        .evnd__img {
            display: block;
            width: 100%;
            height: auto;
            border-radius: 14px;
            box-shadow: 0 30px 60px -25px rgba(0,0,0,0.7);
        }
        .evnd__badge {
            position: absolute;
            z-index: 2;
            display: flex;
            flex-direction: column;
            gap: 2px;
            padding: 10px 14px;
            background: rgba(10,10,10,0.88);
            border: 1px solid rgba(255,255,255,0.1);
            border-radius: 8px;
        }
        .evnd__badge b { color: #ef4444 !important; font-weight: 800; font-size: 24px; line-height: 1; }
        .evnd__badge span { color: rgba(255,255,255,0.55) !important; font-size: 10px; letter-spacing: 0.08em; text-transform: uppercase; }
        .evnd__badge--tl { top: 14px; left: 14px; }
        .evnd__badge--br { bottom: 14px; right: 14px; }

        .evnd__ministats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-top: 20px; }
        .evnd__mini {
            position: relative;
            background: rgba(255,255,255,0.03);
            border: 1px solid rgba(255,255,255,0.06);
            border-radius: 10px;
            padding: 18px 14px 14px;
            overflow: hidden;
        }
        .evnd__mini::before {
            content: '';
            position: absolute; top: 0; left: 0; right: 0;
            height: 2px;
            background: linear-gradient(90deg, #dc2626, transparent);
        }
        .evnd__mini b { display: block; color: #fff !important; font-weight: 800; font-size: clamp(20px, 2.3vw, 28px); line-height: 1; margin-bottom: 6px; }
        .evnd__mini span { color: rgba(255,255,255,0.5) !important; font-size: 11px; letter-spacing: 0.04em; text-transform: uppercase; line-height: 1.3; display: block; }

        /* ---- Feature cards ---- */
        .evnd__features { display: flex; flex-direction: column; gap: 10px; }
        .evnd-feature {
            position: relative;
            display: grid;
            grid-template-columns: 40px 1fr auto;
            gap: 16px;
            align-items: start;
            background: rgba(255,255,255,0.028);
            border: 1px solid rgba(255,255,255,0.07);
            border-radius: 12px;
            padding: 18px 20px;
            overflow: hidden;
            transition: background-color 0.35s ease, border-color 0.35s ease, transform 0.35s cubic-bezier(.25,1,.5,1);
        }
        .evnd-feature::before {
            content: '';
            position: absolute;
            left: 0; top: 0; bottom: 0;
            width: 3px;
            background: #dc2626;
            transform: scaleY(0);
            transform-origin: bottom;
            transition: transform 0.35s ease;
        }
        .evnd-feature:hover { background: rgba(220,38,38,0.06); border-color: rgba(220,38,38,0.25); transform: translateX(4px); }
        .evnd-feature:hover::before { transform: scaleY(1); }
        .evnd-feature__icon {
            width: 40px; height: 40px;
            display: flex; align-items: center; justify-content: center;
            background: rgba(220,38,38,0.1);
            border: 1px solid rgba(220,38,38,0.2);
            border-radius: 10px;
            font-size: 18px;
        }
        .evnd-feature__title {
            color: #fff !important;
            font-weight: 700;
            font-size: 15px !important;
            text-transform: uppercase;
            letter-spacing: 0.04em;
            margin: 3px 0 7px;
            transition: color 0.3s ease;
        }
        .evnd-feature:hover .evnd-feature__title { color: #ef4444 !important; }
        .evnd-feature__desc {
            color: rgba(255,255,255,0.75) !important;
            font-weight: 400 !important;
            font-size: 14.5px !important;
            line-height: 1.65 !important;
            margin: 0;
        }
        .evnd-feature__arrow {
            color: rgba(255,255,255,0.2);
            font-size: 14px;
            align-self: flex-start;
            transition: color 0.3s ease, transform 0.3s ease;
        }
        .evnd-feature:hover .evnd-feature__arrow { color: #ef4444; transform: translate(3px, -3px); }

        /* ---- BOTTOM BAR ---- */
        .evnd__bar {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 1px;
            background: rgba(255,255,255,0.06);
            border-radius: 12px;
            overflow: hidden;
            margin-top: 40px;
        }
        .evnd__bar-item {
            background: #0d0d0d;
            padding: 24px 22px;
            display: flex;
            flex-direction: column;
            gap: 8px;
            align-items: flex-start;
        }
        .evnd__bar-item .dot {
            width: 7px; height: 7px;
            border-radius: 50%;
            background: #dc2626;
            box-shadow: 0 0 8px rgba(220,38,38,0.85);
            animation: evndBlink 1.4s ease-in-out infinite;
        }
        .evnd__bar-item b { color: #fff !important; font-weight: 800; font-size: clamp(22px, 2.6vw, 30px); line-height: 1; }
        .evnd__bar-item span { color: rgba(255,255,255,0.45) !important; font-size: 11px; letter-spacing: 0.06em; text-transform: uppercase; }

        @keyframes evndFloat { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-7px); } }
        @keyframes evndGlow { 0%,100% { opacity: 0.6; } 50% { opacity: 1; } }
        @keyframes evndBlink { 0%,100% { opacity: 1; } 50% { opacity: 0.3; } }

        /* ---- Responsive ---- */
        @media (max-width: 900px) {
            .evnd { padding: 48px 28px 52px; }
            .evnd__top { grid-template-columns: 1fr; gap: 28px; margin-bottom: 36px; }
            .evnd__grid { grid-template-columns: 1fr; gap: 36px; }
        }
        @media (max-width: 600px) {
            .evnd { padding: 40px 18px 44px; }
            .evnd__bar { grid-template-columns: repeat(2, 1fr); }
            .evnd__pill { padding: 11px 16px; }
        }
        @media (prefers-reduced-motion: reduce) {
            .evnd__imgwrap, .evnd__glow, .evnd__pill .dot, .evnd__bar-item .dot { animation: none !important; }
        }
      `}} />

      <div className="elementor-element elementor-element-bbc6760 e-con-full e-flex cut-corner-no sticky-container-off e-con e-parent" data-id="bbc6760" data-element_type="container" data-e-type="container" style={{ backgroundColor: "#0d0d0d", width: "calc(100% - 40px)", marginLeft: "20px", marginRight: "20px", borderRadius: "25px", overflow: "hidden" }}>

        {/* Background Banner with Native GSAP Background Scroll Parallax */}
        <div
          ref={bannerRef}
          className="elementor-element elementor-element-7da6646 e-con-full e-flex cut-corner-no sticky-container-off e-con e-child"
          data-id="7da6646"
          data-element_type="container"
          data-e-type="container"
          data-settings="{&quot;background_background&quot;:&quot;classic&quot;}"
          style={{
            backgroundPosition: "center 0px",
            backgroundImage: "url(/images/bg-header-5.png)",
            backgroundSize: "cover",
            backgroundRepeat: "no-repeat",
            position: "relative",
            zIndex: 2,
            borderRadius: "25px 25px 0 0",
            overflow: "hidden"
          }}
        ></div>

        <div className="elementor-element elementor-element-8b5d6e6 e-con-full e-flex cut-corner-no sticky-container-off e-con e-child" data-id="8b5d6e6" data-element_type="container" data-e-type="container">
          <div className="elementor-element elementor-element-1f766ea e-con-full e-flex cut-corner-no sticky-container-off e-con e-child" data-id="1f766ea" data-element_type="container" data-e-type="container">
            <div className="elementor-element elementor-element-3b61435 e-con-full e-flex cut-corner-no sticky-container-off e-con e-child" data-id="3b61435" data-element_type="container" data-e-type="container" data-settings="{&quot;background_background&quot;:&quot;classic&quot;}">
              <div className="elementor-element elementor-element-c364d1c elementor-widget elementor-widget-text-editor" data-id="c364d1c" data-element_type="widget" data-e-type="widget" data-widget_type="text-editor.default">
                <div className="elementor-widget-container">
                  <p>01</p>
                </div>
              </div>
              <div className="elementor-element elementor-element-239afbb elementor-widget elementor-widget-logico_heading" data-id="239afbb" data-element_type="widget" data-e-type="widget" data-widget_type="logico_heading.default">
                <div className="elementor-widget-container">
                  <h5 className="logico-title">EV Logistics</h5>
                </div>
              </div>
              <div className="elementor-element elementor-element-0d307dd elementor-widget elementor-widget-text-editor" data-id="0d307dd" data-element_type="widget" data-e-type="widget" data-widget_type="text-editor.default">
                <div className="elementor-widget-container">
                  <p>Cleaner miles, lower costs</p>
                </div>
              </div>
            </div>
            <div className="elementor-element elementor-element-5aea22e e-con-full e-flex cut-corner-no sticky-container-off e-con e-child" data-id="5aea22e" data-element_type="container" data-e-type="container" data-settings="{&quot;background_background&quot;:&quot;classic&quot;}"></div>
          </div>
        </div>

        {/* ===== EV-Native Design (redesigned) ===== */}
        <section className="evnd" id="evnd" aria-label="EV-Native Design">
          <div className="evnd__inner">
            {/* TOP ROW */}
            <div className="evnd__top">
              <div className="evnd__head">
                <span className="evnd__eyebrow">/ EV-Native Design /</span>
                <div className="evnd__title">
                  BUILT FOR ELECTRIC. <span className="accent">NOT ADAPTED.</span>
                </div>
              </div>
              <div className="evnd__pills">
                {PILLS.map((p) => (
                  <div className="evnd__pill" key={p.label}>
                    <span className="dot" />
                    <b>{p.value}</b>
                    <span>{p.label}</span>
                  </div>
                ))}
              </div>
            </div>

            {/* MAIN GRID */}
            <div className="evnd__grid">
              {/* Left column */}
              <div className="evnd__left">
                <div className="evnd__media">
                  <div className="evnd__glow" />
                  <div className="evnd__imgwrap">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img className="evnd__img" src="/images/premium-ev-van.png" alt="DoorMile electric delivery van" decoding="async" />
                    <div className="evnd__badge evnd__badge--tl">
                      <b>100%</b>
                      <span>Electric Fleet</span>
                    </div>
                    <div className="evnd__badge evnd__badge--br">
                      <b>&minus;40%</b>
                      <span>Cost / Mile</span>
                    </div>
                  </div>
                </div>

                <div className="evnd__ministats">
                  {MINI_STATS.map((s) => (
                    <div className="evnd__mini" key={s.label}>
                      <CountUp value={s.value} decimals={s.decimals} suffix={s.suffix} />
                      <span>{s.label}</span>
                    </div>
                  ))}
                </div>
              </div>

              {/* Right column */}
              <div className="evnd__features">
                {FEATURES.map((f) => (
                  <div className="evnd-feature" key={f.title}>
                    <span className="evnd-feature__icon" aria-hidden="true">{f.icon}</span>
                    <div className="evnd-feature__body">
                      <div className="evnd-feature__title">{f.title}</div>
                      <p className="evnd-feature__desc">{f.desc}</p>
                    </div>
                    <span className="evnd-feature__arrow" aria-hidden="true">↗</span>
                  </div>
                ))}
              </div>
            </div>

            {/* BOTTOM BAR */}
            <div className="evnd__bar">
              {BOTTOM_STATS.map((s) => (
                <div className="evnd__bar-item" key={s.label}>
                  <span className="dot" />
                  <CountUp value={s.value} decimals={s.decimals} suffix={s.suffix} />
                  <span>{s.label}</span>
                </div>
              ))}
            </div>
          </div>
        </section>

      </div>
    </>
  );
}
