/**
 * SharedReport Layout — outer chrome for the public-report surface.
 *
 * Used by `View`, `PasswordRequired`, and `Expired` so all three pages share
 * the same hairline-grid backdrop, the same theme + branding handling, the
 * same top strip and footer. The pages stay thin and only own their middle
 * content slot.
 *
 * White-label rules (single source of truth):
 *   - When `branding.remove_rankwiz_branding === true`, every "RankWizAI"
 *     surface (header logo, footer mention, free-trial CTA) is hidden.
 *   - The agency's logo or company name takes its place in the header.
 *   - Brand colors are injected as CSS custom properties via BrandThemeRoot.
 *
 * The brief was explicit on the second point: white-labeled reports should
 * have *zero* RankWizAI mentions. Default-branded reports keep them.
 */
import { type ReactNode } from 'react';

import { Link } from '@inertiajs/react';

import { Logo, TextLogo } from '@/Components/branding/Logo';
import { BrandThemeRoot } from '@/Components/SharedReport/BrandThemeRoot';
import { CopyLinkButton } from '@/Components/SharedReport/CopyLinkButton';
import { ThemeToggle } from '@/Components/theme';
import { trackProductEvent } from '@/lib/analytics';
import { isSafeHex } from '@/lib/branding';
import { CTA_CLICKED } from '@/lib/event-catalog';
import { cn } from '@/lib/utils';
import { type Branding } from '@/types';

interface SharedReportLayoutProps {
  /**
   * Optional eyebrow text shown in the top strip on the left, in monospace
   * uppercase tracking. Used by View to show the client/site name + period.
   */
  eyebrow?: ReactNode;
  /**
   * Branding data from the controller. When `remove_rankwiz_branding` is
   * true, the layout fully white-labels (no RankWizAI mention anywhere).
   */
  branding: Branding | null | undefined;
  /**
   * Show the "Copy link" button in the top strip. Off by default — the
   * password-required and expired pages don't need it.
   */
  showCopyLink?: boolean;
  /**
   * Override the date text shown in the footer ("Generated …"). When omitted,
   * the footer renders without the date line.
   */
  generatedAt?: string | null;
  children: ReactNode;
}

