"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 FEATURES: { icon: React.ReactNode; title: string; desc: string }[] = [
  {
    icon: (
      <svg className="evnd-icon" viewBox="0 0 24 24" fill="none" stroke="#f59e0b" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" />
      </svg>
    ),
    title: "Battery-Aware Routing",
    desc: "Battery level, health, and degradation are first-class inputs to route optimization — not afterthoughts.",
  },
  {
    icon: (
      <svg className="evnd-icon" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M18 10h-1.28A6 6 0 0 0 12 5V3M12 5V3M6 10h1.28A6 6 0 0 0 12 5M12 18v2M12 18v2M8 10v6a4 4 0 0 0 8 0v-6" />
      </svg>
    ),
    title: "Charging Integration",
    desc: "Seamlessly integrate charging stops without compromising delivery windows or SLA commitments.",
  },
  {
    icon: (
      <svg className="evnd-icon" viewBox="0 0 24 24" fill="none" stroke="#ef4444" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="m8 3 4 8 5-5 5 15H2L8 3z" />
      </svg>
    ),
    title: "Energy-Optimized Paths",
    desc: "Factor in elevation, speed limits, payload weight, and live weather for maximum range efficiency.",
  },
  {
    icon: (
      <svg className="evnd-icon" viewBox="0 0 24 24" fill="none" stroke="#ef4444" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
      </svg>
    ),
    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: 99.9, decimals: 1, suffix: "%", label: "SLA Compliance" },
  { value: 42, suffix: "%", label: "Distance Saved" },
  { value: 37, suffix: "%", label: "Fewer Vehicles" },
  { value: 45, suffix: "ms", label: "Dispatch Latency" },
];

