// SiteFooter — the canonical public-facing footer for marketing /
// docs / marketplace pages. NOT used inside the authenticated
// dashboard (that surface has its own compact app-chrome footer).
//
//   ┌──────────────────────────────────────────────────────────────┐
//   │ • hairline top highlight (primary tint)                      │
//   ├──────────────────────────────────────────────────────────────┤
//   │                                                              │
//   │  ┌────────────┐  ┌──────────┐ ┌──────────┐ ┌──────────┐     │
//   │  │ brand      │  │ Product  │ │ Docs     │ │ Company  │     │
//   │  │ tagline    │  │ Demo     │ │ Getting… │ │ About    │     │
//   │  │ social row │  │ Pricing  │ │ Plugins  │ │ Blog     │     │
//   │  │            │  │ Status   │ │ Reference│ │ Careers  │     │
//   │  └────────────┘  └──────────┘ └──────────┘ └──────────┘     │
//   │                                                              │
//   ├──────────────────────────────────────────────────────────────┤
//   │ © Year · brand          status badge · lang · theme         │
//   └──────────────────────────────────────────────────────────────┘
//
// Layout: data-driven via `brand`, `tagline`, `social`, `columns`,
// `bottomLeft`, `bottomRight`. All ReactNodes — apps inject their own
// router Link via the `LinkComponent` prop (consistent with DocsLayout
// / DocShell / AppShell pattern).

import type { ComponentType, ReactNode } from 'react'
import { cn } from '../cn'
import type { ShellLinkProps } from './docShell'

export interface SiteFooterLink {
  readonly label: ReactNode
  readonly href: string
  /** External links bypass the internal Link (router) so they navigate
   *  via plain <a>. Defaults to detecting `http:`/`https:` prefix in
   *  the href. */
  readonly external?: boolean
  /** Small label shown next to the link text (e.g. "new", "beta"). */
  readonly badge?: ReactNode
}

export interface SiteFooterColumn {
  /** Section heading — rendered as small uppercase tracking. */
  readonly title: ReactNode
  readonly links: ReadonlyArray<SiteFooterLink>
}

export interface SiteFooterSocial {
  /** Accessible label, e.g. "GitHub". */
  readonly label: string
  readonly href: string
  readonly icon: ReactNode
}

interface SiteFooterProps {
  /** Brand mark — usually a small wordmark + Badge. */
  readonly brand: ReactNode
  /** Short paragraph under the brand. ~2 lines of prose. */
  readonly tagline?: ReactNode
  /** Social / external profile links. Rendered as a row of 32×32
   *  icon buttons under the tagline. */
  readonly social?: ReadonlyArray<SiteFooterSocial>
  /** The column groups. 3 columns is the visual sweet spot; 4 fits
   *  but starts feeling busy. */
  readonly columns: ReadonlyArray<SiteFooterColumn>

  /** Bottom strip slots. Left typically holds the copyright; right
   *  holds status / language / theme toggle. When `bottomLeft` is
   *  omitted, a default `© {year} {copyrightHolder}` line renders. */
  readonly bottomLeft?: ReactNode
  readonly bottomRight?: ReactNode
  /** Copyright holder shown in the default bottom-left line (only when
   *  `bottomLeft` is not supplied). Default `'Voltro. Built on the
   *  framework.'`. Pass your own so the shipped footer isn't Voltro-
   *  branded. */
  readonly copyrightHolder?: ReactNode
  /** `aria-label` for the social-links list. Default `'Social links'`. */
  readonly socialLabel?: string

  /** Optional client-router Link. Same contract as the other kit
   *  compositions. Defaults to plain <a>. */
  readonly LinkComponent?: ComponentType<ShellLinkProps>

  readonly className?: string
}

const PlainLink = ({ to, className, children }: ShellLinkProps): ReactNode => (
  <a href={to} className={className}>{children}</a>
)

const isSchemed = (href: string): boolean => /^[a-z][a-z0-9+.-]*:\/\//i.test(href)

// FooterLink wraps the user's link with the right element: external
// → plain <a target="_blank">, internal → LinkComponent.
const FooterLink = ({
  link, Link,
}: {
  readonly link: SiteFooterLink
  readonly Link: ComponentType<ShellLinkProps>
}): ReactNode => {
  const external = link.external ?? isSchemed(link.href)
  const baseClass = 'inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors'
  if (external) {
    return (
      <a
        href={link.href}
        target="_blank"
        rel="noopener noreferrer"
        className={baseClass}
      >
        {link.label}
        {link.badge ? <FooterBadge>{link.badge}</FooterBadge> : null}
      </a>
    )
  }
  return (
    <Link to={link.href} className={baseClass}>
      {link.label}
      {link.badge ? <FooterBadge>{link.badge}</FooterBadge> : null}
    </Link>
  )
}

const FooterBadge = ({ children }: { children: ReactNode }): ReactNode => (
  <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[0.6rem] uppercase tracking-wider font-semibold bg-primary/10 text-primary">
    {children}
  </span>
)

