/**
 * Landing Page Templates and Block Presets
 *
 * Provides pre-built page templates and block presets for quick setup.
 */
import type { Data } from '@measured/puck';

// ============================================================================
// Template Types
// ============================================================================

export interface PageTemplate {
  id: string;
  name: string;
  description: string;
  thumbnail: string;
  generate: () => Data;
}

export interface BlockPreset {
  id: string;
  name: string;
  description?: string;
  props: Record<string, unknown>;
}

// ============================================================================
// ID Generator
// ============================================================================

let idCounter = 0;
function generateId(prefix: string): string {
  return `${prefix}-${Date.now()}-${++idCounter}`;
}

// ============================================================================
// SaaS Landing Page Template Generator
// ============================================================================

export function generateSaaSLandingPageTemplate(): Data {
  idCounter = 0; // Reset counter for consistent IDs

  return {
    root: {
      props: {},
    },
    content: [
      // TopNav
      {
        type: 'TopNav',
        props: {
          id: generateId('topnav'),
          brandText: 'YourBrand',
          brandLogo: '',
          links: [
            { label: 'Features', href: '#features' },
            { label: 'Pricing', href: '#pricing' },
            { label: 'About', href: '#about' },
            { label: 'Contact', href: '#contact' },
          ],
          ctaButton: {
            text: 'Get Started',
            href: '#signup',
          },
          variant: 'transparent-on-dark',
          showMobileMenu: true,
        },
      },

      // HeroSaaS
      {
        type: 'HeroSaaS',
        props: {
          id: generateId('hero'),
          headline: 'Transform Your Business with Our Platform',
          subheadline:
            'Streamline operations, boost productivity, and scale your business with our all-in-one solution trusted by thousands of companies worldwide.',
          primaryCta: {
            text: 'Start Free Trial',
            href: '#signup',
          },
          secondaryCta: {
            text: 'Watch Demo',
            href: '#demo',
          },
          backgroundVariant: 'gradient',
          gradientPreset: 'dark-purple',
          heroImage: {
            src: 'https://placehold.co/1200x800/1a1a2e/ffffff?text=Product+Screenshot',
            alt: 'Product dashboard screenshot',
          },
          badge: 'New: AI-Powered Features',
          padding: 'xl',
          contentMaxWidth: 'wide',
          alignment: 'center',
        },
      },

      // LogoCloud
      {
        type: 'LogoCloud',
        props: {
          id: generateId('logos'),
          heading: 'Trusted by industry leaders',
          logos: [
            {
              src: 'https://placehold.co/160x48/e4e4e7/71717a?text=Logo+1',
              alt: 'Company 1',
            },
            {
              src: 'https://placehold.co/160x48/e4e4e7/71717a?text=Logo+2',
              alt: 'Company 2',
            },
            {
              src: 'https://placehold.co/160x48/e4e4e7/71717a?text=Logo+3',
              alt: 'Company 3',
            },
            {
              src: 'https://placehold.co/160x48/e4e4e7/71717a?text=Logo+4',
              alt: 'Company 4',
            },
            {
              src: 'https://placehold.co/160x48/e4e4e7/71717a?text=Logo+5',
              alt: 'Company 5',
            },
            {
              src: 'https://placehold.co/160x48/e4e4e7/71717a?text=Logo+6',
              alt: 'Company 6',
            },
          ],
          grayscale: true,
          spacingDensity: 'normal',
          padding: 'lg',
          backgroundVariant: 'light',
          contentMaxWidth: 'wide',
        },
      },

      // FeatureSplit
      {
        type: 'FeatureSplit',
        props: {
          id: generateId('feature-split'),
          eyebrow: 'Powerful Analytics',
          heading: 'Understand your data like never before',
          content:
            'Get deep insights into your business performance with our advanced analytics dashboard. Track key metrics, identify trends, and make data-driven decisions.',
          bullets: [
            { text: 'Real-time data visualization', icon: 'chart' },
            { text: 'Custom report builder', icon: 'file' },
            { text: 'Automated insights & alerts', icon: 'bell' },
          ],
          cta: {
            text: 'Learn More',
            href: '#analytics',
          },
          media: {
            src: 'https://placehold.co/600x400/f4f4f5/3f3f46?text=Analytics+Dashboard',
            alt: 'Analytics dashboard',
          },
          mediaPosition: 'right',
          variant: 'light',
          padding: 'xl',
          contentMaxWidth: 'wide',
        },
      },

      // CTASection (center CTA band)
      {
        type: 'CTASection',
        props: {
          id: generateId('cta-1'),
          heading: 'Ready to get started?',
          supportingText:
            'Join thousands of businesses already using our platform to grow.',
          buttons: [
            {
              text: 'Start Free Trial',
              href: '#signup',
              variant: 'primary',
            },
          ],
          variant: 'gradient',
          gradientPreset: 'royal',
          padding: 'lg',
          contentMaxWidth: 'normal',
          alignment: 'center',
        },
      },

      // StatsStrip
      {
        type: 'StatsStrip',
        props: {
          id: generateId('stats'),
          stats: [
            { value: '10K+', label: 'Active Users' },
            { value: '99.9%', label: 'Uptime' },
            { value: '50M+', label: 'Tasks Completed' },
            { value: '4.9/5', label: 'Customer Rating' },
          ],
          variant: 'light',
          padding: 'lg',
          backgroundVariant: 'none',
          contentMaxWidth: 'wide',
        },
      },

      // GalleryGrid
      {
        type: 'GalleryGrid',
        props: {
          id: generateId('gallery'),
          heading: 'Explore Our Features',
          items: [
            {
              image: 'https://placehold.co/400x300/f4f4f5/3f3f46?text=Feature+1',
              title: 'Team Collaboration',
              text: 'Work together seamlessly with your team in real-time.',
            },
            {
              image: 'https://placehold.co/400x300/f4f4f5/3f3f46?text=Feature+2',
              title: 'Automation',
              text: 'Automate repetitive tasks and save hours every week.',
            },
            {
              image: 'https://placehold.co/400x300/f4f4f5/3f3f46?text=Feature+3',
              title: 'Integrations',
              text: 'Connect with 100+ tools you already use.',
            },
            {
              image: 'https://placehold.co/400x300/f4f4f5/3f3f46?text=Feature+4',
              title: 'Mobile App',
              text: 'Stay productive on the go with our mobile app.',
            },
            {
              image: 'https://placehold.co/400x300/f4f4f5/3f3f46?text=Feature+5',
              title: 'Security',
              text: 'Enterprise-grade security for your peace of mind.',
            },
            {
              image: 'https://placehold.co/400x300/f4f4f5/3f3f46?text=Feature+6',
              title: 'Support',
              text: '24/7 customer support whenever you need help.',
            },
          ],
          columnsMobile: 1,
          columnsTablet: 2,
          columnsDesktop: 3,
          padding: 'xl',
          backgroundVariant: 'light',
          contentMaxWidth: 'wide',
        },
      },

      // CTASection (dark full-width)
      {
        type: 'CTASection',
        props: {
          id: generateId('cta-2'),
          heading: 'See the platform in action',
          supportingText:
            'Watch a 2-minute demo to see how we can help your business.',
          buttons: [
            {
              text: 'Watch Demo',
              href: '#demo',
              variant: 'primary',
            },
            {
              text: 'Talk to Sales',
              href: '#sales',
              variant: 'secondary',
            },
          ],
          variant: 'dark',
          padding: 'xl',
          contentMaxWidth: 'normal',
          alignment: 'center',
        },
      },

      // TestimonialCarousel
      {
        type: 'TestimonialCarousel',
        props: {
          id: generateId('testimonials'),
          heading: 'What our customers say',
          items: [
            {
              quote:
                'This platform has transformed how we work. We\'ve increased productivity by 40% since switching.',
              name: 'Sarah Johnson',
              title: 'CEO, TechCorp',
              avatar: 'https://placehold.co/64x64/e4e4e7/3f3f46?text=SJ',
              rating: 5,
            },
            {
              quote:
                'The best investment we\'ve made for our team. The automation features alone save us 20 hours per week.',
              name: 'Michael Chen',
              title: 'Operations Director, StartupXYZ',
              avatar: 'https://placehold.co/64x64/e4e4e7/3f3f46?text=MC',
              rating: 5,
            },
            {
              quote:
                'Outstanding customer support and a product that just works. Highly recommend to any growing business.',
              name: 'Emily Rodriguez',
              title: 'Founder, GrowthLabs',
              avatar: 'https://placehold.co/64x64/e4e4e7/3f3f46?text=ER',
              rating: 5,
            },
          ],
          layout: 'carousel',
          showRating: true,
          padding: 'xl',
          backgroundVariant: 'none',
          contentMaxWidth: 'wide',
        },
      },

      // VideoFeature
      {
        type: 'VideoFeature',
        props: {
          id: generateId('video'),
          heading: 'See how it works',
          text: 'Watch a quick overview of our platform and discover how it can help your business grow.',
          thumbnailImage:
            'https://placehold.co/800x450/1a1a2e/ffffff?text=Video+Thumbnail',
          provider: 'youtube',
          videoId: 'dQw4w9WgXcQ',
          variant: 'light',
          padding: 'xl',
          backgroundVariant: 'light',
          contentMaxWidth: 'normal',
          alignment: 'center',
        },
      },

      // AlternatingFeatures
      {
        type: 'AlternatingFeatures',
        props: {
          id: generateId('alternating'),
          sectionHeading: 'Everything you need to succeed',
          features: [
            {
              heading: 'Streamlined Workflows',
              text: 'Build custom workflows that automate your most repetitive tasks. Save time and reduce errors.',
              bullets: [
                'Drag-and-drop workflow builder',
                'Pre-built templates',
                'Conditional logic support',
              ],
              image: 'https://placehold.co/500x350/f4f4f5/3f3f46?text=Workflows',
            },
            {
              heading: 'Powerful Integrations',
              text: 'Connect with the tools you already use. Our platform integrates with 100+ popular applications.',
              bullets: [
                'One-click connections',
                'Real-time sync',
                'Custom API access',
              ],
              image: 'https://placehold.co/500x350/f4f4f5/3f3f46?text=Integrations',
            },
            {
              heading: 'Advanced Reporting',
              text: 'Get insights that matter with our comprehensive reporting and analytics tools.',
              bullets: [
                'Custom dashboards',
                'Scheduled reports',
                'Export to any format',
              ],
              image: 'https://placehold.co/500x350/f4f4f5/3f3f46?text=Reporting',
            },
          ],
          padding: 'xl',
          backgroundVariant: 'none',
          contentMaxWidth: 'wide',
        },
      },

      // PricingPlans
      {
        type: 'PricingPlans',
        props: {
          id: generateId('pricing'),
          sectionHeading: 'Simple, transparent pricing',
          sectionSubheading: 'No hidden fees. Cancel anytime.',
          currency: '$',
          billingPeriod: '/month',
          plans: [
            {
              name: 'Starter',
              price: '29',
              subtitle: 'Perfect for small teams',
              features: [
                'Up to 5 team members',
                '10 GB storage',
                'Basic analytics',
                'Email support',
              ],
              cta: {
                text: 'Start Free Trial',
                href: '#signup',
              },
            },
            {
              name: 'Professional',
              price: '79',
              subtitle: 'For growing businesses',
              features: [
                'Up to 25 team members',
                '100 GB storage',
                'Advanced analytics',
                'Priority support',
                'Custom integrations',
                'API access',
              ],
              cta: {
                text: 'Start Free Trial',
                href: '#signup',
              },
            },
            {
              name: 'Enterprise',
              price: '199',
              subtitle: 'For large organizations',
              features: [
                'Unlimited team members',
                'Unlimited storage',
                'Custom analytics',
                '24/7 dedicated support',
                'Custom integrations',
                'API access',
                'SSO & SAML',
                'SLA guarantee',
              ],
              cta: {
                text: 'Contact Sales',
                href: '#sales',
              },
            },
          ],
          highlightIndex: 1,
          popularBadgeText: 'Most Popular',
          variant: 'light',
          padding: 'xl',
          backgroundVariant: 'light',
          contentMaxWidth: 'wide',
          alignment: 'center',
        },
      },

      // FAQAccordion
      {
        type: 'FAQAccordion',
        props: {
          id: generateId('faq'),
          heading: 'Frequently Asked Questions',
          items: [
            {
              question: 'How does the free trial work?',
              answer:
                'Start with a 14-day free trial of our Professional plan. No credit card required. You can downgrade or cancel anytime during the trial.',
            },
            {
              question: 'Can I change plans later?',
              answer:
                'Yes! You can upgrade or downgrade your plan at any time. Changes take effect immediately, and we\'ll prorate any billing differences.',
            },
            {
              question: 'What payment methods do you accept?',
              answer:
                'We accept all major credit cards (Visa, MasterCard, American Express) and can also invoice enterprise customers.',
            },
            {
              question: 'Is my data secure?',
              answer:
                'Absolutely. We use enterprise-grade encryption, are SOC 2 Type II certified, and comply with GDPR. Your data is backed up daily.',
            },
            {
              question: 'Do you offer refunds?',
              answer:
                'Yes, we offer a 30-day money-back guarantee. If you\'re not satisfied, contact support for a full refund.',
            },
            {
              question: 'How do I get support?',
              answer:
                'All plans include email support. Professional plans get priority support, and Enterprise customers have a dedicated success manager.',
            },
          ],
          expandBehavior: 'single',
          variant: 'light',
          padding: 'xl',
          backgroundVariant: 'none',
          contentMaxWidth: 'normal',
        },
      },

      // FooterMega
      {
        type: 'FooterMega',
        props: {
          id: generateId('footer'),
          brandText: 'YourBrand',
          brandLogo: '',
          description:
            'The all-in-one platform for modern businesses. Streamline your operations and grow faster.',
          columns: [
            {
              title: 'Product',
              links: [
                { label: 'Features', href: '#features' },
                { label: 'Pricing', href: '#pricing' },
                { label: 'Integrations', href: '#integrations' },
                { label: 'Changelog', href: '#changelog' },
              ],
            },
            {
              title: 'Company',
              links: [
                { label: 'About', href: '#about' },
                { label: 'Blog', href: '#blog' },
                { label: 'Careers', href: '#careers' },
                { label: 'Contact', href: '#contact' },
              ],
            },
            {
              title: 'Resources',
              links: [
                { label: 'Documentation', href: '#docs' },
                { label: 'Help Center', href: '#help' },
                { label: 'API Reference', href: '#api' },
                { label: 'Status', href: '#status' },
              ],
            },
            {
              title: 'Legal',
              links: [
                { label: 'Privacy Policy', href: '#privacy' },
                { label: 'Terms of Service', href: '#terms' },
                { label: 'Cookie Policy', href: '#cookies' },
              ],
            },
          ],
          socialLinks: {
            twitter: 'https://twitter.com',
            linkedin: 'https://linkedin.com',
            github: 'https://github.com',
          },
          smallPrint: '2024 YourBrand. All rights reserved.',
          miniCta: {
            text: 'Subscribe to our newsletter',
            placeholder: 'Enter your email',
            buttonText: 'Subscribe',
          },
        },
      },
    ],
  };
}

