import { useEffect, useRef, useState } from "react";
import { getBlockComponent } from "@/components/page-blocks";
import { resolvePreviewContent } from "@/lib/contentPlaceholders";
import { ComponentPreviewBySlug } from "../pages/ComponentPreviews";
import type { ComponentRecord } from "../types";

type ComponentPreviewMiniProps = {
  component: ComponentRecord;
  scale?: number;
  maxHeight?: number;
  /** When true, render immediately (e.g. detail modal). */
  eager?: boolean;
};

function extractDescription(content: Record<string, unknown> | null): string | null {
  if (!content) return null;
  const keys = ["subtitle", "heading", "description", "story", "title"];
  for (const key of keys) {
    const value = content[key];
    if (typeof value === "string" && value.trim()) {
      return value.trim().length > 140 ? `${value.trim().slice(0, 137)}…` : value.trim();
    }
  }
  return null;
}

export function getComponentDescription(component: ComponentRecord): string | null {
  return extractDescription(component.content);
}

export default function ComponentPreviewMini({
  component,
  scale = 0.32,
  maxHeight = 148,
  eager = false,
}: ComponentPreviewMiniProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [isVisible, setIsVisible] = useState(eager);

  useEffect(() => {
    if (eager) return;
    const node = containerRef.current;
    if (!node) return;

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry?.isIntersecting) {
          setIsVisible(true);
          observer.disconnect();
        }
      },
      { rootMargin: "120px" },
    );

    observer.observe(node);
    return () => observer.disconnect();
  }, [eager]);

  const BlockComp = getBlockComponent(component.slug);
  const content = resolvePreviewContent((component.content ?? {}) as Record<string, unknown>, {
    blockSlug: component.slug,
  });

  return (
    <div
      ref={containerRef}
      style={{
        position: "relative",
        height: maxHeight,
        overflow: "hidden",
        background: "#f8fafc",
        borderRadius: 8,
        border: "1px solid #e2e8f0",
      }}
      aria-hidden
    >
      {!isVisible ? (
        <div
          style={{
            position: "absolute",
            inset: 0,
            background: "linear-gradient(90deg, #f1f5f9 0%, #e2e8f0 50%, #f1f5f9 100%)",
            backgroundSize: "200% 100%",
            animation: "component-preview-shimmer 1.4s ease infinite",
          }}
        />
      ) : BlockComp ? (
        <div
          style={{
            transform: `scale(${scale})`,
            transformOrigin: "top left",
            width: `${100 / scale}%`,
            pointerEvents: "none",
            userSelect: "none",
          }}
        >
          <BlockComp content={content} />
        </div>
      ) : (
        <div style={{ padding: 12, height: "100%", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <ComponentPreviewBySlug slug={component.slug} content={content} />
        </div>
      )}
    </div>
  );
}
