"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { getSavedRecipesOffline, type SavedRecipe } from "@/lib/offline-db";

export default function OfflinePage() {
  const [saved, setSaved] = useState<SavedRecipe[] | null>(null);

  useEffect(() => {
    getSavedRecipesOffline().then(setSaved).catch(() => setSaved([]));
  }, []);

  return (
    <div className="flex min-h-screen flex-col items-center justify-center gap-4 p-8 text-center">
      <h1 className="text-2xl font-semibold">You&apos;re offline</h1>
      <p className="max-w-sm text-muted-foreground">
        Recipes you&apos;ve saved for offline, or recently visited, are available below. Connect to the internet to load new content.
      </p>

      {saved && saved.length > 0 && (
        <ul className="w-full max-w-sm space-y-2 text-left">
          {saved.map((r) => (
            <li key={r.id}>
              <Link
                href={`/recipes/${r.id}`}
                className="block rounded-md border px-3 py-2 text-sm hover:bg-accent"
              >
                {r.title}
              </Link>
            </li>
          ))}
        </ul>
      )}

      <Link
        href="/recipes"
        className="mt-2 underline underline-offset-4 hover:text-primary"
      >
        Back to my recipes
      </Link>
    </div>
  );
}
