'use client';

import React, { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import { FooterSettings, FooterColumnSetting } from '@/lib/settings';
import { Category } from '@/types/woocommerce';

interface FooterProps {
  settings?: FooterSettings;
  brandName?: string;
  categories?: Category[];
}

const I = {
  pin: (
    <svg className="ic" viewBox="0 0 24 24">
      <path d="M12 21s-7-6.2-7-11a7 7 0 0 1 14 0c0 4.8-7 11-7 11z" />
      <circle cx="12" cy="10" r="2.5" />
    </svg>
  ),
  phone: (
    <svg className="ic" viewBox="0 0 24 24">
      <path d="M5 4h4l2 5-2.5 1.5a12 12 0 0 0 5 5L15 13l5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2z" />
    </svg>
  ),
  mail: (
    <svg className="ic" viewBox="0 0 24 24">
      <path d="M4 5h16v14H4z" />
      <path d="M4 7l8 6 8-6" />
    </svg>
  ),
  clock: (
    <svg className="ic" viewBox="0 0 24 24">
      <circle cx="12" cy="12" r="8" />
      <path d="M12 8v4l3 2" />
    </svg>
  ),
  fb: (
    <svg className="ic" viewBox="0 0 24 24">
      <path d="M15 8h-2a2 2 0 0 0-2 2v11M8 13h6" />
    </svg>
  ),
  ig: (
    <svg className="ic" viewBox="0 0 24 24">
      <rect x="4" y="4" width="16" height="16" rx="5" />
      <circle cx="12" cy="12" r="3.5" />
    </svg>
  ),
  yt: (
    <svg className="ic" viewBox="0 0 24 24">
      <rect x="3" y="6" width="18" height="12" rx="4" />
      <path d="M10 9.5v5l4-2.5z" />
    </svg>
  ),
};

export default function Footer({ settings, brandName = 'Hayat Supplements', categories = [] }: FooterProps) {
  const [logoError, setLogoError] = useState(false);
  const logoRef = useRef<HTMLImageElement>(null);

  // Catch images that failed before hydration attached onError
  useEffect(() => {
    const img = logoRef.current;
    if (img && img.complete && img.naturalWidth === 0) setLogoError(true);
  });

  const tagline =
    settings?.about_text ||
    'খাঁটি মধু, ভেষজ, বাদাম ও প্রিমিয়াম ঘি — নিরাপদ ও ভেজালমুক্ত খাবার, প্রতিটি ঘরের জন্য।';
  const address = settings?.address || 'ঢাকা, বাংলাদেশ';
  const phone = settings?.phone || '';
  const email = settings?.email || '';
  const hours = settings?.hours || 'প্রতিদিন সকাল ১০টা – রাত ১০টা';
  const copyright = settings?.copyright || `© 2026 ${brandName}`;

  const facebookUrl = settings?.facebook || '';
  const instagramUrl = settings?.instagram || '';
  const youtubeUrl = settings?.youtube || '';

  const rawLogo = settings?.logo_url?.trim();
  // Only render an <img> when the plugin provides a logo URL; otherwise show the brand name as text.
  const logoUrl =
    !logoError && rawLogo
      ? rawLogo.startsWith('http://') || rawLogo.startsWith('https://') || rawLogo.startsWith('/')
        ? rawLogo
        : `/images/${rawLogo}`
      : '';

  // Default columns (plugin-driven when configured)
  const shopLinks =
    categories.length > 0
      ? [
          { label: 'All products', url: '/shop', enabled: true },
          ...categories
            .slice(0, 5)
            .map((c) => ({ label: c.name, url: `/category/${c.slug}`, enabled: true })),
        ]
      : [
          { label: 'All products', url: '/shop', enabled: true },
          { label: 'Track order', url: '/track-order', enabled: true },
          { label: 'Contact', url: '/contact', enabled: true },
        ];

  const defaultColumns: FooterColumnSetting[] = [
    { title: 'Shop', links: shopLinks },
    {
      title: 'Help',
      links: [
        { label: 'Shipping', url: '/shipping', enabled: true },
        { label: 'Contact', url: '/contact', enabled: true },
        { label: 'Privacy & terms', url: '/policies', enabled: true },
      ],
    },
    {
      title: 'Company',
      links: [
        { label: 'About us', url: '/about', enabled: true },
        { label: 'Our brands', url: '/brands', enabled: true },
        { label: 'How we price', url: '/pricing', enabled: true },
      ],
    },
  ];

  const columns =
    settings?.columns && settings.columns.length > 0 ? settings.columns : defaultColumns;

  return (
    <footer className="ftr" role="contentinfo">
      <div className="wrap">
        <div className="fgrid2">
          {/* Brand column */}
          <div className="fbrand">
            <Link href="/" aria-label={`${brandName} হোম`}>
              {logoUrl ? (
                <img
                  ref={logoRef}
                  src={logoUrl}
                  alt={brandName}
                  style={{ height: '58px', width: 'auto' }}
                  onError={() => setLogoError(true)}
                />
              ) : (
                <span style={{ fontWeight: 700, fontSize: '22px', color: '#fff' }}>
                  {brandName}
                </span>
              )}
            </Link>
            <p>{tagline}</p>
            <div>
              {I.pin}
              <span>{address}</span>
            </div>
            {phone && (
              <div>
                {I.phone}
                <a href={`tel:${phone.replace(/[^0-9+]/g, '')}`}>{phone}</a>
              </div>
            )}
            {email && (
              <div>
                {I.mail}
                <a href={`mailto:${email}`}>{email}</a>
              </div>
            )}
            <div>
              {I.clock}
              <span>{hours}</span>
            </div>
            <div className="soc" aria-label="Social media links">
              {facebookUrl && (
                <a href={facebookUrl} target="_blank" rel="noopener noreferrer" aria-label="Facebook">
                  {I.fb}
                </a>
              )}
              {instagramUrl && (
                <a href={instagramUrl} target="_blank" rel="noopener noreferrer" aria-label="Instagram">
                  {I.ig}
                </a>
              )}
              {youtubeUrl && (
                <a href={youtubeUrl} target="_blank" rel="noopener noreferrer" aria-label="YouTube">
                  {I.yt}
                </a>
              )}
            </div>
          </div>

          {/* Link columns */}
          <div className="flinks">
            {columns.map((col, idx) => (
              <div key={idx}>
                <h4>{col.title}</h4>
                <ul>
                  {col.links
                    .filter((lnk) => lnk.enabled !== false)
                    .map((lnk, lIdx) => (
                      <li key={lIdx}>
                        <Link href={lnk.url}>{lnk.label}</Link>
                      </li>
                    ))}
                </ul>
              </div>
            ))}
          </div>
        </div>

        {/* Payment badges */}
        <div className="fpay">
          {settings?.payment_logo ? (
            <img
              src={settings.payment_logo}
              alt="Payment methods"
              className="payimg"
              loading="lazy"
            />
          ) : (
            <div className="pays" aria-label="Payment methods">
              <span>bKash</span>
              <span>Nagad</span>
              <span>Rocket</span>
              <span>COD</span>
              <span>Visa</span>
              <span>Mastercard</span>
            </div>
          )}
        </div>

        <div className="fbot">
          <span>{copyright}</span>
        </div>
      </div>
    </footer>
  );
}
