'use client';

/**
 * PageShell Component
 * Enterprise FinTech Platform
 *
 * Provides instant skeleton rendering for progressive navigation.
 * Renders P0 content immediately while P1/P2/P3 load in the background.
 */

import React, { useState, useCallback, useRef, useEffect } from 'react';

type Priority = 0 | 1 | 2 | 3;

interface PrioritySectionProps {
  priority: Priority;
  children: React.ReactNode;
  fallback?: React.ReactNode;
  className?: string;
  onVisible?: () => void;
}

export function PrioritySection({
  priority,
  children,
  fallback,
  className = '',
  onVisible,
}: PrioritySectionProps) {
  const { isVisible, ref } = useIntersectionObserver(onVisible, priority === 3);

  if (priority === 0) {
    return <div className={`priority-p0 ${className}`}>{children}</div>;
  }

  return (
    <div ref={ref as React.Ref<HTMLDivElement>} className={`priority-p${priority} ${className}`}>
      {isVisible || priority < 3 ? (
        <SuspenseContent priority={priority} fallback={fallback}>
          {children}
        </SuspenseContent>
      ) : (
        fallback || DefaultSkeleton(priority)
      )}
    </div>
  );
}

function SuspenseContent({
  priority,
  fallback,
  children,
}: {
  priority: Priority;
  fallback?: React.ReactNode;
  children: React.ReactNode;
}) {
  const defaultFallback = DefaultSkeleton(priority);
  return (
    <React.Suspense fallback={fallback || defaultFallback}>
      {children}
    </React.Suspense>
  );
}

export function DefaultSkeleton(priority: Priority): React.ReactNode {
  switch (priority) {
    case 1:
      return (
        <div className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            {Array.from({ length: 4 }).map((_, i) => (
              <div key={i} className="animate-pulse rounded-xl border border-white/10 bg-white/5 p-5">
                <div className="h-4 w-1/2 rounded bg-white/10" />
                <div className="mt-3 h-8 w-3/4 rounded bg-white/10" />
              </div>
            ))}
          </div>
        </div>
      );
    case 2:
      return (
        <div className="animate-pulse rounded-xl border border-white/10 bg-white/5 p-6">
          <div className="h-6 w-1/3 rounded bg-white/10" />
          <div className="mt-4 h-64 w-full rounded bg-white/10" />
        </div>
      );
    case 3:
      return (
        <div className="animate-pulse rounded-lg border border-white/10 bg-white/5 p-4">
          <div className="h-3 w-1/3 rounded bg-white/10" />
        </div>
      );
    default:
      return null;
  }
}

function useIntersectionObserver(
  onVisible?: () => void,
  enabled = false
): { isVisible: boolean; ref: React.RefCallback<HTMLDivElement | null> } {
  const [isVisible, setIsVisible] = useState(!enabled);
  const ref = useCallback(
    (node: HTMLDivElement | null) => {
      if (!node || !enabled) return;
      const observer = new IntersectionObserver(
        ([entry]) => {
          if (entry.isIntersecting) {
            setIsVisible(true);
            onVisible?.();
            observer.disconnect();
          }
        },
        { rootMargin: '100px' }
      );
      observer.observe(node);
      return () => observer.disconnect();
    },
    [enabled, onVisible]
  );

  return { isVisible, ref };
}
