// uses useState/useEffect/useRef from global scope (defined in components.jsx)

// ==================================================================
// DYNAMIC COMPONENTS
// Image placeholders + animated counters + review carousel + effects
// ==================================================================

// ——— Image placeholder with prompt (awaiting user-provided images) ———
const ImagePrompt = ({ prompt, aspect = "16/9", tone = "dark", className = "" }) => {
  const toneClass = tone === "dark"
    ? "bg-gradient-to-br from-navy-deep via-navy to-navy text-white/40 ring-white/10"
    : "bg-gradient-to-br from-ink/5 via-ink/[0.03] to-ink/5 text-ink/40 ring-ink/10";
  return (
    <div
      className={`relative w-full rounded-xl ring-1 overflow-hidden grid place-items-center ${toneClass} ${className}`}
      style={{ aspectRatio: aspect }}
    >
      {/* subtle grid pattern */}
      <div className="absolute inset-0 opacity-[0.08]" style={{
        backgroundImage: "linear-gradient(currentColor 1px, transparent 1px), linear-gradient(90deg, currentColor 1px, transparent 1px)",
        backgroundSize: "24px 24px"
      }}/>
      {/* diagonal stripes */}
      <div className="absolute inset-0 opacity-[0.04]" style={{
        backgroundImage: "repeating-linear-gradient(45deg, currentColor 0 1px, transparent 1px 14px)"
      }}/>
      <div className="relative z-10 text-center px-5 md:px-8 max-w-[90%]">
        <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full ring-1 ring-current text-[10px] uppercase tracking-widest font-semibold mb-3">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" className="w-3.5 h-3.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-5-5L5 21"/></svg>
          Bildprompt
        </div>
        <div className={`text-[12px] md:text-[13px] leading-relaxed font-mono ${tone === "dark" ? "text-white/70" : "text-ink/65"}`}>
          {prompt}
        </div>
      </div>
    </div>
  );
};

// ——— Animated counter that counts up when scrolled into view ———
const CountUp = ({ to = 100, duration = 1800, suffix = "", prefix = "", className = "" }) => {
  const [val, setVal] = useState(0);
  const [started, setStarted] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting && !started) {
        setStarted(true);
      }
    }, { threshold: 0.3 });
    obs.observe(el);
    return () => obs.disconnect();
  }, [started]);
  useEffect(() => {
    if (!started) return;
    const start = performance.now();
    const tick = (now) => {
      const elapsed = now - start;
      const progress = Math.min(elapsed / duration, 1);
      // ease-out cubic
      const eased = 1 - Math.pow(1 - progress, 3);
      setVal(Math.round(eased * to));
      if (progress < 1) requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
  }, [started, to, duration]);
  return <span ref={ref} className={className}>{prefix}{val.toLocaleString("de-DE")}{suffix}</span>;
};

