"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { useLang } from "@/context/LanguageContext";

/* Whole-system internet status monitor.
   - Browser online/offline events give the instant signal.
   - navigator.onLine only knows about the network interface, so a light
     heartbeat to /api/ping (visible tabs, every 15s, one retry before
     declaring offline) catches "connected to router, no internet".
   - Offline → full-screen animated SVG overlay; reconnect → a short toast. */

type Status = "online" | "offline";

export default function ConnectionStatus() {
  const { t } = useLang();
  const [status, setStatus] = useState<Status>("online");
  const [showBackOnline, setShowBackOnline] = useState(false);
  const wasOffline = useRef(false);
  const missesRef = useRef(0);
  const inFlight = useRef(false);

  const goOffline = useCallback(() => {
    setStatus("offline");
    wasOffline.current = true;
  }, []);

  const goOnline = useCallback(() => {
    missesRef.current = 0;
    setStatus((prev) => {
      if (prev === "offline" && wasOffline.current) {
        setShowBackOnline(true);
        window.setTimeout(() => setShowBackOnline(false), 3200);
      }
      return "online";
    });
  }, []);

  useEffect(() => {
    // instant signal from the browser
    const onOnline = () => goOnline();
    const onOffline = () => goOffline();
    window.addEventListener("online", onOnline);
    window.addEventListener("offline", onOffline);
    if (typeof navigator !== "undefined" && !navigator.onLine) wasOffline.current = false;
    return () => {
      window.removeEventListener("online", onOnline);
      window.removeEventListener("offline", onOffline);
    };
  }, [goOnline, goOffline]);

  useEffect(() => {
    // heartbeat: one failed ping is a fluke, two in a row → offline
    const beat = async () => {
      if (inFlight.current || document.visibilityState !== "visible") return;
      if (typeof navigator !== "undefined" && !navigator.onLine) return; // offline event handles it
      inFlight.current = true;
      try {
        const res = await fetch("/api/ping", { cache: "no-store" });
        if (res.ok) goOnline();
        else throw new Error(String(res.status));
      } catch {
        missesRef.current += 1;
        if (missesRef.current >= 2) goOffline();
      } finally {
        inFlight.current = false;
      }
    };
    const id = window.setInterval(beat, 15_000);
    return () => window.clearInterval(id);
  }, [goOnline, goOffline]);

  if (status === "online" && !showBackOnline) return null;

  if (status === "offline") {
    return (
      <div className="ems-conn-overlay" role="alertdialog" aria-modal="true" aria-live="assertive">
        <div className="ems-conn-card">
          {/* animated offline emblem: searching wifi arcs + crossed slash */}
          <svg className="ems-conn-svg" viewBox="0 0 120 120" width="132" height="132" aria-hidden="true">
            <circle className="ems-conn-ring" cx="60" cy="60" r="52" fill="none" stroke="rgba(36,105,92,0.12)" strokeWidth="3" />
            <g fill="none" stroke="#24695c" strokeWidth="7" strokeLinecap="round">
              <path className="ems-conn-arc ems-conn-arc-1" d="M38 62a31 31 0 0 1 44 0" />
              <path className="ems-conn-arc ems-conn-arc-2" d="M47 71a18 18 0 0 1 26 0" />
            </g>
            <circle className="ems-conn-dot" cx="60" cy="82" r="5" fill="#24695c" />
            <line className="ems-conn-slash" x1="26" y1="94" x2="94" y2="26" stroke="#d9534f" strokeWidth="7" strokeLinecap="round" />
          </svg>
          <h4 className="f-w-700 mb-1 mt-2">{t.connection.offlineTitle}</h4>
          <p className="ems-fs-13 text-muted mb-3">{t.connection.offlineBody}</p>
          <div className="ems-conn-dots" aria-hidden="true">
            <span className="ems-conn-pulse" />
            <span className="ems-conn-pulse" />
            <span className="ems-conn-pulse" />
          </div>
          <p className="ems-fs-11 text-muted mb-0 mt-2">{t.connection.reconnecting}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="ems-conn-toast" role="status" aria-live="polite">
      <span className="ems-conn-toast-icon">
        <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" fill="none" stroke="#fff" strokeWidth="2.4" strokeLinecap="round">
          <path d="M5 12.5a10 10 0 0 1 14 0" />
          <path d="M8.5 16a5 5 0 0 1 7 0" />
          <circle cx="12" cy="19" r="1.4" fill="#fff" stroke="none" />
        </svg>
      </span>
      <span className="f-w-600">{t.connection.backOnline}</span>
    </div>
  );
}
