"use client";

import { Datepicker } from "@/components/datepicker/datepicker";
import { getPlatformIcon } from "@/components/icons";
import { AreaLineChart, SocialPieChart } from "@/components/dashboard/charts";
import { PageHeader } from "@/components/layout";
import { EmptyState } from "@/components/shared/empty-state";
import { ProjectInfoCard } from "@/components/dashboard/projects/project-info-card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { MultiSelect, type MultiSelectOption } from "@/components/ui/multi-select";
import { Skeleton } from "@/components/ui/skeleton";
import { Label } from "@/components/ui/label";
import { useProject } from "@/contexts/project-context";
import { useFormattedDate } from "@/hooks/use-formatted-date";
import { useIsMobile } from "@/hooks/use-mobile";
import { useThemeColors } from "@/hooks/use-theme-colors";
import {
  useSocialMediaReport,
  useSocialMediaReportActions,
} from "@/hooks/use-social-media";
import { formatDateToYMD, type Locale } from "@/lib/date-utils";
import { cn } from "@/lib/utils";
import {
  Bar,
  BarChart,
  CartesianGrid,
  ResponsiveContainer,
  Tooltip as RechartsTooltip,
  XAxis,
  YAxis,
} from "recharts";
import {
  buildSocialMediaReportAccountOptions,
  resolveSocialMediaAssetUrl,
} from "./social-media-report-utils";
import type {
  SocialMediaReportAccountItem,
  SocialMediaReportAccountType,
  SocialMediaReportFilters,
  SocialMediaReportPreset,
  SocialMediaReportSort,
  SocialPlatform,
} from "@/types";
import {
  Check,
  Download,
  FileText,
  Filter,
  Heart,
  Layers,
  MessageCircle,
  Pencil,
  Share2,
  Eye,
  Printer,
  ChevronDown,
  Calendar,
} from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import { useCallback, useEffect, useMemo, useState } from "react";

type TranslationFn = ReturnType<typeof useTranslations>;
type ReportPeriod = SocialMediaReportPreset | "custom";

interface ReportFilterState {
  preset: ReportPeriod;
  from: Date | null;
  to: Date | null;
  platforms: SocialPlatform[];
  accounts: string[];
  accountType: SocialMediaReportAccountType;
  sort: SocialMediaReportSort;
}

const PLATFORM_VALUES: SocialPlatform[] = [
  "facebook",
  "instagram",
  "twitter",
  "linkedin",
  "youtube",
  "snapchat",
  "tiktok",
];

function toLocalNoon(value: Date) {
  const date = new Date(value);
  date.setHours(12, 0, 0, 0);
  return date;
}

function resolvePresetRange(preset: SocialMediaReportPreset, now = new Date()) {
  const to = toLocalNoon(now);
  const from = toLocalNoon(to);

  switch (preset) {
    case "week":
      from.setDate(from.getDate() - 7);
      break;
    case "month":
      from.setMonth(from.getMonth() - 1);
      break;
    case "quarter":
      from.setMonth(from.getMonth() - 3);
      break;
    case "year":
      from.setFullYear(from.getFullYear() - 1);
      break;
    default:
      break;
  }

  return { from, to };
}

function createDefaultReportFilters(): ReportFilterState {
  const { from, to } = resolvePresetRange("month");
  return {
    preset: "month",
    from,
    to,
    platforms: [],
    accounts: [],
    accountType: "all",
    sort: "engagement",
  };
}

function isAccountType(value: string): value is SocialMediaReportAccountType {
  return value === "all" || value === "api" || value === "manual";
}

function isReportSort(value: string): value is SocialMediaReportSort {
  return value === "engagement" || value === "likes" || value === "reach" || value === "views";
}

function getPlatformLabel(platform: SocialPlatform | string, t: TranslationFn) {
  switch (platform) {
    case "facebook":
      return t("socialMedia.tabs.facebook");
    case "instagram":
      return t("socialMedia.tabs.instagram");
    case "twitter":
      return t("socialMedia.tabs.twitter");
    case "linkedin":
      return t("socialMedia.tabs.linkedin");
    case "youtube":
      return t("socialMedia.tabs.youtube");
    case "snapchat":
      return t("socialMedia.tabs.snapchat");
    case "tiktok":
      return t("socialMedia.tabs.tiktok");
    default:
      return platform;
  }
}

function getAccountTypeLabel(value: SocialMediaReportAccountType, t: TranslationFn) {
  switch (value) {
    case "all":
      return t("socialMedia.reportsPage.accountTypes.all");
    case "api":
      return t("socialMedia.reportsPage.accountTypes.api");
    case "manual":
      return t("socialMedia.reportsPage.accountTypes.manual");
    default:
      return value;
  }
}

function getSortLabel(value: SocialMediaReportSort, t: TranslationFn) {
  switch (value) {
    case "engagement":
      return t("socialMedia.reportsPage.sorts.engagement");
    case "likes":
      return t("socialMedia.reportsPage.sorts.likes");
    case "reach":
      return t("socialMedia.reportsPage.sorts.reach");
    case "views":
      return t("socialMedia.reportsPage.sorts.views");
    default:
      return value;
  }
}

function formatNumber(value?: number | null) {
  return (value ?? 0).toLocaleString();
}

function formatPercent(value?: number | string | null) {
  const numeric =
    typeof value === "string" ? Number(value) : typeof value === "number" ? value : 0;
  if (!Number.isFinite(numeric)) return "0.00%";
  return `${Math.max(0, numeric).toFixed(2)}%`;
}

function normalizeExternalUrl(value?: string | null) {
  if (!value) return null;
  const trimmed = value.trim();
  const withoutTicks = trimmed.replace(/^`+/, "").replace(/`+$/, "").trim();
  return withoutTicks.length > 0 ? withoutTicks : null;
}

function formatDelta(value?: number | null) {
  const numeric = typeof value === "number" ? value : 0;
  const safe = Number.isFinite(numeric) ? numeric : 0;
  return `${safe >= 0 ? "+" : ""}${safe.toFixed(0)}%`;
}

function ProjectSummarySkeleton() {
  return (
    <Card className="rounded-[16px] border-border/70 shadow-sm">
      <div className="p-6">
        <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(280px,375px)] lg:items-start">
          <div className="min-w-0 space-y-3">
            <div className="flex flex-wrap items-center gap-2 sm:gap-3">
              <Skeleton className="h-6 w-56 max-w-full" />
              <Skeleton className="h-6 w-20 shrink-0" />
            </div>
            <div className="flex flex-col gap-3 xl:flex-row xl:items-center">
              <Skeleton className="h-4 w-full max-w-2xl" />
              <Skeleton className="h-8 w-28 shrink-0" />
            </div>
          </div>
          <div className="flex min-w-0 flex-col gap-2 sm:flex-row sm:items-end sm:gap-4 lg:justify-end">
            <div className="min-w-0 flex-1 space-y-2 lg:max-w-[375px]">
              <Skeleton className="h-4 w-16" />
              <Skeleton className="h-4 w-full" />
            </div>
            <Skeleton className="h-6 w-12" />
          </div>
        </div>
        <div className="mt-6 grid w-full grid-cols-2 gap-3 sm:gap-4 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
          {[1, 2, 3, 4, 5, 6].map((i) => (
            <Skeleton key={i} className="h-20 rounded-[16px]" />
          ))}
        </div>
      </div>
    </Card>
  );
}

function FiltersSkeleton() {
  return (
    <Card className="rounded-[16px] border-border/70 shadow-sm">
      <CardContent className="space-y-4 p-6">
        <div className="flex items-center justify-between gap-3">
          <div className="space-y-2">
            <Skeleton className="h-5 w-40" />
            <Skeleton className="h-4 w-72 max-w-full" />
          </div>
          <Skeleton className="h-4 w-20" />
        </div>
        <div className="grid gap-4 xl:grid-cols-3">
          <Skeleton className="h-16 rounded-xl" />
          <Skeleton className="h-16 rounded-xl" />
          <Skeleton className="h-16 rounded-xl" />
          <Skeleton className="h-16 rounded-xl xl:col-span-3" />
          <Skeleton className="h-16 rounded-xl xl:col-span-3" />
        </div>
      </CardContent>
    </Card>
  );
}

