"use client";

/**
 * NativePullToRefresh — touch pull-to-refresh, aktivan SAMO unutar
 * Capacitor native aplikacije. Na web-u komponenta rano izlazi i ne
 * renderuje ništa niti vezuje listenere (web ostaje bajt-identičan;
 * gating preko Capacitor.isNativePlatform() + dinamičkog import()-a).
 *
 * Bez biblioteke: prati touch pri scrollTop===0, rubber-band indikator,
 * na prelazak praga `router.refresh()` (soft) + reload fallback.
 */

import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";

const THRESHOLD = 72;
const MAX_PULL = 120;

export function NativePullToRefresh() {
  const router = useRouter();
  const [isNative, setIsNative] = useState(false);
  const [pull, setPull] = useState(0);
  const [refreshing, setRefreshing] = useState(false);
  const startY = useRef<number | null>(null);
  const reduced = useRef(false);

  useEffect(() => {
    let disposed = false;
    (async () => {
      try {
        const { Capacitor } = await import("@capacitor/core");
        if (!disposed && Capacitor.isNativePlatform()) setIsNative(true);
      } catch {
        /* no-op */
      }
    })();
    reduced.current =
      typeof window !== "undefined" &&
      window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
    return () => {
      disposed = true;
    };
  }, []);

  useEffect(() => {
    if (!isNative) return;

    const atTop = () =>
      (window.scrollY || document.documentElement.scrollTop || 0) <= 0;

    const onStart = (e: TouchEvent) => {
      if (refreshing) return;
      startY.current = atTop() ? e.touches[0].clientY : null;
    };

    const onMove = (e: TouchEvent) => {
      if (startY.current == null || refreshing) return;
      const delta = e.touches[0].clientY - startY.current;
      if (delta <= 0) {
        setPull(0);
        return;
      }
      if (!atTop()) {
        startY.current = null;
        setPull(0);
        return;
      }
      // Rubber-band damping.
      const damped = Math.min(MAX_PULL, delta * 0.5);
      setPull(damped);
    };

    const onEnd = () => {
      if (startY.current == null) return;
      startY.current = null;
      if (pull >= THRESHOLD && !refreshing) {
        setRefreshing(true);
        setPull(THRESHOLD);
        window.setTimeout(() => {
          try {
            router.refresh();
          } catch {
            /* no-op */
          }
          window.location.reload();
        }, 320);
      } else {
        setPull(0);
      }
    };

    window.addEventListener("touchstart", onStart, { passive: true });
    window.addEventListener("touchmove", onMove, { passive: true });
    window.addEventListener("touchend", onEnd, { passive: true });
    window.addEventListener("touchcancel", onEnd, { passive: true });
    return () => {
      window.removeEventListener("touchstart", onStart);
      window.removeEventListener("touchmove", onMove);
      window.removeEventListener("touchend", onEnd);
      window.removeEventListener("touchcancel", onEnd);
    };
  }, [isNative, pull, refreshing, router]);

  if (!isNative || (pull <= 0 && !refreshing)) return null;

  const progress = Math.min(1, pull / THRESHOLD);
  const animate = !reduced.current;

  return (
    <div
      className="native-ptr"
      style={{
        transform: `translateY(${pull}px)`,
        opacity: progress,
      }}
      aria-hidden="true"
    >
      <span
        className="native-ptr-spinner"
        data-spin={refreshing && animate ? "true" : "false"}
        style={{
          transform: refreshing
            ? undefined
            : `rotate(${progress * 270}deg)`,
        }}
      >
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" aria-hidden="true">
          <circle
            cx="12"
            cy="12"
            r="9"
            stroke="rgba(194,65,12,0.2)"
            strokeWidth="3"
          />
          <path
            d="M12 3a9 9 0 0 1 9 9"
            stroke="#c2410c"
            strokeWidth="3"
            strokeLinecap="round"
          />
        </svg>
      </span>
    </div>
  );
}

export default NativePullToRefresh;
