import { prisma } from '@/lib/prisma'

interface FooterLink {
  label: string
  url: string
}

export async function Footer() {
  let rows: { key: string; value: unknown }[] = []
  try {
    rows = await prisma.siteSettings.findMany({
      where: { key: { in: ['footer_copyright', 'footer_links', 'site_name'] } },
    })
  } catch {
    // DB not available at build time
  }

  const s = Object.fromEntries(rows.map((r) => [r.key, r.value]))
  const siteName = (s.site_name as string) || 'Il Negozio'
  const copyright = (s.footer_copyright as string) || `© ${new Date().getFullYear()} ${siteName}`
  let links: FooterLink[] = []
  try {
    const raw = s.footer_links
    if (Array.isArray(raw)) links = raw as unknown as FooterLink[]
  } catch {
    // invalid JSON stored, ignore
  }

  return (
    <footer className="border-t border-gray-200 bg-white mt-auto">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col sm:flex-row items-center justify-between gap-3">
        <p className="text-sm text-gray-500">{copyright}</p>
        {links.length > 0 && (
          <nav className="flex gap-4">
            {links.map((link) => (
              <a
                key={link.url}
                href={link.url}
                className="text-sm text-gray-500 hover:text-gray-900 transition-colors"
              >
                {link.label}
              </a>
            ))}
          </nav>
        )}
      </div>
    </footer>
  )
}
