import Link from 'next/link';
import NewsletterSignup from '@/components/ui/NewsletterSignup';
import { getNavigation } from '@/lib/shopware-api';
import { getServerSnippets } from '@/lib/server-snippets';

type NavItem = {
  id: string;
  name: string;
  type: string; // 'folder' | 'page' | 'link'
  url: string;
  externalLink?: string;
  newTab?: boolean;
  children: NavItem[];
};

function mapNavItem(cat: any): NavItem {
  return {
    id: cat.id,
    name: cat.translated?.name ?? cat.name ?? '',
    type: cat.type ?? 'page',
    url: cat.externalLink || `/category/${cat.id}`,
    externalLink: cat.externalLink,
    newTab: cat.linkNewTab ?? false,
    children: Array.isArray(cat.children) ? cat.children.map(mapNavItem) : [],
  };
}

async function loadFooterNav(type: string, depth: number): Promise<NavItem[]> {
  try {
    const res = await getNavigation(type, depth);
    const items: any[] = Array.isArray(res) ? res : [];
    if (items.length === 0) return [];

    // Case A: Shopware returned the root folder itself as the only item — unwrap its children
    if (items.length === 1 && Array.isArray(items[0]?.children) && items[0].children.length > 0) {
      return items[0].children.map(mapNavItem);
    }

    // Case B: Shopware returned a flat list (no nesting) — build tree from parentId
    const hasChildren = items.some((i: any) => Array.isArray(i.children) && i.children.length > 0);
    if (!hasChildren && items.some((i: any) => i.parentId)) {
      const byId = new Map(items.map((i: any) => [i.id, { ...i, children: [] as any[] }]));
      const roots: any[] = [];
      for (const item of byId.values()) {
        const parent = byId.get(item.parentId);
        if (parent) parent.children.push(item);
        else roots.push(item);
      }
      // If single root (the Footer folder), return its children; else return roots
      if (roots.length === 1 && roots[0].children.length > 0) return roots[0].children.map(mapNavItem);
      return roots.map(mapNavItem);
    }

    return items.map(mapNavItem);
  } catch (err) {
    console.error(`[Footer:${type}] error:`, err);
    return [];
  }
}

export default async function Footer() {
  const storeName = process.env.NEXT_PUBLIC_STORE_NAME || 'ReactWare';

  // Fetch nav + Shopware snippet set for the active locale in parallel.
  const [footerNav, serviceNav, { t }] = await Promise.all([
    loadFooterNav('footer-navigation', 3),
    loadFooterNav('service-navigation', 1),
    getServerSnippets(),
  ]);

  // Shopware's snippets may contain HTML (e.g. an <a> wrapping the %url%
  // placeholder), so we render them via dangerouslySetInnerHTML for parity
  // with twig's |raw filter.
  const contactHref = '/contact';
  const serviceContactHtml = t(
    'footer.serviceContactText',
    `Or via our <a class="footer-link" href="${contactHref}">contact form</a>.`
  ).replace(/%url%/g, contactHref);

  const shippingHref = '/shipping-info';
  // Pick include/exclude based on tax state — Shopware uses two distinct keys.
  // Default to the gross/include text; if you wire tax state through, swap key.
  const vatHtml = t(
    'footer.includeVatText')
    .replace(/%url%/g, shippingHref)
    .replace(/%star%/g, '* ');

  return (
    <footer className="bg-surface-950 text-surface-400">
      <div className="max-w-7xl mx-auto px-6 py-12">

        <div className="grid grid-cols-2 md:grid-cols-4 gap-8 mb-10">

          <div className="col-span-2 md:col-span-1">
            <p className="text-white font-bold text-lg mb-4">⚡ {storeName}</p>
            <p className="text-sm font-semibold text-white mb-1">
              {t('footer.serviceHotlineHeadline', 'Service hotline')}
            </p>
            <p
              className="text-sm mb-3"
              dangerouslySetInnerHTML={{
                __html: t(
                  'footer.serviceHotline',
                  'Support and counselling via:<br><strong>0180 - 000000</strong><br>Mon–Fri, 9 am – 5 pm'
                ),
              }}
            />
            <p
              className="text-sm [&_a]:text-brand-400 [&_a:hover]:text-brand-300 [&_a]:underline"
              dangerouslySetInnerHTML={{ __html: serviceContactHtml }}
            />
          </div>

          {footerNav.length > 0 ? (
            footerNav.map((root) => (
              <div key={root.id}>
                <div className="text-white font-semibold text-sm uppercase tracking-wider mb-3">
                  {root.type === 'folder' ? (
                    root.name
                  ) : (
                    <Link
                      href={root.url}
                      target={root.newTab ? '_blank' : undefined}
                      className="hover:text-surface-300 transition-colors"
                    >
                      {root.name}
                    </Link>
                  )}
                </div>

                {root.children.length > 0 && (
                  <ul className="space-y-2 text-sm">
                    {root.children.map((child) => (
                      <li key={child.id}>
                        {child.type === 'folder' ? (
                          <span className="text-surface-400">{child.name}</span>
                        ) : (
                          <Link
                            href={child.url}
                            target={child.newTab ? '_blank' : undefined}
                            className="text-surface-300 hover:text-white transition-colors"
                          >
                            {child.name}
                          </Link>
                        )}
                      </li>
                    ))}
                  </ul>
                )}
              </div>
            ))
          ) : (
            <div>
              <div className="text-white font-semibold text-sm uppercase tracking-wider mb-3">Info</div>
              <ul className="space-y-2 text-sm">
                <li><Link href="/contact" className="text-surface-300 hover:text-white transition-colors">Contact</Link></li>
              </ul>
            </div>
          )}

          <div>
            <NewsletterSignup />
          </div>
        </div>

        <div className="border-t border-surface-800 pt-6">
          <div className="flex flex-col sm:flex-row items-center justify-between gap-4 text-xs">

            {serviceNav.length > 0 && (
              <ul className="flex flex-wrap gap-4">
                {serviceNav.map((item) => (
                  <li key={item.id}>
                    <Link
                      href={item.url}
                      target={item.newTab ? '_blank' : undefined}
                      className="text-surface-400 hover:text-white transition-colors"
                    >
                      {item.name}
                    </Link>
                  </li>
                ))}
              </ul>
            )}

            <div className="text-surface-400 text-center sm:text-right space-y-1 [&_a]:text-surface-300 [&_a:hover]:text-white [&_a]:underline">
              <p dangerouslySetInnerHTML={{ __html: vatHtml }} />
              <p>
                © {new Date().getFullYear()} {storeName}.{' '}
                {t('footer.copyrightInfo', 'Powered by Shopware 6 Headless.')}
              </p>
            </div>
          </div>
        </div>

      </div>
    </footer>
  );
}