function ReportsKpisSection({
  kpis,
  t,
}: {
  kpis: NonNullable<ReturnType<typeof useSocialMediaReport>["kpis"]>;
  t: TranslationFn;
}) {
  const isFollowersUp = (kpis.change?.followers ?? 0) >= 0;
  const isReachUp = (kpis.change?.reach ?? 0) >= 0;
  const isPostsUp = (kpis.change?.posts ?? 0) >= 0;
  const isEngagementUp = (kpis.change?.engagement ?? 0) >= 0;

  const deltaClass = (isUp: boolean) =>
    cn(
      "rounded-md px-2 py-1 text-xs font-semibold",
      isUp ? "bg-emerald-50 text-emerald-700" : "bg-rose-50 text-rose-700",
    );

  const iconBoxClass = (variant: "followers" | "engagement" | "reach" | "posts" | "impressions") =>
    cn(
      "flex size-10 items-center justify-center rounded-xl",
      variant === "followers" && "bg-blue-50 text-blue-600",
      variant === "engagement" && "bg-rose-50 text-rose-600",
      variant === "reach" && "bg-emerald-50 text-emerald-600",
      variant === "posts" && "bg-amber-50 text-amber-600",
      variant === "impressions" && "bg-indigo-50 text-indigo-600",
    );

  const mainCards = [
    {
      key: "followers",
      title: t("socialMedia.reportsPage.kpis.totalFollowers"),
      value: formatNumber(kpis.total_followers),
      delta: formatDelta(kpis.change?.followers),
      deltaClassName: deltaClass(isFollowersUp),
      icon: (
        <svg viewBox="0 0 24 24" className="size-5" fill="none" stroke="currentColor">
          <path
            d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
          <circle cx="8.5" cy="7" r="4" strokeWidth="2" />
          <path
            d="M20 8v6M23 11h-6"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        </svg>
      ),
      iconClassName: iconBoxClass("followers"),
    },
    {
      key: "engagement",
      title: t("socialMedia.reportsPage.kpis.totalEngagement"),
      value: formatNumber(kpis.total_engagement),
      delta: formatDelta(kpis.change?.engagement),
      deltaClassName: deltaClass(isEngagementUp),
      icon: <Heart className="size-5" />,
      iconClassName: iconBoxClass("engagement"),
    },
    {
      key: "reach",
      title: t("socialMedia.reportsPage.kpis.totalReach"),
      value: formatNumber(kpis.total_reach),
      delta: formatDelta(kpis.change?.reach),
      deltaClassName: deltaClass(isReachUp),
      icon: (
        <svg viewBox="0 0 24 24" className="size-5" fill="none" stroke="currentColor">
          <path
            d="M21 12s-4-7-9-7-9 7-9 7 4 7 9 7 9-7 9-7z"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
          <circle cx="12" cy="12" r="3" strokeWidth="2" />
        </svg>
      ),
      iconClassName: iconBoxClass("reach"),
    },
    {
      key: "posts",
      title: t("socialMedia.reportsPage.kpis.totalPosts"),
      value: formatNumber(kpis.total_posts),
      delta: formatDelta(kpis.change?.posts),
      deltaClassName: deltaClass(isPostsUp),
      icon: (
        <svg viewBox="0 0 24 24" className="size-5" fill="none" stroke="currentColor">
          <path
            d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
          <path d="M17 21v-8H7v8" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
          <path d="M7 3v5h8" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      ),
      iconClassName: iconBoxClass("posts"),
    },
  ];

  return (
    <div className="space-y-4">
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {mainCards.map((card) => (
          <Card key={card.key} className="rounded-[16px] border-border/70 shadow-sm">
            <CardContent className="p-5">
              <div className="flex items-start justify-between gap-3">
                <div className={card.iconClassName}>{card.icon}</div>
                <span className={card.deltaClassName}>{card.delta}</span>
              </div>
              <div className="mt-4 space-y-1">
                <div className="text-2xl font-bold text-foreground">{card.value}</div>
                <div className="text-sm text-muted-foreground">
                  {card.title}
                </div>
                <div className="text-[11px] text-muted-foreground">
                  {t("socialMedia.reportsPage.kpis.vsPrevious")}
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      <div className="grid gap-4 lg:grid-cols-4">
        <Card className="rounded-[16px] border-border/70 shadow-sm">
          <CardContent className="p-5">
            <div className="flex items-start justify-between gap-3">
           <div className="text-sm text-muted-foreground">
                {t("socialMedia.reportsPage.kpis.totalImpressions")}
              </div>
            </div>
            <div className="mt-4 space-y-1">
              <div className="text-2xl font-bold text-foreground">
                {formatNumber(kpis.total_impressions)}
              </div>
             
           
            </div>
          </CardContent>
        </Card>
        <Card className="rounded-[16px] border-border/70 shadow-sm">
          <CardContent className="p-5">
            <div className="text-sm font-medium text-muted-foreground">
              {t("socialMedia.reportsPage.kpis.engagementRate")}
            </div>
            <div className="mt-2 text-2xl font-bold text-foreground">
              {formatPercent(kpis.engagement_rate)}
            </div>
          </CardContent>
        </Card>
        <Card className="rounded-[16px] border-border/70 shadow-sm">
          <CardContent className="p-5">
            <div className="text-sm font-medium text-muted-foreground">
              {t("socialMedia.reportsPage.kpis.growthRate")}
            </div>
            <div className="mt-2 text-2xl font-bold text-foreground">
              {formatPercent(kpis.growth_rate_pct)}
            </div>
          </CardContent>
        </Card>
        <Card className="rounded-[16px] border-border/70 shadow-sm">
          <CardContent className="p-5">
            <div className="text-sm font-medium text-muted-foreground">
              {t("socialMedia.reportsPage.kpis.avgEngagementPerPost")}
            </div>
            <div className="mt-2 text-2xl font-bold text-foreground">
              {formatNumber(kpis.avg_engagement_per_post)}
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

function EngagementTimelineChart({
  title,
  labels,
  datasets,
  formatAxisLabel,
  isRTL,
}: {
  title: string;
  labels: string[];
  datasets: Array<{ label: string; data: Array<number | null>; backgroundColor?: string }>;
  formatAxisLabel: (date: string) => string;
  isRTL: boolean;
}) {
  const colors = useThemeColors();
  const isMobile = useIsMobile();
  const locale = useLocale();

  const compactNumberFormatter = useMemo(() => {
    return new Intl.NumberFormat(locale, {
      notation: "compact",
      compactDisplay: "short",
      maximumFractionDigits: 1,
    });
  }, [locale]);

  const xInterval = useMemo(() => {
    if (!isMobile) return "preserveStartEnd" as const;
    if (labels.length <= 6) return 0;
    return Math.max(0, Math.ceil(labels.length / 6) - 1);
  }, [isMobile, labels.length]);

  const data = useMemo(() => {
    return labels.map((label, index) => {
      const row: Record<string, string | number | null> = { date: formatAxisLabel(label) };
      datasets.forEach((dataset, datasetIndex) => {
        row[`s${datasetIndex}`] = dataset.data[index] ?? 0;
      });
      return row;
    });
  }, [datasets, formatAxisLabel, labels]);

  return (
    <Card className="rounded-[16px] border-border/70 shadow-sm">
      <div className="bg-muted/30 px-4 sm:px-6 py-3.5 border-b border-border/60">
        <h3 className="font-semibold text-sm sm:text-base text-foreground">{title}</h3>
      </div>
      <div className="p-4 sm:p-6">
        <div className="h-[240px] sm:h-[280px]">
          <ResponsiveContainer width="100%" height="100%">
            <BarChart data={isRTL ? [...data].reverse() : data}>
              <CartesianGrid strokeDasharray="0" stroke={colors.border} vertical={false} />
              <XAxis
                dataKey="date"
                tick={{ fill: colors.mutedForeground, fontSize: isMobile ? 9 : 10 }}
                axisLine={false}
                tickLine={false}
                reversed={isRTL}
                interval={xInterval}
                minTickGap={isMobile ? 32 : 24}
              />
              <YAxis
                tick={{ fill: colors.mutedForeground, fontSize: isMobile ? 10 : 11 }}
                axisLine={false}
                tickLine={false}
                domain={[0, "auto"]}
                orientation={isRTL ? "right" : "left"}
                width={isMobile ? 38 : 48}
                tickFormatter={(value) =>
                  isMobile
                    ? compactNumberFormatter.format(Number(value))
                    : Number(value).toLocaleString(locale)
                }
              />
              <RechartsTooltip
                contentStyle={{
                  backgroundColor: "var(--card)",
                  border: `1px solid var(--border)`,
                  borderRadius: "8px",
                  boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15)",
                  color: "var(--card-foreground)",
                }}
                itemStyle={{ color: "var(--card-foreground)" }}
                labelStyle={{ color: "var(--card-foreground)", fontWeight: 600 }}
              />
              {datasets.map((dataset, index) => (
                <Bar
                  key={dataset.label}
                  dataKey={`s${index}`}
                  name={dataset.label}
                  fill={dataset.backgroundColor || colors.primary}
                  radius={[6, 6, 0, 0]}
                  maxBarSize={34}
                />
              ))}
            </BarChart>
          </ResponsiveContainer>
        </div>

        {datasets.length > 1 ? (
          <div
            className="mt-4 flex gap-3 justify-center overflow-x-auto whitespace-nowrap pb-1 sm:flex-wrap sm:overflow-visible sm:whitespace-normal"
            dir={isRTL ? "rtl" : "ltr"}
          >
            {datasets.map((dataset) => (
              <div key={dataset.label} className="flex items-center gap-2 shrink-0">
                <span
                  className="inline-block h-2.5 w-2.5 rounded-full"
                  style={{ backgroundColor: dataset.backgroundColor || colors.primary }}
                />
                <span className="text-[11px] sm:text-sm text-muted-foreground truncate max-w-[160px]">
                  {dataset.label}
                </span>
              </div>
            ))}
          </div>
        ) : null}
      </div>
    </Card>
  );
}

function ReportsChartsSection({
  charts,
  t,
  formatDate,
  isRTL,
}: {
  charts: NonNullable<ReturnType<typeof useSocialMediaReport>["data"]>["charts"];
  t: TranslationFn;
  formatDate: (date: string) => string;
  isRTL: boolean;
}) {
  const followersGrowth = charts.followers_growth;
  const followerSeries = followersGrowth.datasets.map((dataset, index) => ({
    dataKey: `s${index}`,
    label: dataset.label,
    color: dataset.borderColor,
  }));

  const followersData = followersGrowth.labels.map((label, labelIndex) => {
    const row: Record<string, string | number> = {
      date: formatDate(label),
    };

    followersGrowth.datasets.forEach((dataset, datasetIndex) => {
      row[`s${datasetIndex}`] = dataset.data[labelIndex] ?? 0;
    });

    return row;
  });

  const distributionData = charts.platform_distribution.labels.map(
    (platform, index) => ({
      name: getPlatformLabel(platform, t),
      value: charts.platform_distribution.data[index] ?? 0,
      color: charts.platform_distribution.colors[index] ?? "var(--primary)",
    }),
  );

  return (
    <div className="space-y-6">
      <div className="grid gap-4 sm:gap-6 lg:grid-cols-2">
        <AreaLineChart
          className="h-[420px]"
          variant="report"
          title={t("socialMedia.reportsPage.charts.followersGrowth")}
          subtitle={t("socialMedia.reportsPage.charts.followersGrowthSubtitle")}
          data={followersData}
          series={followerSeries}
          xAxisKey="date"
        />
        <SocialPieChart
          className="h-[420px]"
          title={t("socialMedia.reportsPage.charts.followersDistribution")}
          subtitle={t("socialMedia.reportsPage.charts.followersDistributionSubtitle")}
          data={distributionData}
        />
      </div>

      <EngagementTimelineChart
        title={t("socialMedia.reportsPage.charts.engagementTimeline")}
        labels={charts.engagement_timeline.labels}
        datasets={charts.engagement_timeline.datasets.map((dataset) => ({
          label: dataset.label,
          data: dataset.data,
          backgroundColor: dataset.backgroundColor,
        }))}
        formatAxisLabel={formatDate}
        isRTL={isRTL}
      />
    </div>
  );
}

function SocialMediaReportAccountsBreakdown({
  accounts,
  t,
}: {
  accounts: SocialMediaReportAccountItem[];
  t: TranslationFn;
}) {
  const rows = accounts.map((account) => ({
    ...account,
    accountUrl: normalizeExternalUrl(account.account_url),
    platformLabel: getPlatformLabel(account.platform, t),
    accountTypeLabel: account.is_manual
      ? t("socialMedia.reportsPage.accountsBreakdown.manual")
      : t("socialMedia.reportsPage.accountsBreakdown.api"),
  }));

  return (
    <Card className="rounded-[16px] border-border/70 shadow-sm">
      <div className="px-6 py-4 border-b border-border/60">
        <h2 className="text-base font-semibold text-foreground">
          {t("socialMedia.reportsPage.accounts.title")}
        </h2>
        <p className="text-sm text-muted-foreground">
          {t("socialMedia.reportsPage.accounts.description")}
        </p>
      </div>
      <div className="overflow-x-auto">
        <table className="min-w-[1280px] w-full text-left rtl:text-right text-sm">
          <thead className="bg-muted/30 text-xs uppercase text-muted-foreground">
            <tr>
              <th className="px-6 py-3 font-medium">
                {t("socialMedia.reportsPage.accountsBreakdown.columns.platform")}
              </th>
              <th className="px-6 py-3 font-medium">
                {t("socialMedia.reportsPage.accountsBreakdown.columns.account")}
              </th>
              <th className="px-6 py-3 font-medium">
                {t("socialMedia.reportsPage.accountsBreakdown.columns.followers")}
              </th>
              <th className="px-6 py-3 font-medium">
                {t.has("socialMedia.reportsPage.accountsBreakdown.columns.following")
                  ? t("socialMedia.reportsPage.accountsBreakdown.columns.following")
                  : t("socialMedia.following")}
              </th>
              <th className="px-6 py-3 font-medium">
                {t("socialMedia.reportsPage.accountsBreakdown.columns.growthRate")}
              </th>
              <th className="px-6 py-3 font-medium">
                {t("socialMedia.reportsPage.accountsBreakdown.columns.posts")}
              </th>
              <th className="px-6 py-3 font-medium">
                {t.has("socialMedia.reportsPage.accountsBreakdown.columns.likes")
                  ? t("socialMedia.reportsPage.accountsBreakdown.columns.likes")
                  : t("socialMedia.likes")}
              </th>
              <th className="px-6 py-3 font-medium">
                {t.has("socialMedia.reportsPage.accountsBreakdown.columns.comments")
                  ? t("socialMedia.reportsPage.accountsBreakdown.columns.comments")
                  : t("socialMedia.comments")}
              </th>
              <th className="px-6 py-3 font-medium">
                {t.has("socialMedia.reportsPage.accountsBreakdown.columns.shares")
                  ? t("socialMedia.reportsPage.accountsBreakdown.columns.shares")
                  : t("socialMedia.shares")}
              </th>
              <th className="px-6 py-3 font-medium">
                {t("socialMedia.reportsPage.accountsBreakdown.columns.engagement")}
              </th>
              <th className="px-6 py-3 font-medium">
                {t("socialMedia.reportsPage.accountsBreakdown.columns.reach")}
              </th>
              <th className="px-6 py-3 font-medium">
                {t("socialMedia.reportsPage.accountsBreakdown.columns.type")}
              </th>
            </tr>
          </thead>
          <tbody className="divide-y divide-border">
            {rows.map((account) => {
              const profileImageUrl =
                resolveSocialMediaAssetUrl(account.profile_image) ?? null;
              return (
                <tr
                  key={account.id}
                  className="bg-transparent transition-colors hover:bg-muted/10"
                >
                  <td className="px-6 py-4 text-foreground">
                    <div className="flex items-center gap-2">
                      <span className="flex size-6 items-center justify-center">
                        {getPlatformIcon(account.platform)}
                      </span>
                      <span className="font-medium">{account.platformLabel}</span>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-3">
                      <div className="size-10 rounded-full border border-border/60 bg-muted/30 overflow-hidden">
                        {profileImageUrl ? (
                          <img
                            src={profileImageUrl}
                            alt={account.account_name}
                            className="h-full w-full object-cover"
                            referrerPolicy="no-referrer"
                          />
                        ) : null}
                      </div>
                      <div className="min-w-0">
                        <div className="font-medium text-foreground truncate">
                          {account.account_name}
                        </div>
                        {account.accountUrl ? (
                          <a
                            href={account.accountUrl}
                            target="_blank"
                            rel="noreferrer"
                            className="text-xs text-primary hover:text-primary/80"
                          >
                            {t("socialMedia.reportsPage.accountsBreakdown.view")}
                          </a>
                        ) : null}
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4 text-foreground">
                    {formatNumber(account.followers)}
                  </td>
                  <td className="px-6 py-4 text-foreground">
                    {formatNumber(account.following)}
                  </td>
                  <td className="px-6 py-4 text-foreground">
                    {formatPercent(account.growth_rate)}
                  </td>
                  <td className="px-6 py-4 text-foreground">
                    {formatNumber(account.posts_count)}
                  </td>
                  <td className="px-6 py-4 text-foreground">
                    {formatNumber(account.total_likes)}
                  </td>
                  <td className="px-6 py-4 text-foreground">
                    {formatNumber(account.total_comments)}
                  </td>
                  <td className="px-6 py-4 text-foreground">
                    {formatNumber(account.total_shares)}
                  </td>
                  <td className="px-6 py-4 text-foreground">
                    {formatNumber(account.engagement)}
                  </td>
                  <td className="px-6 py-4 text-foreground">
                    {formatNumber(account.reach)}
                  </td>
                  <td className="px-6 py-4">
                    <Badge
                      variant="secondary"
                      className="rounded-md bg-amber-50 text-amber-700 border border-amber-200"
                    >
                      {account.accountTypeLabel}
                    </Badge>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </Card>
  );
}

function getRankBadgeClass(index: number): string {
  if (index === 0)
    return "bg-gradient-to-br from-amber-400 to-orange-500 text-white shadow-sm shadow-amber-200 dark:shadow-amber-900/30";
  if (index === 1)
    return "bg-gradient-to-br from-slate-300 to-slate-500 text-white dark:from-slate-500 dark:to-slate-700";
  if (index === 2)
    return "bg-gradient-to-br from-amber-600 to-orange-700 text-white dark:from-amber-700 dark:to-orange-800";
  return "bg-muted text-muted-foreground border border-border";
}

function getPlatformBadgeClass(platform: string): string {
  switch (platform) {
    case "tiktok":
      return "bg-pink-100 text-pink-700 border border-pink-200 dark:bg-pink-900/30 dark:text-pink-300 dark:border-pink-800/50";
    case "twitter":
      return "bg-sky-100 text-sky-700 border border-sky-200 dark:bg-sky-900/30 dark:text-sky-300 dark:border-sky-800/50";
    case "instagram":
      return "bg-purple-100 text-purple-700 border border-purple-200 dark:bg-purple-900/30 dark:text-purple-300 dark:border-purple-800/50";
    case "facebook":
      return "bg-blue-100 text-blue-700 border border-blue-200 dark:bg-blue-900/30 dark:text-blue-300 dark:border-blue-800/50";
    case "linkedin":
      return "bg-blue-100 text-blue-800 border border-blue-200 dark:bg-blue-900/30 dark:text-blue-300 dark:border-blue-800/50";
    case "youtube":
      return "bg-red-100 text-red-700 border border-red-200 dark:bg-red-900/30 dark:text-red-300 dark:border-red-800/50";
    case "snapchat":
      return "bg-yellow-100 text-yellow-700 border border-yellow-200 dark:bg-yellow-900/30 dark:text-yellow-300 dark:border-yellow-800/50";
    default:
      return "bg-muted text-muted-foreground border border-border";
  }
}

function SocialMediaReportTopPosts({
  posts,
  t,
  formatPublishedAt,
}: {
  posts: Array<{
    id: number;
    platform: SocialPlatform | string;
    account_name?: string | null;
    title?: string | null;
    content_excerpt?: string | null;
    post_url?: string | null;
    published_at?: string | null;
    likes: number;
    comments: number;
    shares: number;
    engagement: number;
  }>;
  t: TranslationFn;
  formatPublishedAt: (date: string) => string;
}) {
  if (posts.length === 0) {
    return null;
  }

  return (
    <Card className="overflow-hidden rounded-[16px] border-border/70 shadow-sm">
      <div className="border-b border-border/60 bg-gradient-to-r from-background to-muted/20 px-6 py-4">
        <h2 className="text-base font-semibold text-foreground">
          {t("socialMedia.reportsPage.topPosts.title")}
        </h2>
        <p className="text-sm text-muted-foreground">
          {t("socialMedia.reportsPage.topPosts.subtitle")}
        </p>
      </div>
      <CardContent className="p-0">
        <div className="divide-y divide-border/60">
          {posts.map((post, index) => {
            const postUrl = normalizeExternalUrl(post.post_url);
            const platformLabel = getPlatformLabel(post.platform, t);
            return (
              <div
                key={post.id}
                className="group relative flex gap-3 px-4 py-4 transition-colors hover:bg-muted/30 sm:gap-4 sm:px-6 sm:py-5"
              >
                {index < 3 && (
                  <div
                    className={cn(
                      "absolute bottom-0 start-0 top-0 w-1 rounded-e-full",
                      index === 0
                        ? "bg-gradient-to-b from-amber-400 to-orange-500"
                        : index === 1
                          ? "bg-gradient-to-b from-slate-300 to-slate-500 dark:from-slate-500 dark:to-slate-700"
                          : "bg-gradient-to-b from-amber-600 to-orange-700"
                    )}
                  />
                )}
                <div
                  className={cn(
                    "flex size-9 shrink-0 items-center justify-center rounded-xl text-sm font-bold sm:size-10",
                    getRankBadgeClass(index)
                  )}
                >
                  {index + 1}
                </div>
                <div className="min-w-0 flex-1 space-y-2">
                  <div className="flex flex-wrap items-center gap-1.5">
                    <span
                      className={cn(
                        "inline-flex items-center rounded-full px-2 py-0.5 text-xs font-semibold",
                        getPlatformBadgeClass(post.platform)
                      )}
                    >
                      {platformLabel}
                    </span>
                    {post.account_name ? (
                      <span className="text-xs font-medium text-foreground">
                        {post.account_name}
                      </span>
                    ) : null}
                    {post.published_at ? (
                      <span className="text-xs text-muted-foreground">
                        • {formatPublishedAt(post.published_at)}
                      </span>
                    ) : null}
                  </div>
                  <div className="space-y-1">
                    <p className="line-clamp-2 text-sm font-semibold text-foreground">
                      {post.title || post.content_excerpt || t("socialMedia.reportsPage.topPosts.untitled")}
                    </p>
                    {post.content_excerpt && post.title ? (
                      <p className="line-clamp-2 text-sm text-muted-foreground">
                        {post.content_excerpt}
                      </p>
                    ) : null}
                  </div>
                  <div className="flex flex-wrap items-center gap-1.5">
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <span
                          tabIndex={0}
                          aria-label={t("socialMedia.likes")}
                          className="inline-flex items-center gap-1 rounded-full border border-rose-100 bg-rose-50 px-2 py-0.5 text-xs font-medium text-rose-600 dark:border-rose-900/40 dark:bg-rose-900/20 dark:text-rose-400"
                        >
                          <Heart className="size-3" />
                          {formatNumber(post.likes)}
                        </span>
                      </TooltipTrigger>
                      <TooltipContent side="top" sideOffset={6}>
                        {t("socialMedia.likes")}: {formatNumber(post.likes)}
                      </TooltipContent>
                    </Tooltip>

                    <Tooltip>
                      <TooltipTrigger asChild>
                        <span
                          tabIndex={0}
                          aria-label={t("socialMedia.comments")}
                          className="inline-flex items-center gap-1 rounded-full border border-sky-100 bg-sky-50 px-2 py-0.5 text-xs font-medium text-sky-600 dark:border-sky-900/40 dark:bg-sky-900/20 dark:text-sky-400"
                        >
                          <MessageCircle className="size-3" />
                          {formatNumber(post.comments)}
                        </span>
                      </TooltipTrigger>
                      <TooltipContent side="top" sideOffset={6}>
                        {t("socialMedia.comments")}: {formatNumber(post.comments)}
                      </TooltipContent>
                    </Tooltip>

                    <Tooltip>
                      <TooltipTrigger asChild>
                        <span
                          tabIndex={0}
                          aria-label={t("socialMedia.shares")}
                          className="inline-flex items-center gap-1 rounded-full border border-emerald-100 bg-emerald-50 px-2 py-0.5 text-xs font-medium text-emerald-600 dark:border-emerald-900/40 dark:bg-emerald-900/20 dark:text-emerald-400"
                        >
                          <Share2 className="size-3" />
                          {formatNumber(post.shares)}
                        </span>
                      </TooltipTrigger>
                      <TooltipContent side="top" sideOffset={6}>
                        {t("socialMedia.shares")}: {formatNumber(post.shares)}
                      </TooltipContent>
                    </Tooltip>

                    <Tooltip>
                      <TooltipTrigger asChild>
                        <span
                          tabIndex={0}
                          aria-label={t("socialMedia.views")}
                          className="inline-flex items-center gap-1 rounded-full border border-violet-100 bg-violet-50 px-2 py-0.5 text-xs font-medium text-violet-600 dark:border-violet-900/40 dark:bg-violet-900/20 dark:text-violet-400"
                        >
                          <Eye className="size-3" />
                          {formatNumber(post.engagement)}
                        </span>
                      </TooltipTrigger>
                      <TooltipContent side="top" sideOffset={6}>
                        {t("socialMedia.views")}: {formatNumber(post.engagement)}
                      </TooltipContent>
                    </Tooltip>
                  </div>
                </div>
                {postUrl ? (
                  <a
                    href={postUrl}
                    target="_blank"
                    rel="noreferrer"
                    className="ms-auto inline-flex shrink-0 self-start items-center gap-1 text-sm text-primary hover:text-primary/80"
                  >
                    <span className="hidden sm:inline">{t("socialMedia.reportsPage.topPosts.view")}</span>
                    <svg viewBox="0 0 24 24" className="size-4" fill="none" stroke="currentColor">
                      <path
                        d="M7 17L17 7"
                        strokeWidth="2"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                      <path
                        d="M7 7h10v10"
                        strokeWidth="2"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                    </svg>
                  </a>
                ) : null}
              </div>
            );
          })}
        </div>
      </CardContent>
    </Card>
  );
}

function SocialMediaReportFiltersCard({
  t,
  locale,
  pendingFilters,
  platformOptions,
  accountOptions,
  onPresetChange,
  onFromChange,
  onToChange,
  onPlatformsChange,
  onAccountsChange,
  onAccountTypeChange,
  onSortChange,
  onApply,
  onClear,
  isRefreshing,
  canApply,
}: {
  t: TranslationFn;
  locale: Locale;
  pendingFilters: ReportFilterState;
  platformOptions: MultiSelectOption[];
  accountOptions: MultiSelectOption[];
  onPresetChange: (value: ReportPeriod) => void;
  onFromChange: (value: Date | null) => void;
  onToChange: (value: Date | null) => void;
  onPlatformsChange: (values: string[]) => void;
  onAccountsChange: (values: string[]) => void;
  onAccountTypeChange: (value: SocialMediaReportAccountType) => void;
  onSortChange: (value: SocialMediaReportSort) => void;
  onApply: () => void;
  onClear: () => void;
  isRefreshing: boolean;
  canApply: boolean;
}) {
  const [open, setOpen] = useState(false);
  const selectedAccounts = pendingFilters.accounts;
  const allAccountValues = useMemo(
    () => accountOptions.map((option) => option.value),
    [accountOptions],
  );
  const isAllAccountsSelected =
    allAccountValues.length > 0 &&
    selectedAccounts.length === allAccountValues.length;

  const toggleAccount = useCallback(
    (value: string) => {
      if (selectedAccounts.includes(value)) {
        onAccountsChange(selectedAccounts.filter((item) => item !== value));
        return;
      }
      onAccountsChange([...selectedAccounts, value]);
    },
    [onAccountsChange, selectedAccounts],
  );

  return (
    <Card className="overflow-hidden rounded-[16px] border-border/70 shadow-sm">
      <Collapsible open={open} onOpenChange={setOpen}>
        <CollapsibleTrigger
          type="button"
          className={cn(
            "flex w-full items-center justify-between gap-4 px-4 py-3.5 text-start transition-colors hover:bg-muted/30 sm:px-6",
            open ? "border-b border-border/60 bg-muted/20" : null,
          )}
        >
          <div className="flex items-center gap-2">
            <Filter className="size-5 text-emerald-600 shrink-0" />
            <span className="text-sm sm:text-base font-semibold text-foreground">
              {t("socialMedia.reportsPage.filters.panelTitle")}
            </span>
          </div>

          <ChevronDown
            className={cn(
              "size-5 text-muted-foreground transition-transform",
              open ? "rotate-180" : null,
            )}
          />
        </CollapsibleTrigger>

        <CollapsibleContent>
          <CardContent className="space-y-6 p-4 sm:p-6">
            {/* Quick preset + date range */}
            <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
              <div className="space-y-2">
                <div className="text-sm font-medium text-muted-foreground">
                  {t("socialMedia.reportsPage.filters.quickPeriod")}
                </div>
                <div className="flex items-center gap-2 overflow-x-auto pb-1">
                  {(["day", "week", "month", "quarter", "year"] as const).map((preset) => {
                    const isActive = pendingFilters.preset === preset;
                    return (
                      <Button
                        key={preset}
                        type="button"
                        variant="outline"
                        className={cn(
                          "h-10 shrink-0 rounded-xl border-border/70 bg-background px-4 text-sm font-medium shadow-sm",
                          isActive ? "border-primary bg-primary/5 ring-2 ring-primary/15" : null,
                        )}
                        onClick={() => {
                          const range = resolvePresetRange(preset);
                          onPresetChange(preset);
                          onFromChange(range.from);
                          onToChange(range.to);
                        }}
                      >
                        {t(`socialMedia.reportsPage.filters.quickPresets.${preset}`)}
                      </Button>
                    );
                  })}
                </div>
              </div>

              <div className="grid gap-3 sm:grid-cols-[1fr_auto_1fr] sm:items-end lg:min-w-[420px]">
                <div className="space-y-2">
                  <Label className="text-sm font-medium text-muted-foreground">
                    {t("socialMedia.reportsPage.filters.from")}
                  </Label>
                  <Datepicker
                    value={pendingFilters.from}
                    onChange={(value) => {
                      if (pendingFilters.preset !== "custom") {
                        onPresetChange("custom");
                      }
                      onFromChange(value);
                    }}
                    locale={locale}
                    mode="single"
                    showShortcuts={false}
                    showInput
                    className="w-full"
                  />
                </div>

                <div className="hidden sm:flex items-center justify-center pb-2 text-muted-foreground">
                  <span aria-hidden className="text-lg leading-none">
                    →
                  </span>
                </div>

                <div className="space-y-2">
                  <Label className="text-sm font-medium text-muted-foreground">
                    {t("socialMedia.reportsPage.filters.to")}
                  </Label>
                  <Datepicker
                    value={pendingFilters.to}
                    onChange={(value) => {
                      if (pendingFilters.preset !== "custom") {
                        onPresetChange("custom");
                      }
                      onToChange(value);
                    }}
                    locale={locale}
                    mode="single"
                    showShortcuts={false}
                    showInput
                    className="w-full"
                  />
                </div>
              </div>
            </div>

            {/* Platforms */}
            <div className="space-y-2">
              <Label className="text-sm font-medium text-muted-foreground">
                {t("socialMedia.reportsPage.filters.platforms")}
              </Label>
              <MultiSelect
                options={platformOptions}
                selected={pendingFilters.platforms}
                onChange={onPlatformsChange}
                placeholder={t("socialMedia.reportsPage.filters.platformsPlaceholder")}
                emptyMessage={t("socialMedia.reportsPage.filters.noPlatformOptions")}
                searchPlaceholder={t("common.searchPlaceholder")}
                selectAllLabel={t("socialMedia.reportsPage.filters.selectAllPlatforms")}
                deselectAllLabel={t("socialMedia.reportsPage.filters.deselectAllPlatforms")}
                className="min-h-11 border-border/70 bg-background rounded-xl"
              />
            </div>

            {/* Accounts */}
            <div className="space-y-3">
              <div className="flex flex-wrap items-center justify-between gap-3">
                <div className="text-sm font-medium text-muted-foreground">
                  {t("socialMedia.reportsPage.filters.accounts")}
                  <span className="ms-2 text-muted-foreground/70">
                    {selectedAccounts.length}/{accountOptions.length}
                  </span>
                </div>
                {accountOptions.length > 0 ? (
                  <Button
                    type="button"
                    variant="link"
                    className="h-auto p-0 text-sm text-emerald-700 hover:text-emerald-800"
                    onClick={() => {
                      onAccountsChange(isAllAccountsSelected ? [] : allAccountValues);
                    }}
                  >
                    {isAllAccountsSelected
                      ? t("socialMedia.reportsPage.filters.deselectAllAccounts")
                      : t("socialMedia.reportsPage.filters.selectAllAccounts")}
                  </Button>
                ) : null}
              </div>

              <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                {accountOptions.map((option) => {
                  const isSelected = selectedAccounts.includes(option.value);
                  const [accountName, platformName] = option.label.split(" · ");

                  return (
                    <button
                      key={option.value}
                      type="button"
                      role="checkbox"
                      aria-checked={isSelected}
                      onClick={() => toggleAccount(option.value)}
                      className={cn(
                        "group relative w-full rounded-2xl border border-border/70 bg-background px-4 py-3 text-start shadow-sm transition-colors hover:bg-muted/30",
                        isSelected ? "border-primary ring-2 ring-primary/10" : null,
                      )}
                    >
                      <div className="flex items-center justify-between gap-3">
                        <div className="min-w-0">
                          <div className="text-sm font-semibold text-foreground truncate">
                            {platformName ?? option.label}
                          </div>
                        </div>
                        <span
                          className={cn(
                            "flex h-6 w-6 shrink-0 items-center justify-center rounded-md border border-border/70 bg-background transition-colors",
                            isSelected ? "border-primary bg-primary text-primary-foreground" : "text-transparent",
                          )}
                        >
                          <Check className="h-4 w-4" />
                        </span>
                      </div>

                      <div className="mt-2 flex items-center justify-between gap-3">
                        <div className="text-sm text-muted-foreground truncate">
                          {accountName ?? option.label}
                        </div>
                        {pendingFilters.accountType !== "all" ? (
                          <span className="text-xs font-medium text-primary/80">
                            {getAccountTypeLabel(pendingFilters.accountType, t)}
                          </span>
                        ) : null}
                      </div>
                    </button>
                  );
                })}
              </div>
            </div>

            {/* Footer actions */}
            <div className="flex flex-col gap-4 border-t border-border/60 pt-4 sm:flex-row sm:items-end sm:justify-between">
              <div className="flex items-center gap-3">
                <Button
                  type="button"
                  onClick={onApply}
                  disabled={!canApply || isRefreshing}
                  className="h-11 rounded-xl px-6"
                >
                  <Filter className="me-2 size-4" />
                  {isRefreshing ? t("common.loading") : t("socialMedia.reportsPage.filters.apply")}
                </Button>
                <Button
                  type="button"
                  variant="outline"
                  onClick={onClear}
                  className="h-11 rounded-xl border-border/70"
                >
                  {t("socialMedia.reportsPage.filters.clear")}
                </Button>
              </div>

              <div className="grid gap-4 sm:grid-cols-2">
                <div className="space-y-2">
                  <Label className="text-sm font-medium text-muted-foreground">
                    {t("socialMedia.reportsPage.filters.accountType")}
                  </Label>
                  <Select
                    value={pendingFilters.accountType}
                    onValueChange={(value) => {
                      if (isAccountType(value)) {
                        onAccountTypeChange(value);
                      }
                    }}
                  >
                    <SelectTrigger className="h-11 w-full rounded-xl border-border/70 bg-background">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">{getAccountTypeLabel("all", t)}</SelectItem>
                      <SelectItem value="api">{getAccountTypeLabel("api", t)}</SelectItem>
                      <SelectItem value="manual">{getAccountTypeLabel("manual", t)}</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label className="text-sm font-medium text-muted-foreground">
                    {t("socialMedia.reportsPage.filters.sort")}
                  </Label>
                  <Select
                    value={pendingFilters.sort}
                    onValueChange={(value) => {
                      if (isReportSort(value)) {
                        onSortChange(value);
                      }
                    }}
                  >
                    <SelectTrigger className="h-11 w-full rounded-xl border-border/70 bg-background">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="engagement">{getSortLabel("engagement", t)}</SelectItem>
                      <SelectItem value="likes">{getSortLabel("likes", t)}</SelectItem>
                      <SelectItem value="reach">{getSortLabel("reach", t)}</SelectItem>
                      <SelectItem value="views">{getSortLabel("views", t)}</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>
          </CardContent>
        </CollapsibleContent>
      </Collapsible>
    </Card>
  );
}

function SocialMediaReportsHero({
  title,
  from,
  to,
  accountsCount,
  platformsCount,
  actions,
  t,
}: {
  title: string;
  from: Date | null;
  to: Date | null;
  accountsCount: number;
  platformsCount: number;
  actions: Array<{
    label: string;
    icon: React.ReactNode;
    onClick: () => void;
    disabled?: boolean;
  }>;
  t: TranslationFn;
}) {
  const colors = useThemeColors();

  const rangeLabel = useMemo(() => {
    if (!from || !to) return null;
    return `${formatDateToYMD(from)} → ${formatDateToYMD(to)}`;
  }, [from, to]);

  return (
    <div
      className="relative overflow-hidden rounded-2xl border border-border/50 px-4 py-4 shadow-sm sm:px-6 sm:py-6"
      style={{
        background: `linear-gradient(90deg, ${colors.secondary}, ${colors.primary})`,
      }}
    >
      <div className="absolute inset-0 opacity-[0.08] pointer-events-none">
        <div
          className="absolute inset-0"
          style={{
            backgroundImage: `
              repeating-linear-gradient(
                0deg,
                transparent,
                transparent 42px,
                rgba(255, 255, 255, 0.6) 42px,
                rgba(255, 255, 255, 0.6) 43px
              ),
              repeating-linear-gradient(
                90deg,
                transparent,
                transparent 42px,
                rgba(255, 255, 255, 0.6) 42px,
                rgba(255, 255, 255, 0.6) 43px
              )
            `,
          }}
        />
      </div>

      <div className="relative flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
        <div className="min-w-0 space-y-2.5 sm:space-y-3">
          <div className="text-sm font-medium text-white/80">
            {t("socialMedia.reportsButton")}
          </div>
          <div className="text-xl font-semibold leading-tight text-white sm:text-2xl lg:text-3xl line-clamp-2">
            {title}
          </div>

          <div className="flex flex-wrap items-center gap-2 text-white/90 text-xs sm:text-sm min-w-0">
            {rangeLabel ? (
              <div className="inline-flex max-w-full min-w-0 items-center gap-2 rounded-full bg-white/14 px-3 py-1">
                <Calendar className="size-4" />
                <span dir="ltr" className="tabular-nums truncate">
                  {rangeLabel}
                </span>
              </div>
            ) : null}
            <Badge className="rounded-full border-white/20 bg-white/14 text-white hover:bg-white/18">
              {accountsCount} {t("socialMedia.accounts")}
            </Badge>
            <Badge className="rounded-full border-white/20 bg-white/14 text-white hover:bg-white/18">
              {platformsCount} {t("socialMedia.reportsPage.filters.platforms")}
            </Badge>
          </div>
        </div>

        <div className="grid w-full grid-cols-1 gap-2 sm:grid-cols-2 lg:flex lg:w-auto lg:flex-row lg:flex-wrap lg:items-center lg:justify-end">
          {actions.map((action) => (
            <Button
              key={action.label}
              type="button"
              variant="secondary"
              onClick={action.onClick}
              disabled={action.disabled}
              className="h-11 w-full rounded-xl border border-white/15 bg-white/14 text-white hover:bg-white/18 justify-between lg:w-auto lg:justify-center"
            >
              <span className="inline-flex items-center gap-2 min-w-0">
                {action.icon}
                <span className="truncate">{action.label}</span>
              </span>
            </Button>
          ))}
        </div>
      </div>
    </div>
  );
}

function SocialMediaReportsLoading() {
  return (
    <div className="p-6 space-y-6">
      <ProjectSummarySkeleton />
      <FiltersSkeleton />
      <Card className="rounded-[16px] border-border/70 shadow-sm">
        <CardContent className="p-6">
          <Skeleton className="h-8 w-56" />
          <Skeleton className="mt-6 h-48 w-full rounded-[16px]" />
        </CardContent>
      </Card>
      <Card className="rounded-[16px] border-border/70 shadow-sm">
        <CardContent className="p-6">
          <Skeleton className="h-8 w-56" />
          <Skeleton className="mt-6 h-48 w-full rounded-[16px]" />
        </CardContent>
      </Card>
    </div>
  );
}

interface SocialMediaReportsListContainerProps {
  showHeader?: boolean;
}

export function SocialMediaReportsListContainer({
  showHeader = true,
}: SocialMediaReportsListContainerProps) {
  const t = useTranslations();
  const locale = useLocale();
  const { projectId, projectName } = useProject();
  const { formatDate, formatDateTime } = useFormattedDate();
  const safeFormatDateTime = (value: string | Date) =>
    typeof formatDateTime === "function" ? formatDateTime(value) : formatDate(value);
  const formatPublishedAt = (value: string) =>
    typeof formatDateTime === "function" ? formatDateTime(value) : formatDate(value);

  const [pendingFilters, setPendingFilters] = useState<ReportFilterState>(() =>
    createDefaultReportFilters(),
  );
  const [appliedFilters, setAppliedFilters] = useState<ReportFilterState>(() =>
    createDefaultReportFilters(),
  );
  const [exportingFormat, setExportingFormat] = useState<"pdf" | "csv" | null>(null);
  const [isPrinting, setIsPrinting] = useState(false);

  const appliedQueryFilters = useMemo<SocialMediaReportFilters>(() => {
    const preset = appliedFilters.preset;

    return {
      preset,
      from:
        preset === "custom" && appliedFilters.from
          ? formatDateToYMD(appliedFilters.from)
          : null,
      to:
        preset === "custom" && appliedFilters.to
          ? formatDateToYMD(appliedFilters.to)
          : null,
      platforms: appliedFilters.platforms,
      accounts: appliedFilters.accounts,
      account_type: appliedFilters.accountType,
      sort: appliedFilters.sort,
    };
  }, [appliedFilters]);

  const {
    data: report,
    project,
    kpis,
    accounts,
    topPosts,
    availableAccounts,
    availablePlatforms,
    meta,
    platformGroups,
    isLoading,
    isRefreshing,
    error,
  } = useSocialMediaReport(appliedQueryFilters);

  const accountNameByPlatform = useMemo(() => {
    const platformToNames = new Map<string, Set<string>>();
    for (const account of accounts) {
      const platform = account.platform;
      const name = account.account_name;
      if (!platform || !name) continue;
      if (!platformToNames.has(platform)) {
        platformToNames.set(platform, new Set());
      }
      platformToNames.get(platform)?.add(name);
    }

    const result = new Map<string, string>();
    for (const [platform, names] of platformToNames.entries()) {
      if (names.size === 1) {
        const only = Array.from(names)[0];
        result.set(platform, only);
      }
    }
    return result;
  }, [accounts]);

  const filteredAccountOptions = useMemo<MultiSelectOption[]>(
    () =>
      buildSocialMediaReportAccountOptions(
        availableAccounts,
        pendingFilters.platforms,
        pendingFilters.accountType,
        (platform) => getPlatformLabel(platform, t),
      ),
    [availableAccounts, pendingFilters.accountType, pendingFilters.platforms, t],
  );

  const platformOptions = useMemo<MultiSelectOption[]>(
    () =>
      (availablePlatforms.length > 0 ? availablePlatforms : PLATFORM_VALUES)
        .filter((platform): platform is SocialPlatform =>
          PLATFORM_VALUES.includes(platform as SocialPlatform),
        )
        .map((platform) => ({
          label: getPlatformLabel(platform, t),
          value: platform,
        })),
    [availablePlatforms, t],
  );

  useEffect(() => {
    setPendingFilters((current) => {
      const allowed = new Set(filteredAccountOptions.map((option) => option.value));
      const nextAccounts = current.accounts.filter((accountId) => allowed.has(accountId));

      if (nextAccounts.length === current.accounts.length) {
        return current;
      }

      return {
        ...current,
        accounts: nextAccounts,
      };
    });
  }, [filteredAccountOptions]);

  const { downloadCsv, downloadPdf, printPdf } = useSocialMediaReportActions(
    projectId || null,
    locale,
  );

  const hasReportData =
    meta?.has_data ??
    Boolean(kpis && (accounts.length > 0 || topPosts.length > 0 || platformGroups.length > 0));
  const isInitialLoading = isLoading && !report;

  const canApply =
    Boolean(pendingFilters.from && pendingFilters.to);

  const handleApply = () => {
    if (!canApply) return;
    setAppliedFilters({
      ...pendingFilters,
      platforms: [...pendingFilters.platforms],
      accounts: [...pendingFilters.accounts],
    });
  };

  const handleClear = () => {
    setPendingFilters(createDefaultReportFilters());
    setAppliedFilters(createDefaultReportFilters());
  };

  const exportLabels = useMemo(() => {
    return {
      pdf: t("reports.exportPdf"),
      csv: t("reports.exportCsv"),
      print: t("reports.print"),
    };
  }, [t]);

  const handleExportPdf = useCallback(async () => {
    setExportingFormat("pdf");
    try {
      await downloadPdf(appliedQueryFilters);
    } finally {
      setExportingFormat(null);
    }
  }, [appliedQueryFilters, downloadPdf]);

  const handleExportCsv = useCallback(async () => {
    setExportingFormat("csv");
    try {
      await downloadCsv(appliedQueryFilters);
    } finally {
      setExportingFormat(null);
    }
  }, [appliedQueryFilters, downloadCsv]);

  const handlePrint = useCallback(async () => {
    if (!projectId) return;

    setIsPrinting(true);
    try {
      await printPdf(appliedQueryFilters);
    } finally {
      setIsPrinting(false);
    }
  }, [appliedQueryFilters, printPdf, projectId]);

  const headerActions = useMemo(() => {
    const isExportingPdf = exportingFormat === "pdf";
    const isExportingCsv = exportingFormat === "csv";

    return [
      {
        label: isExportingPdf ? t("common.loading") : exportLabels.pdf,
        icon: <FileText className="h-5 w-5" />,
        onClick: handleExportPdf,
        variant: "outline" as const,
        disabled: Boolean(exportingFormat),
        actionKey: "reports.export",
      },
      {
        label: isExportingCsv ? t("common.loading") : exportLabels.csv,
        icon: <Download className="h-5 w-5" />,
        onClick: handleExportCsv,
        variant: "outline" as const,
        disabled: Boolean(exportingFormat),
        actionKey: "reports.export",
      },
      {
        label: isPrinting ? t("common.loading") : exportLabels.print,
        icon: <Printer className="h-5 w-5" />,
        onClick: handlePrint,
        variant: "outline" as const,
        disabled: isPrinting,
        actionKey: "reports.print",
      },
    ];
  }, [exportLabels, exportingFormat, handleExportCsv, handleExportPdf, handlePrint, isPrinting, t]);

  if (!projectId) {
    return (
      <div>
        {showHeader ? (
          <PageHeader
            title={t("socialMedia.reportsPage.title")}
            breadcrumbs={[
              { label: t("dashboard.home") },
              { label: t("socialMedia.reportsPage.title") },
            ]}
          />
        ) : null}
        <div className="p-6">
          <Card className="rounded-[16px] border-border/70 shadow-sm">
            <EmptyState
              icon={FileText}
              title={t("reports.noProjectSelected")}
              description={t("reports.selectProjectDescription")}
              action={{
                label: t("reports.goToProjects"),
                href: "/projects",
              }}
            />
          </Card>
        </div>
      </div>
    );
  }

  if (isInitialLoading) {
    return (
      <div>
        {showHeader ? (
          <PageHeader
            title={t("socialMedia.reportsPage.title")}
            description={t("socialMedia.reportsPage.description")}
            breadcrumbs={[
              { label: t("dashboard.home") },
              { label: t("sidebar.projects"), href: "/projects" },
              { label: project?.name || projectName || t("reports.projectName") },
              { label: t("socialMedia.title"), href: "/social-media" },
              { label: t("socialMedia.reportsPage.title") },
            ]}
            actions={headerActions}
          />
        ) : null}
        <SocialMediaReportsLoading />
      </div>
    );
  }

  if (error && !report) {
    return (
      <div>
        {showHeader ? (
          <PageHeader
            title={t("socialMedia.reportsPage.title")}
            description={t("socialMedia.reportsPage.description")}
            breadcrumbs={[
              { label: t("dashboard.home") },
              { label: t("sidebar.projects"), href: "/projects" },
              { label: project?.name || projectName || t("reports.projectName") },
              { label: t("socialMedia.title"), href: "/social-media" },
              { label: t("socialMedia.reportsPage.title") },
            ]}
          />
        ) : null}
        <div className="p-6">
          <Card className="rounded-[16px] border-border/70 shadow-sm">
            <EmptyState
              icon={FileText}
              title={t("socialMedia.reportsPage.empty.errorTitle")}
              description={t("socialMedia.reportsPage.empty.errorDescription")}
            />
          </Card>
        </div>
      </div>
    );
  }

  if (!hasReportData || !kpis) {
    return (
      <div>
        {showHeader ? (
          <PageHeader
            title={t("socialMedia.reportsPage.title")}
            description={t("socialMedia.reportsPage.description")}
            breadcrumbs={[
              { label: t("dashboard.home") },
              { label: t("sidebar.projects"), href: "/projects" },
              { label: project?.name || projectName || t("reports.projectName") },
              { label: t("socialMedia.title"), href: "/social-media" },
              { label: t("socialMedia.reportsPage.title") },
            ]}
            actions={headerActions}
          />
        ) : null}
        <div className="p-6">
          <Card className="rounded-[16px] border-border/70 shadow-sm">
            <EmptyState
              icon={FileText}
              title={t("socialMedia.reportsPage.empty.noDataTitle")}
              description={t("socialMedia.reportsPage.empty.noDataDescription")}
            />
          </Card>
        </div>
      </div>
    );
  }

  const charts = report?.charts;
  const isRTL = locale === "ar";
  const summaryCardData = {
    title: t("socialMedia.reportsPage.summary.title"),
    description: t("socialMedia.reportsPage.summary.description"),
    status: kpis.total_posts > 0 ? ("inProgress" as const) : ("notStarted" as const),
    statusLabel:
      kpis.total_posts > 0
        ? t("socialMedia.reportsPage.status.active")
        : t("socialMedia.reportsPage.status.noData"),
    progress: Math.max(0, Math.min(100, kpis.engagement_rate || 0)),
    phaseCount: kpis.total_accounts,
    totalTasks: kpis.total_posts,
    completedTasks: kpis.total_followers,
    inProgressTasks: kpis.total_engagement,
    pendingTasks: kpis.total_reach,
    overdueTasks: kpis.active_accounts,
    phaseCountLabel: t("socialMedia.reportsPage.summary.totalAccounts"),
    totalTasksLabel: t("socialMedia.reportsPage.summary.totalPosts"),
    completedTasksLabel: t("socialMedia.reportsPage.summary.totalFollowers"),
    inProgressTasksLabel: t("socialMedia.reportsPage.summary.totalEngagement"),
    pendingTasksLabel: t("socialMedia.reportsPage.summary.totalReach"),
    overdueTasksLabel: t("socialMedia.reportsPage.summary.activeAccounts"),
    progressLabel: t("socialMedia.reportsPage.summary.engagementRate"),
  };

  const heroAccountsCount =
    appliedFilters.accounts.length > 0
      ? appliedFilters.accounts.length
      : availableAccounts.length;
  const heroPlatformsCount =
    appliedFilters.platforms.length > 0
      ? appliedFilters.platforms.length
      : availablePlatforms.length > 0
        ? availablePlatforms.length
        : PLATFORM_VALUES.length;

  return (
    <div>
      {showHeader ? (
        <PageHeader
          title={t("socialMedia.reportsPage.title")}
          description={t("socialMedia.reportsPage.description")}
          breadcrumbs={[
            { label: t("dashboard.home") },
            { label: t("sidebar.projects"), href: "/projects" },
            { label: project?.name || projectName || t("reports.projectName") },
            { label: t("socialMedia.title"), href: "/social-media" },
            { label: t("socialMedia.reportsPage.title") },
          ]}
        />
      ) : null}

      <div className="space-y-6 p-4 sm:p-6">
        <SocialMediaReportsHero
          title={project?.name || projectName || t("reports.projectName")}
          from={appliedFilters.from}
          to={appliedFilters.to}
          accountsCount={heroAccountsCount}
          platformsCount={heroPlatformsCount}
          actions={headerActions}
          t={t}
        />

        <SocialMediaReportFiltersCard
          t={t}
          locale={locale as Locale}
          pendingFilters={pendingFilters}
          platformOptions={platformOptions}
          accountOptions={filteredAccountOptions}
          onPresetChange={(value) =>
            setPendingFilters((current) => ({ ...current, preset: value }))
          }
          onFromChange={(value) =>
            setPendingFilters((current) => ({ ...current, from: value }))
          }
          onToChange={(value) =>
            setPendingFilters((current) => ({ ...current, to: value }))
          }
          onPlatformsChange={(values) =>
            setPendingFilters((current) => ({
              ...current,
              platforms: values.filter((value): value is SocialPlatform =>
                PLATFORM_VALUES.includes(value as SocialPlatform),
              ),
            }))
          }
          onAccountsChange={(values) =>
            setPendingFilters((current) => ({
              ...current,
              accounts: values,
            }))
          }
          onAccountTypeChange={(value) =>
            setPendingFilters((current) => ({ ...current, accountType: value }))
          }
          onSortChange={(value) =>
            setPendingFilters((current) => ({ ...current, sort: value }))
          }
          onApply={handleApply}
          onClear={handleClear}
          isRefreshing={isRefreshing}
          canApply={canApply}
        />

        <ProjectInfoCard {...summaryCardData} />

        <ReportsKpisSection kpis={kpis} t={t} />

        {charts ? (
          <ReportsChartsSection
            charts={charts}
            t={t}
            formatDate={(value) => formatDate(value)}
            isRTL={isRTL}
          />
        ) : null}

        <SocialMediaReportAccountsBreakdown accounts={accounts} t={t} />

        <SocialMediaReportTopPosts
          posts={topPosts.map((post) => ({
            id: post.id,
            platform: post.platform,
            account_name: accountNameByPlatform.get(String(post.platform)) ?? null,
            title: post.title,
            content_excerpt: post.content_excerpt,
            post_url: post.post_url,
            published_at: post.published_at,
            likes: post.likes,
            comments: post.comments,
            shares: post.shares,
            engagement: post.engagement,
          }))}
          t={t}
          formatPublishedAt={(value) => formatPublishedAt(value)}
        />

        {meta?.generated_at ? (
          <div className="pt-2 text-center text-xs text-muted-foreground">
            {t("socialMedia.reportsPage.generatedAt")}{" "}
            {safeFormatDateTime(meta.generated_at)}
          </div>
        ) : null}
      </div>
    </div>
  );
}
