import React, { useEffect, useState, lazy, Suspense, useRef } from "react";
import { Link, useNavigate } from "react-router-dom";
import PageMeta from "../../components/common/PageMeta";
import CreditBalanceWidget from "../../components/dashboard/CreditBalanceWidget";
import UsageChartWidget from "../../components/dashboard/UsageChartWidget";
import EnhancedMetricCard from "../../components/dashboard/EnhancedMetricCard";
import ComponentCard from "../../components/common/ComponentCard";
import PageHeader from "../../components/common/PageHeader";
import WorkflowGuide from "../../components/onboarding/WorkflowGuide";
import { useOnboardingStore } from "../../store/onboardingStore";
import { Card } from "../../components/ui/card";
import { ProgressBar } from "../../components/ui/progress";
import { ApexOptions } from "apexcharts";
import { 
  ListIcon, 
  FileIcon,
  FileTextIcon,
  BoltIcon,
  GroupIcon,
  CheckCircleIcon,
  ArrowRightIcon,
  PlugInIcon,
  PencilIcon,
  UserIcon,
  PieChartIcon,
  ClockIcon,
  PaperPlaneIcon,
  PlusIcon,
  ChevronDownIcon,
  GridIcon,
} from "../../icons";
import { 
  fetchKeywords, 
  fetchClusters, 
  fetchContentIdeas,
  fetchTasks,
  fetchContent,
  fetchContentImages,
  fetchSites,
  Site,
} from "../../services/api";
import { useSiteStore } from "../../store/siteStore";
import { useSectorStore } from "../../store/sectorStore";
import { useToast } from "../../components/ui/toast/ToastContainer";
import { Dropdown } from "../../components/ui/dropdown/Dropdown";
import { DropdownItem } from "../../components/ui/dropdown/DropdownItem";
import Button from "../../components/ui/button/Button";
import SelectDropdown from "../../components/form/SelectDropdown";
import { useAuthStore } from "../../store/authStore";
import SiteAndSectorSelector from "../../components/common/SiteAndSectorSelector";

const Chart = lazy(() => import("react-apexcharts").then((mod) => ({ default: mod.default })));

// Homepage Site Selector Component (with "All Sites" option)
interface HomepageSiteSelectorProps {
  sites: Site[];
  siteFilter: 'all' | number;
  onSiteFilterChange: (value: string) => void;
}

