'use client';

import { useEffect, useState } from 'react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';
import { useLiveRefresh } from '@/lib/realtime';

type Company = {
  legalName: string; crbNo: string; tin: string; vrn: string; phone1: string; phone2: string;
  email: string; website: string; addressLine: string; poBox: string;
};

// Company identity comes from Settings → Company, so changing it there changes this footer (and every PDF) at once.
export default function Footer() {
  const { accessToken, appSecretProof } = useAuth();
  const [c, setC] = useState<Company | null>(null);

  async function load() {
    if (!accessToken || !appSecretProof) return;
    try { setC((await adminApiFetch('/admin/settings/company', accessToken, appSecretProof)).settings); } catch { /* footer is non-critical */ }
  }
  useEffect(() => { load(); }, [accessToken, appSecretProof]); // eslint-disable-line react-hooks/exhaustive-deps
  useLiveRefresh(['settings'], load);

  if (!c) return <footer className="h-12" />;
  return (
    <footer className="border-t border-brand-border bg-white px-6 py-3 text-[11px] text-gray-500 flex flex-wrap items-center gap-x-4 gap-y-1">
      <span className="font-semibold text-brand-charcoal">{c.legalName}</span>
      {c.crbNo && <span>CRB {c.crbNo}</span>}
      {c.tin && <span>TIN {c.tin}</span>}
      {c.vrn && <span>VRN {c.vrn}</span>}
      <span>{[c.phone1, c.phone2].filter(Boolean).join(' / ')}</span>
      <span>{c.email}</span>
      <span>{c.poBox ? `P.O. Box ${c.poBox}, ` : ''}{c.addressLine}</span>
    </footer>
  );
}
