"use client";

import { useAppSelector } from "@/store/hooks";
import { selectHomeSections } from "@/store/slices/homeSlice";
import type { Section } from "@/types/api/section.types";

// ── Type 1: Article — layout-driven ──────────────────────────────────────────
import LatestNewsSection from "./LatestNewsSection";
import TrendingSection from "./TrendingSection";
import ListenSection from "./ListenSection";
import ArticleLandscapeSection from "./ArticleLandscapeSection";
import ArticleSmallLandscapeSection from "./ArticleSmallLandscapeSection";
import ArticleSquareSection from "./ArticleSquareSection";
import ArticlePortraitSection from "./ArticlePortraitSection";

// ── Type 2–10: Dedicated components ──────────────────────────────────────────
import LiveNewsSection from "./LiveNewsSection";
import ShowsSectionDynamic from "./ShowsSectionDynamic";
import StorySection from "./StorySection";
import HeadLineSection from "./HeadLineSection";
import OpinionPollSection from "./OpinionPollSection";
import CategoryGridSection from "./CategoryGridSection";
import LiveTVSection from "./LiveTVSection";
import HashTagSection from "./HashTagSection";
import Link from "next/link";
import { usePermission } from "@/hooks/usePermission";

// ── Premium section overlay ───────────────────────────────────────────────────
function SectionPremiumOverlay({
  section,
  children,
}: {
  section: Section;
  children: React.ReactNode;
}) {
  const { isPremium, isGuest } = usePermission();

  // No gating needed
  if (section.is_premium !== 1 || isPremium) return <>{children}</>;

  return (
    <div style={{ position: "relative" }}>
      {/* Blurred section content */}
      <div
        style={{
          filter: "blur(5px)",
          pointerEvents: "none",
          userSelect: "none",
        }}
      >
        {children}
      </div>

      {/* Premium CTA overlay */}
      <div
        style={{
          position: "absolute",
          inset: 0,
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
          gap: "0.75rem",
          background:
            "linear-gradient(to top, rgba(255,255,255,0.96) 35%, rgba(255,255,255,0.6) 100%)",
          padding: "1.5rem",
          textAlign: "center",
        }}
      >
        <div
          style={{
            width: 48,
            height: 48,
            borderRadius: "50%",
            background: "rgba(193,39,45,0.08)",
            border: "1.5px solid rgba(193,39,45,0.2)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <svg
            width="22"
            height="22"
            viewBox="0 0 24 24"
            fill="none"
            stroke="var(--brand, #C1272D)"
            strokeWidth="2"
            strokeLinecap="round"
          >
            <rect x="3" y="11" width="18" height="11" rx="2" />
            <path d="M7 11V7a5 5 0 0 1 10 0v4" />
          </svg>
        </div>

        <div>
          <p
            style={{
              fontWeight: 800,
              fontSize: "0.9375rem",
              color: "var(--ink, #0e0e11)",
              margin: "0 0 0.25rem",
            }}
          >
            Premium Content
          </p>
          <p
            style={{
              fontSize: "0.8125rem",
              color: "var(--text-2, #6b7280)",
              margin: 0,
            }}
          >
            {isGuest
              ? "Sign in to view this section"
              : "Subscribe to unlock all premium sections"}
          </p>
        </div>

        <Link
          href={isGuest ? "/login" : "/subscribe"}
          style={{
            display: "inline-flex",
            alignItems: "center",
            gap: "0.375rem",
            padding: "0.5625rem 1.375rem",
            background: "var(--brand, #C1272D)",
            color: "#fff",
            borderRadius: 8,
            fontWeight: 700,
            fontSize: "0.875rem",
            textDecoration: "none",
          }}
        >
          {isGuest ? "Sign in" : "Subscribe"}
          <svg
            width="14"
            height="14"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2.5"
          >
            <path d="M5 12h14M13 6l6 6-6 6" />
          </svg>
        </Link>
      </div>
    </div>
  );
}

interface Props {
  locale: string;
}

/**
 * Routes each section from the API by:
 *   1. section.type   — determines the content category
 *   2. section.screen_layout — determines how it is displayed
 *
 * Sections are rendered in sort_order from the API.
 * Empty data sections (data.length === 0) are skipped.
 */
function renderSection(section: Section, locale: string) {
  const hasData = section.data.length > 0;

  switch (section.type) {
    // ── Type 1: Article ───────────────────────────────────────────────────────
    // Note: list_view, small_portrait, portrait have built-in static fallbacks,
    // so they render even when section.data is empty.
    case 1: {
      switch (section.screen_layout) {
        case "list_view":
          return (
            <LatestNewsSection
              key={section.id}
              section={section}
              locale={locale}
            />
          );

        case "small_portrait":
          return (
            <TrendingSection
              key={section.id}
              section={section}
              locale={locale}
            />
          );

        case "portrait":
          // article_type === 3 → audio/podcast content → ListenSection
          // otherwise → standard portrait card grid
          return section.article_type === 3 ? (
            <ListenSection key={section.id} section={section} locale={locale} />
          ) : (
            <ArticlePortraitSection
              key={section.id}
              section={section}
              locale={locale}
            />
          );

        case "landscape":
          if (!hasData) return null;
          return (
            <ArticleLandscapeSection
              key={section.id}
              section={section}
              locale={locale}
            />
          );

        case "small_landscape":
          if (!hasData) return null;
          return (
            <ArticleSmallLandscapeSection
              key={section.id}
              section={section}
              locale={locale}
            />
          );

        case "square":
          if (!hasData) return null;
          return (
            <ArticleSquareSection
              key={section.id}
              section={section}
              locale={locale}
            />
          );

        default:
          return (
            <LatestNewsSection
              key={section.id}
              section={section}
              locale={locale}
            />
          );
      }
    }

    // ── Type 2: Live News ─────────────────────────────────────────────────────
    case 2:
      if (!hasData) return null;
      return (
        <LiveNewsSection key={section.id} section={section} locale={locale} />
      );

    // ── Type 3: Shows ─────────────────────────────────────────────────────────
    case 3:
      if (!hasData) return null;
      return (
        <ShowsSectionDynamic
          key={section.id}
          section={section}
          locale={locale}
        />
      );

    // ── Type 4: Story ─────────────────────────────────────────────────────────
    case 4:
      if (!hasData) return null;
      return (
        <StorySection key={section.id} section={section} locale={locale} />
      );

    // ── Type 5: HeadLine ──────────────────────────────────────────────────────
    case 5:
      if (!hasData) return null;
      return (
        <HeadLineSection key={section.id} section={section} locale={locale} />
      );

    // ── Type 6: Opinion Poll ──────────────────────────────────────────────────
    case 6:
      if (!hasData) return null;
      return (
        <OpinionPollSection
          key={section.id}
          section={section}
          locale={locale}
        />
      );

    // ── Type 7: Category ──────────────────────────────────────────────────────
    case 7:
      if (!hasData) return null;
      return (
        <CategoryGridSection
          key={section.id}
          section={section}
          locale={locale}
        />
      );

    // ── Type 8: Language — skip on web ────────────────────────────────────────
    case 8:
      return null;

    // ── Type 9: Channel / Live TV ─────────────────────────────────────────────
    case 9:
      if (!hasData) return null;
      return (
        <LiveTVSection key={section.id} section={section} locale={locale} />
      );

    // ── Type 10: HashTag ──────────────────────────────────────────────────────
    case 10:
      if (!hasData) return null;
      return (
        <HashTagSection key={section.id} section={section} locale={locale} />
      );

    default:
      return null;
  }
}

export default function SectionRenderer({ locale }: Props) {
  const sections = useAppSelector(selectHomeSections);
  if (!sections.length) return null;

  return (
    <>
      {sections
        .slice()
        .sort((a, b) => a.sort_order - b.sort_order)
        .map((section) => {
          const rendered = renderSection(section, locale);
          if (!rendered) return null;
          // Wrap premium sections with access gate
          return (
            <SectionPremiumOverlay key={section.id} section={section}>
              {rendered}
            </SectionPremiumOverlay>
          );
        })}
    </>
  );
}