export function SharedReportLayout({
  eyebrow,
  branding,
  showCopyLink = false,
  generatedAt,
  children,
}: SharedReportLayoutProps) {
  const whiteLabel = Boolean(branding?.remove_rankwiz_branding);
  const companyName = branding?.company_name ?? null;

  // The controller passes `logo_url` only when `logo_path` is set on the row.
  // When white-label is on AND a logo exists, render it instead of the agency
  // name. The TextLogo / Logo (RankWizAI mark) is reserved for non-white-label.
  const brandLogoUrl = branding?.logo_url ?? null;
  const useBrandLogoImage = whiteLabel && brandLogoUrl !== null;
  const useBrandTextOnly = whiteLabel && !useBrandLogoImage;

  // Accent inline only when WL + safe primary color. Non-WL reports use the
  // default theme — a corrupt primary_color value falls through cleanly.
  const safeAccent =
    whiteLabel && isSafeHex(branding?.primary_color) ? branding!.primary_color : null;

  return (
    <BrandThemeRoot branding={branding}>
      {/* Hairline-grid backdrop — sits behind the whole page, fades behind content
          and is hidden in print so the PDF doesn't ship grid lines. */}
      <div
        aria-hidden="true"
        className="bg-grid-hair pointer-events-none fixed inset-0 -z-0 opacity-30 print:hidden"
      />
      <div className="relative z-10 flex min-h-screen flex-col">
        {/* Skip-to-main: keyboard users land on the report body without
            tabbing through the header strip (logo, copy-link, theme toggle).
            sr-only by default; visible on focus. (F-A11Y-15) */}
        <a
          href="#shared-report-main"
          className="sr-only focus:not-sr-only focus:absolute focus:top-4 focus:left-4 focus:z-50 focus:px-4 focus:py-2 focus:bg-background focus:text-foreground focus:border focus:border-border focus:rounded-md focus:outline-none focus:ring-2 focus:ring-ring"
        >
          Skip to report
        </a>
        <header className="border-b border-border bg-background/80 backdrop-blur supports-[backdrop-filter]:bg-background/60 print:border-0 print:bg-transparent print:backdrop-blur-none">
          <div className="container mx-auto flex flex-wrap items-center justify-between gap-3 px-4 py-4 sm:gap-6">
            <div className="flex min-w-0 items-center gap-3 sm:gap-4">
              {useBrandLogoImage ? (
                <img
                  src={brandLogoUrl ?? undefined}
                  alt={companyName ?? 'Brand logo'}
                  className="h-7 max-w-[160px] object-contain sm:h-8 sm:max-w-[200px]"
                />
              ) : useBrandTextOnly ? (
                <span
                  className="truncate text-base font-semibold tracking-tight sm:text-lg"
                  style={safeAccent ? { color: safeAccent } : undefined}
                >
                  {companyName ?? 'Report'}
                </span>
              ) : (
                <Link
                  href="/"
                  className="flex items-center gap-3 transition-opacity hover:opacity-80"
                  aria-label="RankWizAI home"
                >
                  <Logo size="md" />
                  <TextLogo size="md" className="font-bold" />
                </Link>
              )}

              {eyebrow && (
                <div
                  className={cn(
                    'hidden truncate border-l border-border pl-3 text-xs uppercase tracking-[0.18em] text-muted-foreground sm:block sm:pl-4',
                    'font-data',
                  )}
                >
                  {eyebrow}
                </div>
              )}
            </div>

            <div className="no-print flex items-center gap-1 sm:gap-2">
              {showCopyLink && <CopyLinkButton />}
              <ThemeToggle />
            </div>
          </div>

          {/* Mobile-only eyebrow row — too long to fit in the 375px header strip. */}
          {eyebrow && (
            <div className="container mx-auto px-4 pb-3 sm:hidden">
              <div className="font-data truncate text-[0.6875rem] uppercase tracking-[0.18em] text-muted-foreground">
                {eyebrow}
              </div>
            </div>
          )}
        </header>

        <main
          id="shared-report-main"
          className="container mx-auto flex-1 px-4 py-8 sm:py-12 print:py-0"
        >
          {children}
        </main>

        <footer className="border-t border-border bg-card/60 print:border-0 print:bg-transparent">
          <div className="container mx-auto flex flex-col items-center gap-2 px-4 py-8 text-center sm:gap-3">
            {generatedAt && (
              <p className="font-data text-[0.6875rem] uppercase tracking-[0.18em] text-muted-foreground">
                Generated {generatedAt}
              </p>
            )}

            {whiteLabel ? (
              // Full white-label: zero RankWizAI mention, per the brief. The
              // agency owns this surface end-to-end on this plan.
              companyName && (
                <p className="text-sm text-muted-foreground">
                  Powered by <span className="font-medium text-foreground">{companyName}</span>
                </p>
              )
            ) : (
              // Default-branded: a single, quiet RankWizAI mention in the
              // footer. Clicking it fires the tracked CTA — no separate
              // "Try RankWizAI Free" link here. The visible CTA lives in the
              // inline soft-banner above the report body so we don't dilute
              // attribution into two places.
              <p className="text-sm text-muted-foreground">
                Generated by{' '}
                <Link
                  href="/"
                  className="font-semibold text-foreground hover:underline"
                  onClick={() =>
                    trackProductEvent(CTA_CLICKED, {
                      cta_text: 'RankWizAI',
                      cta_location: 'shared_report_footer',
                    })
                  }
                >
                  RankWizAI
                </Link>
              </p>
            )}
          </div>
        </footer>
      </div>
    </BrandThemeRoot>
  );
}
