"use client";

import Image from "next/image";
import Link from "next/link";
import { useEffect, useState } from "react";
import { appVersion } from "@/lib/runtime/version";
import type { SettingsContent } from "@/lib/content/types";

const fallbackSettings: SettingsContent = {
  siteName: "Funktechnik Schubert",
  logoUrl: "/funktechnik_schubert_logo.jpg",
  footerShortText: "Service und technische Unterstützung für Funkgeräte, Messtechnik und Kommunikationstechnik.",
  copyright: "© Funktechnik Schubert",
  footerLinks: [
    { label: "Leistungen", href: "/leistungen" },
    { label: "Funkgeräte-Service", href: "/funkgeraete-service" },
    { label: "Reparatur", href: "/reparatur" },
    { label: "Kontakt", href: "/kontakt" },
  ],
  legalLinks: [
    { label: "Impressum", href: "/impressum" },
    { label: "Datenschutz", href: "/datenschutz" },
  ],
  headerCta: { label: "Reparatur anfragen", href: "/reparatur" },
  seo: {
    metaTitle: "Funktechnik Schubert",
    metaDescription: "",
    keywords: "",
    openGraphTitle: "",
    openGraphDescription: "",
    socialImage: "/funktechnik_schubert_logo.jpg",
    canonicalUrl: "/",
  },
  updatedAt: "",
};

export default function Footer() {
  const [settings, setSettings] = useState(fallbackSettings);

  useEffect(() => {
    let active = true;

    async function loadSettings() {
      try {
        const response = await fetch("/api/content/settings");
        const result = await response.json() as { settings?: SettingsContent };
        if (active && response.ok && result.settings) setSettings(result.settings);
      } catch {
        if (active) setSettings(fallbackSettings);
      }
    }

    void loadSettings();
    return () => {
      active = false;
    };
  }, []);

  return (
    <footer className="footer">
      <div className="container footer-grid">
        <div>
          <Image
            src={settings.logoUrl || fallbackSettings.logoUrl}
            alt={settings.siteName}
            width={1672}
            height={941}
            className="footer-logo"
          />
          <p>{settings.footerShortText}</p>
          <p className="copyright">{settings.copyright} · v{appVersion}</p>
        </div>
        <div>
          <h3>Website</h3>
          {settings.footerLinks.map((link) => <p key={`${link.href}-${link.label}`}><Link href={link.href}>{link.label}</Link></p>)}
        </div>
        <div>
          <h3>Rechtliches</h3>
          {settings.legalLinks.map((link) => <p key={`${link.href}-${link.label}`}><Link href={link.href}>{link.label}</Link></p>)}
        </div>
      </div>
    </footer>
  );
}
