"use client";

import { useEffect, useState } from "react";

interface OfflineCacheProps {
  idAw: string;
  profileData: Record<string, unknown>;
  children: React.ReactNode;
}

export default function OfflineCache({ idAw, profileData, children }: OfflineCacheProps) {
  const [isOffline, setIsOffline] = useState(false);
  const [cachedData, setCachedData] = useState<Record<string, unknown> | null>(null);

  useEffect(() => {
    // Cache profile data on mount
    const cacheKey = `cached_profile_${idAw}`;
    try {
      localStorage.setItem(
        cacheKey,
        JSON.stringify({
          data: profileData,
          cachedAt: new Date().toISOString(),
        })
      );
    } catch {
      // Storage quota exceeded or unavailable
    }

    // Listen for online/offline events
    const handleOffline = () => {
      setIsOffline(true);
      try {
        const cached = localStorage.getItem(cacheKey);
        if (cached) {
          const parsed = JSON.parse(cached);
          setCachedData(parsed.data);
        }
      } catch {
        // Parse error
      }
    };

    const handleOnline = () => {
      setIsOffline(false);
      setCachedData(null);
    };

    // Check initial state
    if (!navigator.onLine) {
      handleOffline();
    }

    window.addEventListener("offline", handleOffline);
    window.addEventListener("online", handleOnline);

    return () => {
      window.removeEventListener("offline", handleOffline);
      window.removeEventListener("online", handleOnline);
    };
  }, [idAw, profileData]);

  return (
    <>
      {isOffline && (
        <div className="bg-amber-900/30 border border-amber-500/30 rounded-xl px-4 py-3 mb-4 flex items-center gap-3">
          <svg className="w-5 h-5 text-amber-400 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18.364 5.636a9 9 0 010 12.728m-2.829-2.829a5 5 0 000-7.07m-2.828 2.828a1 1 0 010 1.414" />
          </svg>
          <p className="text-amber-200 text-sm">
            You&apos;re viewing a cached version. Connect to the internet for the latest information.
          </p>
        </div>
      )}
      {children}
    </>
  );
}