// ============================================================================
// Landing Page Templates Registry
// ============================================================================

export const LANDING_PAGE_TEMPLATES: PageTemplate[] = [
  {
    id: 'saas-dark-hero',
    name: 'SaaS Landing Page (Dark Hero)',
    description:
      'Modern SaaS landing page with dark gradient hero, product screenshot, logo cloud, feature sections, pricing, and more.',
    thumbnail: 'https://placehold.co/400x300/1a1a2e/ffffff?text=SaaS+Dark+Hero',
    generate: generateSaaSLandingPageTemplate,
  },
];

// ============================================================================
// Block Presets
// ============================================================================

export const BLOCK_PRESETS: Record<string, BlockPreset[]> = {
  HeroSaaS: [
    {
      id: 'dark-gradient-centered',
      name: 'Dark Gradient (Centered)',
      description: 'Dark gradient background with centered text',
      props: {
        backgroundVariant: 'gradient',
        gradientPreset: 'dark-purple',
        alignment: 'center',
        padding: 'xl',
      },
    },
    {
      id: 'light-left-aligned',
      name: 'Light (Left Aligned)',
      description: 'Light background with left-aligned text',
      props: {
        backgroundVariant: 'light',
        alignment: 'left',
        padding: 'xl',
      },
    },
  ],
  PricingPlans: [
    {
      id: 'three-card-highlighted',
      name: '3 Cards (Middle Highlighted)',
      description: 'Three pricing cards with middle plan highlighted',
      props: {
        highlightIndex: 1,
        variant: 'light',
      },
    },
    {
      id: 'two-card',
      name: '2 Cards',
      description: 'Two pricing cards side by side',
      props: {
        highlightIndex: 0,
        variant: 'light',
      },
    },
  ],
  CTASection: [
    {
      id: 'dark-gradient',
      name: 'Dark Gradient',
      props: {
        variant: 'gradient',
        gradientPreset: 'dark-purple',
        alignment: 'center',
      },
    },
    {
      id: 'light-centered',
      name: 'Light Centered',
      props: {
        variant: 'light',
        alignment: 'center',
      },
    },
  ],
  FeatureSplit: [
    {
      id: 'image-right',
      name: 'Image Right',
      props: {
        mediaPosition: 'right',
        variant: 'light',
      },
    },
    {
      id: 'image-left',
      name: 'Image Left',
      props: {
        mediaPosition: 'left',
        variant: 'light',
      },
    },
  ],
};

// ============================================================================
// Puck Data Validation
// ============================================================================

export interface ValidationResult {
  isValid: boolean;
  error?: string;
}

export function validatePuckData(data: unknown): ValidationResult {
  if (!data || typeof data !== 'object') {
    return { isValid: false, error: 'Data must be an object' };
  }

  const puckData = data as Record<string, unknown>;

  if (!('content' in puckData)) {
    return { isValid: false, error: 'Data must have a content array' };
  }

  if (!Array.isArray(puckData.content)) {
    return { isValid: false, error: 'content must be an array' };
  }

  for (let i = 0; i < puckData.content.length; i++) {
    const component = puckData.content[i] as Record<string, unknown>;
    if (!component || typeof component !== 'object') {
      return { isValid: false, error: `content[${i}] must be an object` };
    }
    if (!('type' in component) || typeof component.type !== 'string') {
      return { isValid: false, error: `content[${i}] must have a type string` };
    }
  }

  return { isValid: true };
}