// ——— Stat counter row on home page ———
const StatsStrip = () => {
  const stats = [
    { n: 500, suffix: "+", label: "zufriedene Kunden pro Jahr", desc: "Privat und Gewerbe" },
    { n: 4.9, suffix: "", label: "Sterne-Bewertung", desc: "187 Google-Bewertungen", decimal: true },
    { n: 30, suffix: " min", label: "Steinschlag-Reparatur", desc: "Express-Service" },
    { n: 0, suffix: " €", label: "Selbstbeteiligung", desc: "bei Teilkasko-Reparatur" },
  ];
  return (
    <section className="bg-white py-16 md:py-20 border-b border-ink/5">
      <div className="max-w-[1280px] mx-auto px-4 md:px-8">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 md:gap-6">
          {stats.map((s, i) => (
            <div key={i} className="text-center p-6 rounded-2xl bg-gradient-to-b from-bg to-white ring-1 ring-ink/5">
              <div className="text-[44px] md:text-[56px] font-bold text-brand-red tracking-tight leading-none">
                {s.decimal
                  ? <CountUpDecimal to={s.n}/>
                  : <CountUp to={s.n} suffix={s.suffix}/>
                }
              </div>
              <div className="text-[14px] md:text-[15px] font-bold text-ink mt-3 leading-tight">{s.label}</div>
              <div className="text-[12px] text-ink/50 mt-1">{s.desc}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

const CountUpDecimal = ({ to = 4.9, duration = 1800 }) => {
  const [val, setVal] = useState(0);
  const [started, setStarted] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting && !started) setStarted(true);
    }, { threshold: 0.3 });
    obs.observe(el);
    return () => obs.disconnect();
  }, [started]);
  useEffect(() => {
    if (!started) return;
    const start = performance.now();
    const tick = (now) => {
      const elapsed = now - start;
      const progress = Math.min(elapsed / duration, 1);
      const eased = 1 - Math.pow(1 - progress, 3);
      setVal(eased * to);
      if (progress < 1) requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
  }, [started, to, duration]);
  return <span ref={ref}>{val.toFixed(1).replace(".", ",")}</span>;
};

// ——— Review marquee (continuous horizontal scroll) ———
const ReviewMarquee = () => {
  const reviews = [
    { n: "Markus W.", o: "Essen · VW Passat", t: "Morgens angerufen, mittags war der Steinschlag weg. Kein Papierkram.", s: 5 },
    { n: "Selda K.", o: "Altenessen · Sprinter", t: "Als Lieferdienst kann ich nicht warten. Am nächsten Morgen neue Scheibe drin.", s: 5 },
    { n: "Holger B.", o: "Steele · Wohnmobil", t: "Die Panoramascheibe war eine Herausforderung, Kommunikation 1A.", s: 5 },
    { n: "Anna L.", o: "Frohnhausen · BMW 1er", t: "Steinschlag repariert, kein teurer Tausch nötig. Absolut empfehlenswert!", s: 5 },
    { n: "Thomas R.", o: "Rüttenscheid · Audi A4", t: "Top Beratung, faire Preise. Versicherung direkt abgerechnet.", s: 5 },
    { n: "Mehmet Y.", o: "Katernberg · Taxi", t: "Schnelle Hilfe für mein Taxi. Ausfallzeit minimal.", s: 5 },
    { n: "Julia S.", o: "Borbeck · Golf", t: "Sehr freundlich, ehrliche Aussage. Reparatur statt Tausch empfohlen.", s: 5 },
    { n: "Bernd K.", o: "Werden · Tesla Model 3", t: "Eine der wenigen Werkstätten die Tesla wirklich verstehen.", s: 5 },
    { n: "Claudia H.", o: "Kray · Ford Fiesta", t: "Unkomplizierter Service, freundlicher Empfang.", s: 5 },
    { n: "Dieter M.", o: "Heisingen · Porsche Cayenne", t: "Premium-Service auf höchstem Niveau. Sehr professionell.", s: 5 },
  ];
  // duplicate for seamless loop
  const all = [...reviews, ...reviews];
  return (
    <section className="bg-navy-deep py-16 md:py-20 overflow-hidden">
      <div className="max-w-[1280px] mx-auto px-4 md:px-8 mb-8">
        <div className="text-center max-w-[720px] mx-auto">
          <Pill tone="red" className="!normal-case">Live-Stimmen</Pill>
          <h2 className="text-[32px] md:text-[44px] font-bold mt-4 leading-tight tracking-tight text-white">
            Was unsere Kunden sagen
          </h2>
          <div className="flex justify-center items-center gap-2 mt-4">
            <div className="flex gap-0.5 text-amber-400">
              {[0,1,2,3,4].map(i => <Ico.star key={i} className="w-5 h-5"/>)}
            </div>
            <span className="text-white/70 text-[14px]"><CountUpDecimal to={4.9}/> aus <CountUp to={187}/> Google-Bewertungen</span>
          </div>
        </div>
      </div>

      <div className="relative">
        {/* gradient fade edges */}
        <div className="absolute left-0 top-0 bottom-0 w-24 md:w-40 bg-gradient-to-r from-navy-deep to-transparent z-10 pointer-events-none"/>
        <div className="absolute right-0 top-0 bottom-0 w-24 md:w-40 bg-gradient-to-l from-navy-deep to-transparent z-10 pointer-events-none"/>

        <div className="flex gap-5 animate-marquee" style={{ width: "max-content" }}>
          {all.map((r, i) => (
            <div key={i} className="w-[340px] md:w-[400px] shrink-0 bg-white/5 rounded-xl p-6 ring-1 ring-white/10 hover:ring-brand-red/40 transition">
              <div className="flex items-center justify-between mb-3">
                <div className="flex gap-0.5 text-amber-400">
                  {Array.from({length: r.s}).map((_,i) => <Ico.star key={i} className="w-4 h-4"/>)}
                </div>
                <svg viewBox="0 0 24 24" className="w-4 h-4 text-white/30" fill="currentColor"><path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.76h3.56c2.08-1.92 3.28-4.74 3.28-8.09Z"/><path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.56-2.76c-.98.66-2.24 1.06-3.72 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84A11 11 0 0 0 12 23Z"/><path d="M5.84 14.11a6.62 6.62 0 0 1 0-4.22V7.05H2.18a11 11 0 0 0 0 9.9l3.66-2.84Z"/><path d="M12 5.38c1.62 0 3.06.56 4.2 1.64l3.15-3.15A11 11 0 0 0 12 1a11 11 0 0 0-9.82 6.05l3.66 2.84C6.71 7.31 9.14 5.38 12 5.38Z"/></svg>
              </div>
              <p className="text-white/85 text-[14px] leading-relaxed mb-4 line-clamp-3">„{r.t}"</p>
              <div className="pt-3 border-t border-white/10 flex items-center gap-3">
                <div className="w-9 h-9 rounded-full bg-brand-red/20 text-brand-red-light grid place-items-center font-bold text-[13px]">
                  {r.n.charAt(0)}
                </div>
                <div>
                  <div className="font-semibold text-[13px] text-white">{r.n}</div>
                  <div className="text-[11px] text-white/55">{r.o}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      <style>{`
        @keyframes marquee {
          0% { transform: translateX(0); }
          100% { transform: translateX(-50%); }
        }
        .animate-marquee { animation: marquee 80s linear infinite; }
        .animate-marquee:hover { animation-play-state: paused; }
        @media (prefers-reduced-motion: reduce) {
          .animate-marquee { animation: none; }
        }
      `}</style>
    </section>
  );
};

// ——— Live activity ticker (fake but believable) ———
const LiveTicker = () => {
  const events = [
    "🔧 Steinschlag-Reparatur bei VW Golf abgeschlossen (Essen-Nord)",
    "📞 Anruf aus Altenessen – Termin morgen 9 Uhr",
    "✅ Scheibentausch BMW 3er fertig (Rüttenscheid)",
    "🚐 Mobiler Service-Einsatz in Kray unterwegs",
    "⚡ Express-Reparatur Mercedes C-Klasse in 28 Minuten erledigt",
    "📋 Kostenvoranschlag Audi Q5 an Versicherung versendet",
    "🔔 Neue Google-Bewertung: 5 Sterne von Familie M.",
    "🎯 Kalibrierung Spurhalteassistent Tesla Model Y abgeschlossen",
    "🚛 Sprinter-Scheibe für Lieferdienst in 2h eingebaut",
  ];
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setIdx(i => (i + 1) % events.length), 3800);
    return () => clearInterval(id);
  }, []);
  return (
    <div className="bg-navy-deep border-t border-b border-white/10 overflow-hidden">
      <div className="max-w-[1280px] mx-auto px-4 md:px-8 py-3 flex items-center gap-4">
        <div className="flex items-center gap-2 shrink-0">
          <span className="relative flex h-2.5 w-2.5">
            <span className="absolute inline-flex h-full w-full rounded-full bg-brand-red opacity-75 animate-ping"/>
            <span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-brand-red"/>
          </span>
          <span className="text-[11px] uppercase tracking-widest font-bold text-brand-red">Live</span>
        </div>
        <div className="flex-1 min-w-0 overflow-hidden">
          <div key={idx} className="text-[13px] md:text-[14px] text-white/85 truncate animate-slide-in">
            {events[idx]}
          </div>
        </div>
        <div className="hidden md:block text-[11px] text-white/40 shrink-0">vor wenigen Minuten</div>
      </div>
      <style>{`
        @keyframes slide-in {
          from { opacity: 0; transform: translateY(6px); }
          to { opacity: 1; transform: translateY(0); }
        }
        .animate-slide-in { animation: slide-in 0.5s ease-out; }
      `}</style>
    </div>
  );
};

// ——— Reveal on scroll wrapper ———
const Reveal = ({ children, delay = 0, className = "" }) => {
  const [visible, setVisible] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) setVisible(true);
    }, { threshold: 0.15 });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  return (
    <div
      ref={ref}
      className={className}
      style={{
        opacity: visible ? 1 : 0,
        transform: visible ? "translateY(0)" : "translateY(24px)",
        transition: `opacity 0.7s ease-out ${delay}ms, transform 0.7s ease-out ${delay}ms`
      }}
    >
      {children}
    </div>
  );
};

// ——— Enhanced SimplePage — alias to main SimplePage (which now has hero image) ———
const SimplePageV2 = (props) => {
  if (typeof SimplePage !== "undefined") return <SimplePage {...props}/>;
  return null;
};

Object.assign(window, {
  ImagePrompt, CountUp, CountUpDecimal, StatsStrip, ReviewMarquee, LiveTicker, Reveal, SimplePageV2
});