export const SiteFooter = ({
  brand, tagline, social, columns,
  bottomLeft, bottomRight,
  copyrightHolder = 'Voltro. Built on the framework.',
  socialLabel = 'Social links',
  LinkComponent = PlainLink, className,
}: SiteFooterProps): ReactNode => {
  const Link = LinkComponent
  const year = new Date().getFullYear()
  // Default copyright when neither slot fills the bottom-left.
  const defaultLeft = (
    <span className="text-xs text-muted-foreground">
      © {year} {copyrightHolder}
    </span>
  )

  return (
    <footer
      className={cn(
        'relative border-t border-border',
        // Hairline highlight along the top — same language as bento
        // cells, ties the page chrome together.
        'before:absolute before:inset-x-0 before:top-0 before:h-px before:bg-gradient-to-r before:from-transparent before:via-primary/50 before:to-transparent',
        className,
      )}
    >
      <div className="mx-auto max-w-7xl px-6 py-14 lg:py-16">
        {/* ---- Main grid: brand + columns ---- */}
        <div className="grid grid-cols-2 md:grid-cols-12 gap-8 lg:gap-12">
          {/* Brand block — spans 4 columns on md, full width on mobile */}
          <div className="col-span-2 md:col-span-4 lg:col-span-5">
            <div className="text-base font-semibold text-foreground">{brand}</div>
            {tagline ? (
              <p className="mt-3 text-sm text-muted-foreground leading-relaxed max-w-xs">
                {tagline}
              </p>
            ) : null}
            {social && social.length > 0 ? (
              <ul className="mt-5 flex items-center gap-2" aria-label={socialLabel}>
                {social.map((s) => (
                  <li key={s.href}>
                    <a
                      href={s.href}
                      target="_blank"
                      rel="noopener noreferrer"
                      aria-label={s.label}
                      className="inline-flex items-center justify-center w-8 h-8 rounded-md text-muted-foreground hover:text-foreground hover:bg-card transition-colors [&_svg]:w-4 [&_svg]:h-4"
                    >
                      {s.icon}
                    </a>
                  </li>
                ))}
              </ul>
            ) : null}
          </div>

          {/* Link columns. Each column takes equal slice of the
           * remaining 8 cols on md (12-col grid). On mobile they
           * stack into the 2-col grid below the brand. */}
          {columns.map((col, i) => (
            <div
              key={i}
              className={cn(
                'col-span-1',
                // 3 cols → md:col-span-2 (so 3 × 2 + brand 4 = 10, leaves room)
                // Use lg:col-span-2 for tighter packing on big screens.
                columns.length === 3 ? 'md:col-span-2 lg:col-span-2' : 'md:col-span-2',
              )}
            >
              <h3 className="text-xs uppercase tracking-[0.08em] text-muted-foreground font-semibold mb-4">
                {col.title}
              </h3>
              <ul className="space-y-2.5">
                {col.links.map((link, j) => (
                  <li key={j}>
                    <FooterLink link={link} Link={Link} />
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>

        {/* ---- Bottom strip ---- */}
        <div className="mt-12 lg:mt-16 pt-6 border-t border-border flex flex-col-reverse sm:flex-row items-start sm:items-center justify-between gap-4">
          <div>{bottomLeft ?? defaultLeft}</div>
          {bottomRight ? <div className="flex items-center gap-3">{bottomRight}</div> : null}
        </div>
      </div>
    </footer>
  )
}

// ---- StatusBadge — handy bottom-right slot piece ----
// Solid green dot + "All systems operational" style label. Drop into
// `bottomRight` when the app has a real status URL to link to.

interface StatusBadgeProps {
  readonly href: string
  readonly label?: ReactNode
  /** `'ok' | 'degraded' | 'down'` — colours the dot accordingly. */
  readonly tone?: 'ok' | 'degraded' | 'down'
}

const STATUS_DOT: Record<NonNullable<StatusBadgeProps['tone']>, string> = {
  ok:       'bg-success shadow-[0_0_8px_2px_oklch(0.7_0.15_162_/_0.5)]',
  degraded: 'bg-warning shadow-[0_0_8px_2px_oklch(0.78_0.18_70_/_0.5)]',
  down:     'bg-destructive shadow-[0_0_8px_2px_oklch(0.7_0.19_22_/_0.5)]',
}

export const StatusBadge = ({
  href, label = 'All systems operational', tone = 'ok',
}: StatusBadgeProps): ReactNode => (
  <a
    href={href}
    target="_blank"
    rel="noopener noreferrer"
    className="inline-flex items-center gap-2 text-xs text-muted-foreground hover:text-foreground transition-colors"
  >
    <span className={cn('w-1.5 h-1.5 rounded-full motion-safe:animate-pulse', STATUS_DOT[tone])} aria-hidden="true" />
    {label}
  </a>
)