function HomepageSiteSelector({ sites, siteFilter, onSiteFilterChange }: HomepageSiteSelectorProps) {
  const [isOpen, setIsOpen] = useState(false);
  const buttonRef = useRef<HTMLButtonElement>(null);
  const { activeSite } = useSiteStore();

  const displayText = siteFilter === 'all' 
    ? 'All Sites' 
    : sites.find(s => s.id === siteFilter)?.name || activeSite?.name || 'Select Site';

  return (
    <div className="relative inline-block">
      <button
        ref={buttonRef}
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-2 px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-brand-200 rounded-lg hover:bg-brand-50 hover:border-brand-300 dark:bg-gray-800 dark:text-gray-300 dark:border-brand-700/50 dark:hover:bg-brand-500/10 dark:hover:border-brand-600/50 transition-colors"
        aria-label="Filter sites"
      >
        <span className="flex items-center gap-2">
          <svg
            className="w-4 h-4 text-brand-500 dark:text-brand-400"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"
            />
          </svg>
          <span className="max-w-[150px] truncate">{displayText}</span>
        </span>
        <ChevronDownIcon className={`w-4 h-4 text-brand-500 dark:text-brand-400 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
      </button>
      <Dropdown
        isOpen={isOpen}
        onClose={() => setIsOpen(false)}
        anchorRef={buttonRef}
        placement="bottom-left"
        className="w-64 p-2"
      >
        <DropdownItem
          onItemClick={() => {
            onSiteFilterChange('all');
            setIsOpen(false);
          }}
          className={`flex items-center gap-3 px-3 py-2 font-medium rounded-lg text-sm text-left ${
            siteFilter === 'all'
              ? "bg-brand-50 text-brand-700 dark:bg-brand-500/20 dark:text-brand-300"
              : "text-gray-700 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-white/5 dark:hover:text-gray-300"
          }`}
        >
          <span className="flex-1">All Sites</span>
          {siteFilter === 'all' && (
            <svg
              className="w-4 h-4 text-brand-600 dark:text-brand-400"
              fill="currentColor"
              viewBox="0 0 20 20"
            >
              <path
                fillRule="evenodd"
                d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                clipRule="evenodd"
              />
            </svg>
          )}
        </DropdownItem>
        {sites.map((site) => (
          <DropdownItem
            key={site.id}
            onItemClick={() => {
              onSiteFilterChange(site.id.toString());
              setIsOpen(false);
            }}
            className={`flex items-center gap-3 px-3 py-2 font-medium rounded-lg text-sm text-left ${
              siteFilter === site.id
                ? "bg-brand-50 text-brand-700 dark:bg-brand-500/20 dark:text-brand-300"
                : "text-gray-700 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-white/5 dark:hover:text-gray-300"
            }`}
          >
            <span className="flex-1">{site.name}</span>
            {siteFilter === site.id && (
              <svg
                className="w-4 h-4 text-brand-600 dark:text-brand-400"
                fill="currentColor"
                viewBox="0 0 20 20"
              >
                <path
                  fillRule="evenodd"
                  d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                  clipRule="evenodd"
                />
              </svg>
            )}
          </DropdownItem>
        ))}
      </Dropdown>
    </div>
  );
}

interface AppInsights {
  totalKeywords: number;
  totalClusters: number;
  totalIdeas: number;
  totalTasks: number;
  totalContent: number;
  totalImages: number;
  publishedContent: number;
  workflowCompletionRate: number;
  contentThisWeek: number;
  contentThisMonth: number;
  automationEnabled: boolean;
}

const workflowSteps = [
  {
    id: 1,
    title: "Discover Keywords",
    description: "Find high-volume keywords from our global database",
    icon: <ListIcon />,
    color: "blue",
    path: "/planner/keyword-opportunities"
  },
  {
    id: 2,
    title: "Cluster Keywords",
    description: "Group related keywords into strategic clusters",
    icon: <GroupIcon />,
    color: "purple",
    path: "/planner/clusters"
  },
  {
    id: 3,
    title: "Generate Ideas",
    description: "AI creates content ideas from keyword clusters",
    icon: <BoltIcon />,
    color: "orange",
    path: "/planner/ideas"
  },
  {
    id: 4,
    title: "Create Tasks",
    description: "Convert ideas into actionable writing tasks",
    icon: <CheckCircleIcon />,
    color: "indigo",
    path: "/writer/tasks"
  },
  {
    id: 5,
    title: "Write Content",
    description: "AI generates full content pieces automatically",
    icon: <FileTextIcon />,
    color: "green",
    path: "/writer/content"
  },
  {
    id: 6,
    title: "Generate Images",
    description: "Create featured and in-article images",
    icon: <FileIcon />,
    color: "pink",
    path: "/writer/images"
  },
  {
    id: 7,
    title: "Publish",
    description: "Content ready for publication",
    icon: <CheckCircleIcon />,
    color: "success",
    path: "/writer/published"
  }
];

export default function Home() {
  const toast = useToast();
  const navigate = useNavigate();
  const { activeSite, setActiveSite, loadActiveSite } = useSiteStore();
  const { activeSector } = useSectorStore();
  const { isGuideDismissed, showGuide, loadFromBackend } = useOnboardingStore();
  const { user } = useAuthStore();
  
  const [insights, setInsights] = useState<AppInsights | null>(null);
  const [loading, setLoading] = useState(true);
  const [lastUpdated, setLastUpdated] = useState<Date>(new Date());
  
  // Site management state
  const [sites, setSites] = useState<Site[]>([]);
  const [sitesLoading, setSitesLoading] = useState(true);
  const [siteFilter, setSiteFilter] = useState<'all' | number>('all');
  const [showAddSite, setShowAddSite] = useState(false);
  const [isSiteSelectorOpen, setIsSiteSelectorOpen] = useState(false);
  const siteSelectorRef = useRef<HTMLButtonElement>(null);
  
  // Progress tracking state
  const [progress, setProgress] = useState({
    hasSiteWithSectors: false,
    keywordsCount: 0,
    clustersCount: 0,
    ideasCount: 0,
    contentCount: 0,
    imagesCount: 0,
    publishedCount: 0,
    completionPercentage: 0,
  });
  
  // Get plan limits - check both possible structures
  const maxSites = (user?.account as any)?.plan?.max_sites || (user as any)?.account?.plan?.max_sites || 0;
  const canAddMoreSites = maxSites === 0 || sites.length < maxSites;

  // Load sites and guide state
  useEffect(() => {
    loadSites();
    loadFromBackend().catch(() => {
      // Silently fail - local state will be used
    });
  }, [loadFromBackend]);

  // Load active site if not set
  useEffect(() => {
    if (!activeSite && sites.length > 0) {
      loadActiveSite();
    }
  }, [sites, activeSite, loadActiveSite]);

  // Set initial site filter based on sites
  useEffect(() => {
    if (sites.length === 0) {
      setSiteFilter('all');
    } else if (sites.length === 1 && sites[0]) {
      // For single site users, use that site
      setSiteFilter(sites[0].id);
    } else if (sites.length > 1 && siteFilter === 'all') {
      // For multi-site users, default to "All Sites" (already set)
      // Keep it as is
    }
  }, [sites.length]);

  // Show guide logic: show if no sites OR manually triggered
  useEffect(() => {
    if (sites.length === 0) {
      // Always show if no sites
      showGuide();
    } else if (showAddSite) {
      // Show if manually triggered
      showGuide();
    } else if (!isGuideDismissed && sites.length === 0) {
      // Show on first visit if not dismissed and no sites
      showGuide();
    }
  }, [sites.length, showAddSite, isGuideDismissed, showGuide]);

  const loadSites = async () => {
    try {
      setSitesLoading(true);
      const response = await fetchSites();
      const activeSites = (response.results || []).filter(site => site.is_active);
      setSites(activeSites);
    } catch (error: any) {
      console.error('Failed to load sites:', error);
      toast.error(`Failed to load sites: ${error.message}`);
    } finally {
      setSitesLoading(false);
    }
  };

  const handleSiteFilterChange = (value: string) => {
    if (value === 'all') {
      setSiteFilter('all');
    } else {
      const siteId = parseInt(value, 10);
      setSiteFilter(siteId);
      // Optionally set as active site
      const site = sites.find(s => s.id === siteId);
      if (site) {
        setActiveSite(site);
      }
    }
    setIsSiteSelectorOpen(false);
  };

  const handleAddSiteClick = () => {
    setShowAddSite(true);
    showGuide();
  };

  const handleSiteAdded = () => {
    setShowAddSite(false);
    loadSites();
    fetchAppInsights();
  };

  const appModules = [
    {
      title: "Planner",
      description: "Keyword research, clustering, and content planning",
      icon: PieChartIcon,
      color: "from-[var(--color-primary)] to-[var(--color-primary-dark)]",
      path: "/planner",
      count: insights?.totalClusters || 0,
      status: "active",
      metric: `${insights?.totalKeywords || 0} keywords`,
    },
    {
      title: "Writer",
      description: "AI content generation, editing, and publishing",
      icon: PencilIcon,
      color: "from-[var(--color-success)] to-[var(--color-success-dark)]",
      path: "/writer",
      count: insights?.totalContent || 0,
      status: "active",
      metric: `${insights?.publishedContent || 0} published`,
    },
    {
      title: "Thinker",
      description: "Prompts, author profiles, and content strategies",
      icon: BoltIcon,
      color: "from-[var(--color-warning)] to-[var(--color-warning-dark)]",
      path: "/thinker",
      count: 0,
      status: "active",
      metric: "24 prompts",
    },
    {
      title: "Automation",
      description: "Workflow automation and scheduled tasks",
      icon: PlugInIcon,
      color: "from-[var(--color-purple)] to-[var(--color-purple-dark)]",
      path: "/automation",
      count: 0,
      status: "active",
      metric: insights?.automationEnabled ? "3 active" : "Not configured",
    },
  ];

  const recentActivity = [
    {
      id: 1,
      type: "Content Published",
      description: "5 pieces published to WordPress",
      timestamp: new Date(Date.now() - 30 * 60 * 1000),
      icon: PaperPlaneIcon,
      color: "text-green-600",
    },
    {
      id: 2,
      type: "Ideas Generated",
      description: "12 new content ideas from clusters",
      timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000),
      icon: BoltIcon,
      color: "text-orange-600",
    },
    {
      id: 3,
      type: "Keywords Clustered",
      description: "45 keywords grouped into 8 clusters",
      timestamp: new Date(Date.now() - 4 * 60 * 60 * 1000),
      icon: GroupIcon,
      color: "text-purple-600",
    },
    {
      id: 4,
      type: "Content Generated",
      description: "8 new content pieces created",
      timestamp: new Date(Date.now() - 6 * 60 * 60 * 1000),
      icon: FileTextIcon,
      color: "text-blue-600",
    },
  ];

  const fetchAppInsights = async () => {
    try {
      setLoading(true);
      const delay = (ms: number) => new Promise((res) => setTimeout(res, ms));
      
      // Determine site_id based on filter
      const siteId = siteFilter === 'all' ? undefined : siteFilter;
      
      // Fetch sequentially with small delays to avoid burst throttling
      const keywordsRes = await fetchKeywords({ page_size: 1, site_id: siteId });
      await delay(120);
      const clustersRes = await fetchClusters({ page_size: 1, site_id: siteId });
      await delay(120);
      const ideasRes = await fetchContentIdeas({ page_size: 1, site_id: siteId });
      await delay(120);
      const tasksRes = await fetchTasks({ page_size: 1, site_id: siteId });
      await delay(120);
      const contentRes = await fetchContent({ page_size: 1, site_id: siteId });
      await delay(120);
      const imagesRes = await fetchContentImages({ page_size: 1, site_id: siteId });

      const totalKeywords = keywordsRes.count || 0;
      const totalClusters = clustersRes.count || 0;
      const totalIdeas = ideasRes.count || 0;
      const totalTasks = tasksRes.count || 0;
      const totalContent = contentRes.count || 0;
      const totalImages = imagesRes.count || 0;

      // Check for published content (status = 'published')
      const publishedContent = totalContent; // TODO: Filter by published status when API supports it
      const workflowCompletionRate = totalKeywords > 0 
        ? Math.round((publishedContent / totalKeywords) * 100) 
        : 0;

      // Check if site has industry and sectors (site with sectors means industry is set)
      const hasSiteWithSectors = sites.some(site => site.active_sectors_count > 0);

      setInsights({
        totalKeywords,
        totalClusters,
        totalIdeas,
        totalTasks,
        totalContent,
        totalImages,
        publishedContent,
        workflowCompletionRate,
        contentThisWeek: Math.floor(totalContent * 0.3),
        contentThisMonth: Math.floor(totalContent * 0.7),
        automationEnabled: false,
      });

      // Update progress
      const milestones = [
        hasSiteWithSectors,
        totalKeywords > 0,
        totalClusters > 0,
        totalIdeas > 0,
        totalContent > 0,
        publishedContent > 0,
      ];
      const completedMilestones = milestones.filter(Boolean).length;
      const completionPercentage = Math.round((completedMilestones / milestones.length) * 100);

      setProgress({
        hasSiteWithSectors,
        keywordsCount: totalKeywords,
        clustersCount: totalClusters,
        ideasCount: totalIdeas,
        contentCount: totalContent,
        imagesCount: totalImages,
        publishedCount: publishedContent,
        completionPercentage,
      });
      
      setLastUpdated(new Date());
    } catch (error: any) {
      if (error?.status === 429) {
        // Back off and retry once after a short delay
        setTimeout(() => {
          fetchAppInsights();
        }, 2000);
      } else {
        console.error('Error fetching insights:', error);
        toast.error(`Failed to load insights: ${error.message}`);
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchAppInsights();
  }, [siteFilter, activeSector]);

  const chartOptions: ApexOptions = {
    chart: {
      type: "area",
      height: 300,
      toolbar: { show: false },
      zoom: { enabled: false },
    },
    stroke: {
      curve: "smooth",
      width: 3,
    },
    xaxis: {
      categories: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
      labels: { style: { colors: "#6b7280" } },
    },
    yaxis: {
      labels: { style: { colors: "#6b7280" } },
    },
    legend: {
      position: "top",
      labels: { colors: "#6b7280" },
    },
    colors: ["var(--color-primary)", "var(--color-success)", "var(--color-purple)"],
    grid: {
      borderColor: "#e5e7eb",
    },
    fill: {
      type: "gradient",
      gradient: {
        opacityFrom: 0.6,
        opacityTo: 0.1,
      },
    },
  };

  const chartSeries = [
    {
      name: "Content Created",
      data: [12, 19, 15, 25, 22, 18, 24],
    },
    {
      name: "Keywords Added",
      data: [8, 12, 10, 15, 14, 11, 16],
    },
    {
      name: "Ideas Generated",
      data: [5, 8, 6, 10, 9, 7, 11],
    },
  ];

  const formatTimeAgo = (date: Date) => {
    const minutes = Math.floor((Date.now() - date.getTime()) / 60000);
    if (minutes < 60) return `${minutes}m ago`;
    const hours = Math.floor(minutes / 60);
    if (hours < 24) return `${hours}h ago`;
    const days = Math.floor(hours / 24);
    return `${days}d ago`;
  };

  return (
    <>
      <PageMeta
        title="Dashboard - IGNY8"
        description="IGNY8 AI-Powered Content Creation Dashboard"
      />
      
      {/* Custom Header with Site Selector and Refresh */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-6">
        <div className="flex-1">
          <h2 className="text-2xl font-bold text-gray-800 dark:text-white/90">Dashboard</h2>
          {lastUpdated && (
            <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
              Last updated: {lastUpdated.toLocaleTimeString()}
            </p>
          )}
        </div>
        <div className="flex items-center gap-3">
          {/* Site Selector with "All Sites" option for homepage - Before Refresh */}
          {sites.length > 1 && (
            <HomepageSiteSelector
              sites={sites}
              siteFilter={siteFilter}
              onSiteFilterChange={handleSiteFilterChange}
            />
          )}
          <button
            onClick={fetchAppInsights}
            className="px-4 py-2 text-sm font-medium text-brand-500 hover:text-brand-600 border border-brand-200 rounded-lg hover:bg-brand-50 dark:border-brand-800 dark:hover:bg-brand-500/10 transition-colors"
          >
            Refresh
          </button>
        </div>
      </div>

      {/* Banner with Add Site Button and Site Count/Title */}
      <div className="mb-6">
        <div className="bg-gradient-to-r from-brand-500 to-purple-600 rounded-2xl p-6 text-white relative overflow-hidden">
          <div className="absolute inset-0 bg-grid-white/10 [mask-image:linear-gradient(0deg,white,transparent)]"></div>
          <div className="relative z-10 flex items-center justify-between">
            <div>
              <h1 className="text-3xl md:text-4xl font-bold mb-2">
                AI-Powered Content Creation Workflow
              </h1>
              <p className="text-lg text-white/90">
                Transform keywords into published content with intelligent automation.
              </p>
            </div>
            {/* Add Site Button and Site Count in Single Row - Right Side */}
            <div className="flex items-center gap-4">
              {sites.length > 0 && (
                <div className="text-right">
                  {sites.length > 1 ? (
                    <div className="text-3xl font-bold text-white">
                      {sites.length}/{maxSites || '∞'} Sites
                    </div>
                  ) : (
                    <div className="text-xl font-semibold text-white/90">
                      {activeSite?.name || sites[0]?.name}
                    </div>
                  )}
                </div>
              )}
              {canAddMoreSites && (
                <Button
                  onClick={handleAddSiteClick}
                  variant="solid"
                  tone="brand"
                  size="lg"
                  shape="pill"
                  startIcon={<PlusIcon className="w-6 h-6 fill-current" />}
                  className="!bg-white !text-brand-600 hover:!bg-gray-50 font-bold text-base px-8 py-4 shadow-2xl hover:shadow-[0_25px_50px_-12px_rgba(0,0,0,0.4)] hover:scale-105 active:scale-100 transition-all duration-200"
                >
                  Add Site
                </Button>
              )}
              {!canAddMoreSites && sites.length > 0 && maxSites > 0 && (
                <div className="text-base text-white/80 font-medium">
                  Plan limit reached
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Welcome/Guide Screen - Conditional */}
      {(sites.length === 0 || showAddSite) && (
        <div className="mb-6">
          <WorkflowGuide onSiteAdded={handleSiteAdded} />
        </div>
      )}

     

      <div className="space-y-6">
        {/* Progress Flow - Circular Design with Progress Bar */}
        <ComponentCard title="Your Progress" desc="Track your content creation workflow completion">
          {/* Percentage and Progress Bar */}
          <div className="mb-8">
            <div className="flex items-center justify-between mb-3">
              <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
                Overall Completion
              </span>
              <span className="text-2xl font-bold text-brand-600 dark:text-brand-400">
                {progress.completionPercentage}%
              </span>
            </div>
            <ProgressBar 
              value={progress.completionPercentage} 
              size="lg"
              color="primary"
              className="h-4"
            />
          </div>
          
          {/* Icon-based Progress Flow */}
          <div className="py-6">
            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-6">
              <Link to="/sites" className="flex flex-col items-center gap-3">
                <div className="flex items-center justify-center w-20 h-20 text-[#c0c7d3]">
                  <GridIcon className="w-14 h-14" strokeWidth={2.4} />
                </div>
                <div className="text-center">
                  <div className="text-sm font-semibold text-gray-800 dark:text-white">Site & Sectors</div>
                  <div className="text-lg font-bold text-gray-900 dark:text-white">{sites.filter(s => s.active_sectors_count > 0).length}</div>
                  <div className="text-xs text-gray-500 dark:text-gray-400">Industry & sectors configured</div>
                </div>
              </Link>

              <Link to="/planner/keyword-opportunities" className="flex flex-col items-center gap-3">
                <div className="flex items-center justify-center w-20 h-20 text-[#8bb9ff]">
                  <ListIcon className="w-14 h-14" strokeWidth={2.4} />
                </div>
                <div className="text-center">
                  <div className="text-sm font-semibold text-gray-800">Keywords</div>
                  <div className="text-lg font-bold text-blue-600">{progress.keywordsCount}</div>
                  <div className="text-xs text-gray-500">Keywords added from opportunities</div>
                </div>
              </Link>

              <Link to="/planner/clusters" className="flex flex-col items-center gap-3">
                <div className="flex items-center justify-center w-20 h-20 text-[#c088ff]">
                  <GroupIcon className="w-14 h-14" strokeWidth={2.4} />
                </div>
                <div className="text-center">
                  <div className="text-sm font-semibold text-gray-800">Clusters</div>
                  <div className="text-lg font-bold text-purple-600">{progress.clustersCount}</div>
                  <div className="text-xs text-gray-500">Keywords grouped into clusters</div>
                </div>
              </Link>

              <Link to="/planner/ideas" className="flex flex-col items-center gap-3">
                <div className="flex items-center justify-center w-20 h-20 text-[#f9a172]">
                  <BoltIcon className="w-14 h-14" strokeWidth={2.4} />
                </div>
                <div className="text-center">
                  <div className="text-sm font-semibold text-gray-800">Ideas</div>
                  <div className="text-lg font-bold text-orange-600">{progress.ideasCount}</div>
                  <div className="text-xs text-gray-500">Content ideas and outlines</div>
                </div>
              </Link>

              <Link to="/writer/content" className="flex flex-col items-center gap-3">
                <div className="flex items-center justify-center w-20 h-20 text-[#79cd95]">
                  <FileTextIcon className="w-14 h-14" strokeWidth={2.4} />
                </div>
                <div className="text-center">
                  <div className="text-sm font-semibold text-gray-800">Content</div>
                  <div className="text-lg font-bold text-green-600">{progress.contentCount}</div>
                  <div className="text-xs text-gray-500">Content pieces + images created</div>
                </div>
              </Link>

              <Link to="/writer/published" className="flex flex-col items-center gap-3">
                <div className="flex items-center justify-center w-20 h-20 text-[#8c97ff]">
                  <PaperPlaneIcon className="w-14 h-14" strokeWidth={2.4} />
                </div>
                <div className="text-center">
                  <div className="text-sm font-semibold text-gray-800">Published</div>
                  <div className="text-lg font-bold text-indigo-600">{progress.publishedCount}</div>
                  <div className="text-xs text-gray-500">Content published to site</div>
                </div>
              </Link>
            </div>
          </div>
        </ComponentCard>

 {/* Quick Actions - Below Welcome Screen */}
 <ComponentCard title="Quick Actions" desc="Common tasks and shortcuts" className="mb-6">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
          <Link
            to="/planner/keyword-opportunities"
            className="flex items-center gap-4 p-4 rounded-xl border border-gray-200 bg-white hover:border-gray-300 hover:shadow-sm transition group"
          >
            <div className="size-12 rounded-lg bg-blue-50 text-blue-600 border border-blue-100 flex items-center justify-center">
              <ListIcon className="h-6 w-6" />
            </div>
            <div className="flex-1">
              <h4 className="font-semibold text-gray-900">Keyword Research</h4>
              <p className="text-xs text-gray-600">Discover opportunities</p>
            </div>
            <ArrowRightIcon className="h-5 w-5 text-gray-400 group-hover:text-gray-600 transition" />
          </Link>

          <Link
            to="/planner/clusters"
            className="flex items-center gap-4 p-4 rounded-xl border border-gray-200 bg-white hover:border-gray-300 hover:shadow-sm transition group"
          >
            <div className="size-12 rounded-lg bg-purple-50 text-purple-600 border border-purple-100 flex items-center justify-center">
              <GroupIcon className="h-6 w-6" />
            </div>
            <div className="flex-1">
              <h4 className="font-semibold text-gray-900">Clustering & Ideas</h4>
              <p className="text-xs text-gray-600">Organize strategy</p>
            </div>
            <ArrowRightIcon className="h-5 w-5 text-gray-400 group-hover:text-gray-600 transition" />
          </Link>

          <Link
            to="/writer/content"
            className="flex items-center gap-4 p-4 rounded-xl border border-gray-200 bg-white hover:border-gray-300 hover:shadow-sm transition group"
          >
            <div className="size-12 rounded-lg bg-green-50 text-green-600 border border-green-100 flex items-center justify-center">
              <PencilIcon className="h-6 w-6" />
            </div>
            <div className="flex-1">
              <h4 className="font-semibold text-gray-900">Content Generation</h4>
              <p className="text-xs text-gray-600">Create content</p>
            </div>
            <ArrowRightIcon className="h-5 w-5 text-gray-400 group-hover:text-gray-600 transition" />
          </Link>

          <Link
            to="/linker/content"
            className="flex items-center gap-4 p-4 rounded-xl border border-gray-200 bg-white hover:border-gray-300 hover:shadow-sm transition group"
          >
            <div className="size-12 rounded-lg bg-indigo-50 text-indigo-600 border border-indigo-100 flex items-center justify-center">
              <PlugInIcon className="h-6 w-6" />
            </div>
            <div className="flex-1">
              <h4 className="font-semibold text-gray-900">Internal Linking</h4>
              <p className="text-xs text-gray-600">Link content</p>
            </div>
            <ArrowRightIcon className="h-5 w-5 text-gray-400 group-hover:text-gray-600 transition" />
          </Link>

          <Link
            to="/optimizer/content"
            className="flex items-center gap-4 p-4 rounded-xl border border-gray-200 bg-white hover:border-gray-300 hover:shadow-sm transition group"
          >
            <div className="size-12 rounded-lg bg-orange-50 text-orange-600 border border-orange-100 flex items-center justify-center">
              <BoltIcon className="h-6 w-6" />
            </div>
            <div className="flex-1">
              <h4 className="font-semibold text-gray-900">Content Optimization</h4>
              <p className="text-xs text-gray-600">Optimize content</p>
            </div>
            <ArrowRightIcon className="h-5 w-5 text-gray-400 group-hover:text-gray-600 transition" />
          </Link>
        </div>
      </ComponentCard>
      1
        {/* Key Metrics */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          <EnhancedMetricCard
            title="Total Keywords"
            value={insights?.totalKeywords.toLocaleString() || "0"}
            subtitle={`${insights?.totalClusters || 0} clusters • ${insights?.totalIdeas || 0} ideas`}
            icon={<ListIcon className="size-6" />}
            accentColor="blue"
            trend={0}
            href="/planner/keywords"
          />
          <EnhancedMetricCard
            title="Content Pieces"
            value={insights?.totalContent.toLocaleString() || "0"}
            subtitle={`${insights?.publishedContent || 0} published • ${insights?.contentThisWeek || 0} this week`}
            icon={<FileTextIcon className="size-6" />}
            accentColor="green"
            trend={0}
            href="/writer/content"
          />
          <EnhancedMetricCard
            title="Images Generated"
            value={insights?.totalImages.toLocaleString() || "0"}
            subtitle={`${insights?.totalContent || 0} content pieces • ${insights?.totalTasks || 0} tasks`}
            icon={<FileIcon className="size-6" />}
            accentColor="purple"
            trend={0}
            href="/writer/images"
          />
          <EnhancedMetricCard
            title="Workflow Completion"
            value={`${insights?.workflowCompletionRate || 0}%`}
            subtitle={`${insights?.totalKeywords || 0} keywords → ${insights?.publishedContent || 0} published`}
            icon={<CheckCircleIcon className="size-6" />}
            accentColor="success"
            trend={0}
          />
        </div>

        {/* Credit Balance & Usage - Improved Design */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <ComponentCard title="Credit Balance" desc="Current credit status and usage">
            <div className="space-y-6">
              <div className="text-center py-4">
                <div className="text-4xl font-bold text-brand-600 dark:text-brand-400 mb-2">
                  {user?.account?.credits?.toLocaleString() || '0'}
                </div>
                <div className="text-sm text-gray-600 dark:text-gray-400">Current Credits</div>
              </div>
              
              <div className="space-y-4">
                <div>
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Used This Month</span>
                    <span className="text-sm font-semibold">
                      {user?.account?.credits ? '547' : '0'} / {user?.account?.credits ? '1000' : '0'}
                    </span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-3 dark:bg-gray-700">
                    <div
                      className="bg-brand-500 h-3 rounded-full transition-all"
                      style={{ width: `${user?.account?.credits ? 54.7 : 0}%` }}
                    />
                  </div>
                </div>
                
                <div className="pt-4 border-t border-gray-200 dark:border-gray-700">
                  <div className="flex justify-between items-center">
                    <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Remaining</span>
                    <span className="text-lg font-bold text-green-600 dark:text-green-400">
                      {user?.account?.credits?.toLocaleString() || '0'}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </ComponentCard>
          
          <ComponentCard title="Usage Summary" desc="Credit usage breakdown by operation and model">
            <div className="space-y-6">
              <div className="flex justify-end items-center mb-4">
                <select
                  className="h-9 rounded-lg border border-gray-300 bg-transparent px-3 py-2 text-sm shadow-theme-xs text-gray-800 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/10 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 dark:focus:border-brand-800"
                  defaultValue="month"
                >
                  <option value="week">Last 7 Days</option>
                  <option value="month">This Month</option>
                  <option value="year">This Year</option>
                </select>
              </div>
              
              <div className="grid grid-cols-2 gap-6">
                <div className="text-center p-4 bg-gray-50 dark:bg-gray-800 rounded-lg">
                  <div className="text-sm text-gray-600 dark:text-gray-400 mb-1">Total Credits Used</div>
                  <div className="text-3xl font-bold text-gray-900 dark:text-white">547</div>
                </div>
                <div className="text-center p-4 bg-gray-50 dark:bg-gray-800 rounded-lg">
                  <div className="text-sm text-gray-600 dark:text-gray-400 mb-1">Total Cost</div>
                  <div className="text-3xl font-bold text-gray-900 dark:text-white">$0.34</div>
                </div>
              </div>
              
              <div>
                <h4 className="text-sm font-semibold mb-3 text-gray-900 dark:text-white">By Operation</h4>
                <div className="space-y-3">
                  <div className="flex justify-between items-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                    <span className="text-sm font-medium text-gray-700 dark:text-gray-300 capitalize">Clustering</span>
                    <div className="text-right">
                      <div className="text-sm font-bold text-gray-900 dark:text-white">97 credits</div>
                      <div className="text-xs text-gray-500 dark:text-gray-400">$0.33</div>
                    </div>
                  </div>
                  <div className="flex justify-between items-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                    <span className="text-sm font-medium text-gray-700 dark:text-gray-300 capitalize">Content Generation</span>
                    <div className="text-right">
                      <div className="text-sm font-bold text-gray-900 dark:text-white">450 credits</div>
                      <div className="text-xs text-gray-500 dark:text-gray-400">$0.01</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </ComponentCard>
        </div>              

        {/* Workflow Modules Guide - 2 Columns */}
        <ComponentCard title="Workflow Modules" desc="Explore each module to understand your content creation workflow">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Keyword Research */}
            <div className="rounded-xl p-4 border-b-2 border-blue-500 bg-blue-50 dark:border-blue-500/30 dark:bg-blue-500/15">
              <div className="flex items-start gap-3">
                <div className="size-12 rounded-lg bg-gradient-to-br from-blue-500 to-blue-600 flex items-center justify-center text-white flex-shrink-0">
                  <ListIcon className="h-6 w-6" />
                </div>
                <div className="flex-1">
                  <h4 className="mb-1 text-sm font-semibold text-gray-800 dark:text-white/90">
                    Keyword Research
                  </h4>
                  <p className="text-sm text-gray-600 dark:text-gray-400">
                    Discover high-value keywords from opportunities. Analyze search volume, difficulty, and intent to identify the best keywords for your content strategy. Add keywords to your site to start building your content foundation.
                  </p>
                </div>
              </div>
            </div>

            {/* Clustering & Ideas */}
            <div className="rounded-xl p-4 border-b-2 border-purple-500 bg-purple-50 dark:border-purple-500/30 dark:bg-purple-500/15">
              <div className="flex items-start gap-3">
                <div className="size-12 rounded-lg bg-gradient-to-br from-purple-500 to-purple-600 flex items-center justify-center text-white flex-shrink-0">
                  <GroupIcon className="h-6 w-6" />
                </div>
                <div className="flex-1">
                  <h4 className="mb-1 text-sm font-semibold text-gray-800 dark:text-white/90">
                    Clustering & Ideas
                  </h4>
                  <p className="text-sm text-gray-600 dark:text-gray-400">
                    Organize keywords into thematic clusters to create content groups. Generate content ideas and outlines based on your clusters. This helps you plan a comprehensive content strategy that covers all important topics.
                  </p>
                </div>
              </div>
            </div>

            {/* Content Generation */}
            <div className="rounded-xl p-4 border-b-2 border-green-500 bg-green-50 dark:border-green-500/30 dark:bg-green-500/15">
              <div className="flex items-start gap-3">
                <div className="size-12 rounded-lg bg-gradient-to-br from-green-500 to-green-600 flex items-center justify-center text-white flex-shrink-0">
                  <PencilIcon className="h-6 w-6" />
                </div>
                <div className="flex-1">
                  <h4 className="mb-1 text-sm font-semibold text-gray-800 dark:text-white/90">
                    Content Generation
                  </h4>
                  <p className="text-sm text-gray-600 dark:text-gray-400">
                    Create high-quality, SEO-optimized content using AI. Generate articles, blog posts, and other content pieces based on your ideas and outlines. Each piece is crafted to match your brand voice and target keywords.
                  </p>
                </div>
              </div>
            </div>

            {/* Internal Linking */}
            <div className="rounded-xl p-4 border-b-2 border-indigo-500 bg-indigo-50 dark:border-indigo-500/30 dark:bg-indigo-500/15">
              <div className="flex items-start gap-3">
                <div className="size-12 rounded-lg bg-gradient-to-br from-indigo-500 to-indigo-600 flex items-center justify-center text-white flex-shrink-0">
                  <PlugInIcon className="h-6 w-6" />
                </div>
                <div className="flex-1">
                  <h4 className="mb-1 text-sm font-semibold text-gray-800 dark:text-white/90">
                    Internal Linking
                  </h4>
                  <p className="text-sm text-gray-600 dark:text-gray-400">
                    Automatically identify and create strategic internal links between your content pieces. Improve SEO by connecting related articles, enhancing user navigation, and distributing page authority throughout your site.
                  </p>
                </div>
              </div>
            </div>

            {/* Content Optimization */}
            <div className="rounded-xl p-4 border-b-2 border-orange-500 bg-orange-50 dark:border-orange-500/30 dark:bg-orange-500/15">
              <div className="flex items-start gap-3">
                <div className="size-12 rounded-lg bg-gradient-to-br from-orange-500 to-orange-600 flex items-center justify-center text-white flex-shrink-0">
                  <BoltIcon className="h-6 w-6" />
                </div>
                <div className="flex-1">
                  <h4 className="mb-1 text-sm font-semibold text-gray-800 dark:text-white/90">
                    Content Optimization
                  </h4>
                  <p className="text-sm text-gray-600 dark:text-gray-400">
                    Analyze and optimize your existing content for better SEO performance. Get recommendations for improving readability, keyword density, meta tags, and overall content quality to boost search rankings.
                  </p>
                </div>
              </div>
            </div>

            {/* Image Generation */}
            <div className="rounded-xl p-4 border-b-2 border-pink-500 bg-pink-50 dark:border-pink-500/30 dark:bg-pink-500/15">
              <div className="flex items-start gap-3">
                <div className="size-12 rounded-lg bg-gradient-to-br from-pink-500 to-pink-600 flex items-center justify-center text-white flex-shrink-0">
                  <FileIcon className="h-6 w-6" />
                </div>
                <div className="flex-1">
                  <h4 className="mb-1 text-sm font-semibold text-gray-800 dark:text-white/90">
                    Image Generation
                  </h4>
                  <p className="text-sm text-gray-600 dark:text-gray-400">
                    Generate custom images for your content using AI. Create relevant, high-quality images that match your content theme and brand style. Images are automatically optimized and can be added directly to your content pieces.
                  </p>
                </div>
              </div>
            </div>

            {/* Automation */}
            <div className="rounded-xl p-4 border-b-2 border-teal-500 bg-teal-50 dark:border-teal-500/30 dark:bg-teal-500/15">
              <div className="flex items-start gap-3">
                <div className="size-12 rounded-lg bg-gradient-to-br from-teal-500 to-teal-600 flex items-center justify-center text-white flex-shrink-0">
                  <BoltIcon className="h-6 w-6" />
                </div>
                <div className="flex-1">
                  <h4 className="mb-1 text-sm font-semibold text-gray-800 dark:text-white/90">
                    Automation
                  </h4>
                  <p className="text-sm text-gray-600 dark:text-gray-400">
                    Set up automated workflows to streamline your content creation process. Schedule content generation, automatic publishing, keyword monitoring, and other tasks to save time and maintain consistency.
                  </p>
                </div>
              </div>
            </div>

            {/* Prompts */}
            <div className="rounded-xl p-4 border-b-2 border-cyan-500 bg-cyan-50 dark:border-cyan-500/30 dark:bg-cyan-500/15">
              <div className="flex items-start gap-3">
                <div className="size-12 rounded-lg bg-gradient-to-br from-cyan-500 to-cyan-600 flex items-center justify-center text-white flex-shrink-0">
                  <FileTextIcon className="h-6 w-6" />
                </div>
                <div className="flex-1">
                  <h4 className="mb-1 text-sm font-semibold text-gray-800 dark:text-white/90">
                    Prompts
                  </h4>
                  <p className="text-sm text-gray-600 dark:text-gray-400">
                    Create and manage custom AI prompts to guide content generation. Customize prompts for different content types, industries, and writing styles. Save and reuse your best prompts for consistent, high-quality output.
                  </p>
                </div>
              </div>
            </div>
          </div>
        </ComponentCard>

      </div>
    </>
  );
}