/** 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 #080808 · red #ef4444 · Manrope
           ============================================================ */

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

        .evnd {
            position: relative;
            isolation: isolate;
            overflow: hidden;
            background: #080808;
            /* 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: 64px 48px clamp(48px, 6vw, 80px);
        }
        /* 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.015) 50%, transparent 72%);
        }
        .evnd__inner { position: relative; z-index: 1; max-width: 1280px; margin: 0 auto; }

        /* ---- MAIN GRID ---- */
        .evnd__grid {
            display: grid;
            grid-template-columns: 1.15fr 1fr;
            gap: clamp(32px, 4vw, 56px);
            align-items: center;
        }

        .evnd__left {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
        }

        .evnd__right {
            display: flex;
            flex-direction: column;
        }

        .evnd__eyebrow {
            display: inline-flex;
            align-items: center;
            gap: 12px;
            color: #ef4444 !important;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.16em;
            font-size: 13px;
            margin-bottom: 20px;
        }
        .evnd__eyebrow::before {
            content: '';
            width: 16px;
            height: 2px;
            background: #ef4444;
        }
        
        .evnd__title {
            color: #fff !important;
            font-weight: 800 !important;
            font-size: clamp(32px, 3.8vw, 48px) !important;
            line-height: 1.15 !important;
            letter-spacing: -0.01em;
            margin: 0 0 36px 0;
        }
        @media (min-width: 768px) {
            .evnd__title {
                white-space: nowrap;
            }
        }
        .evnd__title .accent {
            color: #ef4444 !important;
        }

        .evnd__media {
            position: relative;
            width: 100%;
        }
        .evnd__glow {
            position: absolute;
            left: 50%; bottom: -4%;
            width: 80%; height: 80px;
            transform: translateX(-50%);
            background: radial-gradient(50% 50% at 50% 50%, rgba(239,68,68,0.3), transparent 72%);
            filter: blur(35px);
            z-index: 0;
            animation: evndGlow 4s ease-in-out infinite;
        }
        .evnd__imgwrap {
            position: relative;
            z-index: 1;
            overflow: hidden;
            border-radius: 16px;
            border: 1px solid rgba(255,255,255,0.06);
            box-shadow: 0 30px 60px -25px rgba(0,0,0,0.85);
        }
        .evnd__img {
            display: block;
            width: 100%;
            height: auto;
            object-fit: cover;
            transition: transform 0.8s cubic-bezier(0.25, 1, 0.5, 1);
        }
        .evnd__imgwrap:hover .evnd__img {
            transform: scale(1.03);
        }

        /* Badge overlay styling */
        .evnd__badge {
            position: absolute;
            z-index: 2;
            display: flex;
            flex-direction: column;
            gap: 2px;
            padding: 12px 16px;
            background: rgba(13,13,13,0.72);
            border: 1px solid rgba(255,255,255,0.08);
            border-radius: 8px;
            backdrop-filter: blur(12px);
            -webkit-backdrop-filter: blur(12px);
        }
        .evnd__badge b {
            color: #ef4444 !important;
            font-weight: 800;
            font-size: 24px;
            line-height: 1;
        }
        .evnd__badge span {
            color: rgba(255,255,255,0.7) !important;
            font-size: 10px;
            font-weight: 700;
            letter-spacing: 0.08em;
            text-transform: uppercase;
        }
        .evnd__badge--tl { top: 20px; left: 20px; }
        .evnd__badge--br { bottom: 20px; right: 20px; }

        /* ---- Feature cards ---- */
        .evnd__features {
            display: flex;
            flex-direction: column;
            gap: 16px;
            height: 100%;
            justify-content: space-between;
        }
        .evnd-feature {
            position: relative;
            display: grid;
            grid-template-columns: 48px 1fr auto;
            gap: 20px;
            align-items: start;
            background: rgba(255,255,255,0.02);
            border: 1px solid rgba(255,255,255,0.05);
            border-radius: 16px;
            padding: 24px;
            overflow: hidden;
            transition: background-color 0.4s ease, border-color 0.4s ease, transform 0.4s cubic-bezier(.25,1,.5,1);
        }
        .evnd-feature::before {
            content: '';
            position: absolute;
            left: 0; top: 0; bottom: 0;
            width: 3px;
            background: #ef4444;
            transform: scaleY(0);
            transform-origin: bottom;
            transition: transform 0.4s ease;
        }
        .evnd-feature:hover {
            background: rgba(239,68,68,0.03);
            border-color: rgba(239,68,68,0.2);
            transform: translateY(-2px);
        }
        .evnd-feature:hover::before { transform: scaleY(1); }
        
        .evnd-feature__icon-container {
            width: 48px; height: 48px;
            display: flex; align-items: center; justify-content: center;
            background: rgba(255,255,255,0.03);
            border: 1px solid rgba(255,255,255,0.08);
            border-radius: 12px;
            transition: background-color 0.3s ease, border-color 0.3s ease;
        }
        .evnd-feature:hover .evnd-feature__icon-container {
            background: rgba(239,68,68,0.08);
            border-color: rgba(239,68,68,0.25);
        }
        
        .evnd-icon {
            width: 22px;
            height: 22px;
            display: block;
        }
        
        .evnd-feature__title {
            color: #fff !important;
            font-weight: 700;
            font-size: 15px !important;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            margin: 4px 0 8px;
            transition: color 0.3s ease;
        }
        .evnd-feature:hover .evnd-feature__title { color: #ef4444 !important; }
        .evnd-feature__desc {
            color: rgba(255,255,255,0.65) !important;
            font-weight: 400 !important;
            font-size: 14px !important;
            line-height: 1.6 !important;
            margin: 0;
        }
        .evnd-feature__arrow {
            color: rgba(255,255,255,0.25);
            font-size: 16px;
            align-self: flex-start;
            margin-top: 4px;
            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);
            background: rgba(255,255,255,0.02);
            border: 1px solid rgba(255,255,255,0.06);
            border-radius: 16px;
            overflow: hidden;
            margin-top: 60px;
            padding: 38px 0;
        }
        .evnd__bar-item {
            position: relative;
            display: flex;
            flex-direction: column;
            gap: 12px;
            align-items: center;
            justify-content: center;
            text-align: center;
            padding: 12px 24px;
        }
        .evnd__bar-item:not(:last-child)::after {
            content: '';
            position: absolute;
            right: 0;
            top: 15%;
            height: 70%;
            width: 1px;
            background: rgba(255, 255, 255, 0.08);
        }
        
        .evnd__bar-val {
            color: #ef4444 !important;
            font-weight: 800;
            font-size: clamp(32px, 4vw, 56px);
            line-height: 1;
        }
        .evnd__bar-label {
            color: #fff !important;
            font-size: 14px;
            font-weight: 600;
            letter-spacing: 0.02em;
            text-transform: none;
            opacity: 0.9;
        }

        @keyframes evndGlow { 0%,100% { opacity: 0.75; } 50% { opacity: 1; } }

        /* ---- Responsive ---- */
        @media (max-width: 991px) {
            .evnd { padding: 48px 32px 56px; }
            .evnd__grid { grid-template-columns: 1fr; gap: 40px; }
            .evnd__title { margin-bottom: 28px; }
            .evnd__features { gap: 14px; }
        }
        @media (max-width: 767px) {
            .evnd__bar { grid-template-columns: repeat(2, 1fr); gap: 24px 0; padding: 24px 0; }
            .evnd__bar-item:nth-child(even)::after { display: none; }
            .evnd__bar-item:nth-child(2)::after { display: none; }
            .evnd__bar-item { padding: 12px 16px; }
        }
        @media (max-width: 480px) {
            .evnd { padding: 40px 16px 48px; }
            .evnd__bar { grid-template-columns: 1fr; gap: 28px 0; }
            .evnd__bar-item::after { display: none !important; }
            .evnd__badge { padding: 8px 12px; }
            .evnd__badge b { font-size: 20px; }
        }
      `}} />

      <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">
            <span className="evnd__eyebrow">/ EV-Native Design /</span>
            <h2 className="evnd__title">
              BUILT FOR ELECTRIC. <span className="accent">NOT ADAPTED.</span>
            </h2>

            {/* 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>-40%</b>
                      <span>COST / MILE</span>
                    </div>
                  </div>
                </div>
              </div>

              {/* Right column */}
              <div className="evnd__right">
                <div className="evnd__features">
                  {FEATURES.map((f) => (
                    <div className="evnd-feature" key={f.title}>
                      <div className="evnd-feature__icon-container" aria-hidden="true">
                        {f.icon}
                      </div>
                      <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>
            </div>

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

      </div>
    </>
  );
}
