import React, { useEffect, useState, useRef } from 'react';
import { useAuth } from 'react-oidc-context';
import SEO from '../../components/SEO/SEO';
import SharedHeader from '../../components/SharedHeader/SharedHeader';
import SharedFooter from '../../components/SharedFooter/SharedFooter';
import CTASection from '../../components/CTASection/CTASection';
import Typewriter from '../../components/Typewriter/Typewriter';
import RandomLetterSwap from '../../components/RandomLetterSwap';
import ParseChart from '../../components/ParseChart/ParseChart';
import LayoutChart from '../../components/LayoutChart/LayoutChart';
import OrderChart from '../../components/OrderChart/OrderChart';
import Lottie from 'lottie-react';
import { isHealth } from '../../services/health';
import './Home.css';

// Dynamic Lottie Animation Loader Component
interface LazyLottieProps {
  animationPath: string;
  className?: string;
  loop?: boolean;
  autoplay?: boolean;
}

const LazyLottie: React.FC<LazyLottieProps> = ({ animationPath, className, loop = false, autoplay = true }) => {
  const [animationData, setAnimationData] = useState<object | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadAnimation = async () => {
      try {
        const module = await import(`../../assets/animations/${animationPath}.json`);
        setAnimationData(module.default);
      } catch (error) {
        console.error(`Failed to load animation: ${animationPath}`, error);
      } finally {
        setLoading(false);
      }
    };

    loadAnimation();
  }, [animationPath]);

  if (loading) {
    return (
      <div className={`${className} animation-placeholder`} style={{
        width: '24px',
        height: '24px',
        background: 'rgba(255, 255, 255, 0.1)',
        borderRadius: '4px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
      }}>
        <div style={{
          width: '12px',
          height: '12px',
          border: '1px solid rgba(255, 255, 255, 0.3)',
          borderTop: '1px solid rgba(255, 255, 255, 0.8)',
          borderRadius: '50%',
          animation: 'spin 1s linear infinite'
        }} />
      </div>
    );
  }

  return animationData ? (
    <Lottie
      animationData={animationData}
      loop={loop}
      autoplay={autoplay}
      className={className}
    />
  ) : null;
};

// Import feature card images
import featureParseCard1 from '../../assets/landing-images/parse-card-1.webp';
import featureParseCard2 from '../../assets/landing-images/parse-card-2.webp';
import featureParseCard3 from '../../assets/landing-images/parse-card-3.webp';
import featureParseCard4 from '../../assets/landing-images/parse-card-4.webp';
import featureExtractCard1 from '../../assets/landing-images/extract-card-1.webp';
import featureExtractCard2 from '../../assets/landing-images/extract-card-2.webp';
import featureExtractCard3 from '../../assets/landing-images/extract-card-3.webp';
import featureExtractCard4 from '../../assets/landing-images/extract-card-4.webp';

// Sticky header height plus the announcement bar, if shown
const getHeaderOffset = () =>
  112 + (parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--announcement-height')) || 0);

// Feature Link Component with Typewriter hover effect
interface FeatureLinkProps {
  href: string;
  label: string;
  colorClass: string;
  hoverTexts: string[];
  disableHover?: boolean;
}

// Feature Card Component for value proposition section
interface FeatureCardProps {
  title: string;
  description?: string; // legacy prop, prefer summary/detail
  summary?: string; // single-sentence default state
  detail?: string; // robust description shown on hover
  colorClass?: string;
  bgImage?: string; // optional background image (used later)
  animated?: boolean; // enable/disable RandomLetterSwap animations
  headline?: string; // optional large headline for alternate layout
  subtitle?: React.ReactNode; // optional smaller subtitle line below headline
  hoverLink?: string; // optional link text shown on hover
  hoverLinkUrl?: string; // optional URL for the hover link
  showDetailByDefault?: boolean; // show detail instead of summary by default (for mobile)
  forceHover?: boolean; // force hover state (for scroll-triggered hover)
}

const FeatureCard: React.FC<FeatureCardProps> = ({ title, description, summary, detail, colorClass = '', bgImage, animated = true, headline, subtitle, hoverLink, hoverLinkUrl, showDetailByDefault = false, forceHover = false }) => {
  const [isHovered, setIsHovered] = useState(false);
  const effectiveHover = forceHover || isHovered; // Use forced hover if provided, otherwise manual hover

  const styleProps = bgImage
    ? ({ ['--card-bg-image' as keyof React.CSSProperties]: `url(${bgImage})` } as React.CSSProperties)
    : undefined;

  return (
    <div
      className={`feature-card ${colorClass} ${bgImage ? 'has-image' : ''} ${!animated ? 'no-hover-change' : ''} ${forceHover ? 'forced-hover' : ''}`}
      style={styleProps}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      {headline ? (
        <h3 className="feature-card-headline">{headline}</h3>
      ) : (
        <div className="feature-card-content-container">
          <h3 className="feature-card-title">
            {animated ? (
              <RandomLetterSwap
                key={effectiveHover ? `title-hide-${title}` : `title-show-${title}`}
                label={title}
                reverse={effectiveHover}
              />
            ) : (
              title
            )}
          </h3>
          {/* Always render description content for hover effect */}
          {detail && (
            <div className="feature-card-detail">
              {animated && !showDetailByDefault ? (
                <RandomLetterSwap
                  key={effectiveHover ? `detail-show-${detail}` : `detail-hide-${detail}`}
                  label={detail}
                  reverse={!effectiveHover}
                />
              ) : (
                detail
              )}
            </div>
          )}
          {summary && !detail && (
            <div className="feature-card-summary">
              {animated && !showDetailByDefault ? (
                <RandomLetterSwap
                  key={effectiveHover ? `summary-show-${summary}` : `summary-hide-${summary}`}
                  label={summary}
                  reverse={!effectiveHover}
                />
              ) : (
                summary
              )}
            </div>
          )}
          {description && !detail && !summary && (
            <div className="feature-card-description">
              {animated && !showDetailByDefault ? (
                <RandomLetterSwap
                  key={effectiveHover ? `desc-show-${description}` : `desc-hide-${description}`}
                  label={description}
                  reverse={!effectiveHover}
                />
              ) : (
                description
              )}
            </div>
          )}
        </div>
      )}
      <div className="feature-card-content">
        {headline && subtitle && <div className="feature-card-subtitle">{subtitle}</div>}
      </div>
      {hoverLink && (
        <div className="feature-card-hover-link">
          <a
            href={hoverLinkUrl || '#'}
            target="_blank"
            rel="noopener noreferrer"
            onClick={(e) => {
              if (!hoverLinkUrl) e.preventDefault();
            }}
          >
            <span>{hoverLink}</span>
            <svg
              width="12"
              height="12"
              viewBox="0 0 12 12"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
              className="hover-link-icon"
            >
              <path
                d="M3.5 1.5H10.5V8.5M10.5 1.5L1.5 10.5L10.5 1.5Z"
                stroke="currentColor"
                strokeWidth="1.5"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
          </a>
        </div>
      )}
    </div>
  );
};

const FeatureLink: React.FC<FeatureLinkProps> = ({ href, label, colorClass, hoverTexts, disableHover = false }) => {
  const [isHovered, setIsHovered] = useState(false);

  const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
    // If it's a hash link, handle instant jump
    if (href.startsWith('#')) {
      e.preventDefault();
      const targetId = href.substring(1);
      const targetElement = document.getElementById(targetId);

      if (targetElement) {
        const headerOffset = getHeaderOffset();
        const elementPosition = targetElement.getBoundingClientRect().top;
        const offsetPosition = elementPosition + window.pageYOffset - headerOffset;

        // Use instant scrolling instead of smooth to avoid going through sticky sections
        window.scrollTo({
          top: offsetPosition,
          behavior: 'auto'
        });

        // Update URL hash without jumping
        window.history.pushState(null, '', href);
      }
    }
  };

  return (
    <a
      href={href}
      className={`feature-link ${colorClass}`}
      onMouseEnter={() => !disableHover && setIsHovered(true)}
      onMouseLeave={() => !disableHover && setIsHovered(false)}
      onClick={handleClick}
    >
      {isHovered && !disableHover ? (
        <Typewriter
          texts={hoverTexts}
          speed={60}
          deleteSpeed={40}
          pauseTime={1000}
          cursorChar="_"
          className="typewriter-text"
        />
      ) : (
        label
      )}
    </a>
  );
};

const Home: React.FC = () => {
  const auth = useAuth();
  const isAuthenticated = auth.isAuthenticated;
  // State for value proposition section scroll behavior
  const [valueSection, setValueSection] = useState(1); // 1-4 for Parse (1-2) and Extract (3-4)
  const [scrollProgress, setScrollProgress] = useState(0); // 0 to 1 for overall scroll progress
  const [hoveredCards, setHoveredCards] = useState<Set<number>>(new Set()); // Track which cards are hovered by scroll
  const valuePropRef = useRef<HTMLElement>(null);
  const numSections = 4; // Number of feature sections (2 for Parse, 2 for Extract)

  // State for models section scroll behavior
  const [modelSection, setModelSection] = useState(1); // 1-3 for parse-1, layout-1, and order-1
  const [modelScrollProgress, setModelScrollProgress] = useState(0); // 0 to 1 for overall scroll progress
  const modelsRef = useRef<HTMLElement>(null);
  const numModelSections = 3; // Number of model sections

  // State for responsive behavior
  const [isMobile, setIsMobile] = useState(false);
  const [isShortHeight, setIsShortHeight] = useState(false);

  // State for health check
  const [isHealthy, setIsHealthy] = useState<boolean>(true);
  const [healthCheckLoading, setHealthCheckLoading] = useState<boolean>(true);

  // State for active section tracking
  const [activeSection, setActiveSection] = useState<string>('');

  // Check health status on component mount
  useEffect(() => {
    const checkHealthStatus = async () => {
      try {
        setHealthCheckLoading(true);
        const healthy = await isHealth();
        setIsHealthy(healthy);
      } catch (error) {
        console.error('Health check failed:', error);
        setIsHealthy(false);
      } finally {
        setHealthCheckLoading(false);
      }
    };

    checkHealthStatus();
  }, []);

  const handleAuthRedirect = (returnPath?: string) => {
    const currentPath = window.location.pathname + window.location.hash;
    auth.signinRedirect({ state: { returnTo: returnPath || currentPath } });
  };

  const handleGetStarted = () => {
    if (isAuthenticated) {
      window.location.href = '/dashboard';
    } else {
      handleAuthRedirect('/dashboard');
    }
  };

  // Track window size for responsive behavior
  useEffect(() => {
    const checkMobile = () => {
      setIsMobile(window.innerWidth <= 768);
      setIsShortHeight(window.innerHeight <= 896 && window.innerWidth > 768);
    };

    checkMobile(); // Initial check
    window.addEventListener('resize', checkMobile);

    return () => window.removeEventListener('resize', checkMobile);
  }, []);

  // Handle initial page load with hash
  useEffect(() => {
    const hash = window.location.hash;
    if (hash) {
      const targetId = hash.substring(1);
      const targetElement = document.getElementById(targetId);

      if (targetElement) {
        setTimeout(() => {
          const headerOffset = getHeaderOffset();
          const elementPosition = targetElement.getBoundingClientRect().top;
          const offsetPosition = elementPosition + window.pageYOffset - headerOffset;

          window.scrollTo({
            top: offsetPosition,
            behavior: 'auto'
          });
        }, 100); // Small delay to ensure page is loaded
      }
    }
  }, []);

  // Setup intersection observer for section tracking
  useEffect(() => {
    const sections = ['features', 'models', 'security', 'faq'];
    const observerOptions = {
      root: null,
      rootMargin: '-30% 0px -60% 0px',
      threshold: 0
    };

    const observerCallback = (entries: IntersectionObserverEntry[]) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const sectionId = entry.target.id;
          setActiveSection(sectionId);
          // Update URL hash without causing jump
          window.history.replaceState(null, '', `#${sectionId}`);
        }
      });
    };

    const observer = new IntersectionObserver(observerCallback, observerOptions);

    sections.forEach((sectionId) => {
      const section = document.getElementById(sectionId);
      if (section) {
        observer.observe(section);
      }
    });

    // Add scroll listener to detect when at top
    const handleScroll = () => {
      // If we're at the top of the page, clear the hash
      if (window.scrollY < 100) {
        setActiveSection('');
        // Clear the hash from URL
        window.history.replaceState(null, '', window.location.pathname);
      }
    };

    window.addEventListener('scroll', handleScroll);

    return () => {
      sections.forEach((sectionId) => {
        const section = document.getElementById(sectionId);
        if (section) {
          observer.unobserve(section);
        }
      });
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);



  useEffect(() => {
    // Scroll-based content switching with progress tracking
    const handleScroll = () => {
      if (!valuePropRef.current) return;

      const scrollContainer = valuePropRef.current.querySelector('.value-prop-scroll-container') as HTMLElement;
      if (!scrollContainer) return;

      const rect = scrollContainer.getBoundingClientRect();
      const containerHeight = scrollContainer.offsetHeight;
      const viewportHeight = window.innerHeight;

      // Calculate scroll progress through the container
      const scrolled = -rect.top;
      const scrollableHeight = containerHeight - viewportHeight;
      const progress = Math.max(0, Math.min(1, scrolled / scrollableHeight));

      // Update overall scroll progress
      setScrollProgress(progress);

      // Switch content based on progress (Parse: sections 1-2, Extract: sections 3-4)
      const sectionThreshold = 1 / numSections;
      const currentSection = Math.min(Math.floor(progress / sectionThreshold) + 1, numSections);
      setValueSection(currentSection);

      // Calculate which card should be hovered based on scroll progress
      // For short height: activate cards sequentially but show them in pairs
      // For normal height: activate individual cards
      const newHoveredCards = new Set<number>();

      // Only activate cards after some scroll progress (avoid initial state activation)
      if (progress > 0.02) {
        // Check if we're in short height mode (laptop width but short height)
        const isCurrentlyShortHeight = window.innerHeight <= 896 && window.innerWidth > 768;

        if (progress < 0.5) {
          // In Parse section (0-0.5 progress)
          const parseProgress = progress * 2; // Normalize to 0-1 for Parse section

          if (isCurrentlyShortHeight) {
            // Short height: still activate cards sequentially for animation
            // But show them in pairs based on which pair is visible
            if (parseProgress < 0.25) {
              newHoveredCards.add(0);
            } else if (parseProgress < 0.5) {
              newHoveredCards.add(0);
              newHoveredCards.add(1);
            } else if (parseProgress < 0.75) {
              newHoveredCards.add(2);
            } else {
              newHoveredCards.add(2);
              newHoveredCards.add(3);
            }
          } else {
            // Normal height: activate individual cards
            if (parseProgress < 0.25) {
              newHoveredCards.add(0);
            } else if (parseProgress < 0.5) {
              newHoveredCards.add(1);
            } else if (parseProgress < 0.75) {
              newHoveredCards.add(2);
            } else {
              newHoveredCards.add(3);
            }
          }
        } else {
          // In Extract section (0.5-1.0 progress)
          const extractProgress = (progress - 0.5) * 2; // Normalize to 0-1 for Extract section

          if (isCurrentlyShortHeight) {
            // Short height: still activate cards sequentially for animation
            // But show them in pairs based on which pair is visible
            if (extractProgress < 0.25) {
              newHoveredCards.add(4);
            } else if (extractProgress < 0.5) {
              newHoveredCards.add(4);
              newHoveredCards.add(5);
            } else if (extractProgress < 0.75) {
              newHoveredCards.add(6);
            } else {
              newHoveredCards.add(6);
              newHoveredCards.add(7);
            }
          } else {
            // Normal height: activate individual cards
            if (extractProgress < 0.25) {
              newHoveredCards.add(4);
            } else if (extractProgress < 0.5) {
              newHoveredCards.add(5);
            } else if (extractProgress < 0.75) {
              newHoveredCards.add(6);
            } else {
              newHoveredCards.add(7);
            }
          }
        }
      }

      setHoveredCards(newHoveredCards);
    };

    window.addEventListener('scroll', handleScroll);
    handleScroll(); // Initial check

    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  useEffect(() => {
    // Scroll-based content switching for models section
    const handleScroll = () => {
      if (!modelsRef.current) return;

      const scrollContainer = modelsRef.current.querySelector('.models-scroll-container') as HTMLElement;
      if (!scrollContainer) return;

      const rect = scrollContainer.getBoundingClientRect();
      const containerHeight = scrollContainer.offsetHeight;
      const viewportHeight = window.innerHeight;

      // Calculate scroll progress through the container
      const scrolled = -rect.top;
      const scrollableHeight = containerHeight - viewportHeight;
      const progress = Math.max(0, Math.min(1, scrolled / scrollableHeight));

      // Update overall scroll progress
      setModelScrollProgress(progress);

      // Switch content based on progress
      const sectionThreshold = 1 / numModelSections;
      const currentSection = Math.min(Math.floor(progress / sectionThreshold) + 1, numModelSections);
      setModelSection(currentSection);
    };

    window.addEventListener('scroll', handleScroll);
    handleScroll(); // Initial check

    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);


  // FAQ data and state
  const faqItems: { question: string; answer: React.ReactNode }[] = [
    {
      question: "How is data handled?",
      answer: (
        <>
          We are{' '}
          <a
            href="https://trust.chunkr.ai"
            target="_blank"
            rel="noopener noreferrer"
            style={{ color: 'inherit', textDecoration: 'underline' }}
          >
            <span className="faq-highlight">SOC2 and HIPAA compliant</span>
          </a>
          {' '}with <span className="faq-highlight">customizable zero data retention</span> by default. Your documents are processed securely and deleted immediately based on the expiration time you set. Enterprise customers get additional controls and audit trails.
        </>
      ),
    },
    {
      question: "What document/file types are supported?",
      answer: (
        <>
          <span className="faq-highlight">PDFs, images (PNG/JPEG/TIFF), Word docs, spreadsheets (CSV/XLSX), PowerPoint, scanned documents</span>, and more. We support <span className="faq-highlight">~100 languages</span> with multilingual document processing. Format support grows continuously based on customer needs.
        </>
      ),
    },
    {
      question: "Can you handle complex things like handwriting, forms, formulas?",
      answer: (
        <>
          Yes. Our advanced vision models excel at <span className="faq-highlight">handwritten text, complex forms, mathematical formulas, tables, charts</span>, and technical diagrams. We maintain structure and reading order even in challenging layouts.
        </>
      ),
    },
    {
      question: "On-prem availability?",
      answer: (
        <>
          Yes, <span className="faq-highlight">on-premises deployment</span> is available for Enterprise customers who need to keep data within their infrastructure.{' '}
          <a
            href="https://cal.com/team/chunkr-ai/chunkr-contact"
            target="_blank"
            rel="noopener noreferrer"
            style={{ color: 'inherit', textDecoration: 'underline' }}
          >
            Contact our sales team
          </a>
          {' '}to discuss deployment options and requirements.
        </>
      ),
    },
    {
      question: "Is there a free trial?",
      answer: (
        <>
          Yes! We provide <span className="faq-highlight">200 pages for free</span> to get started - no credit card required. Perfect for testing our API and exploring document processing capabilities before upgrading to a paid plan.{' '}
          <a
            href="/dashboard"
            style={{ color: 'inherit', textDecoration: 'underline' }}
            onClick={(e) => {
              e.preventDefault();
              handleGetStarted();
            }}
          >
            Get started now
          </a>
          .
        </>
      ),
    },
    {
      question: "Where can I get help?",
      answer: (
        <>
          Check our{' '}
          <a
            href="https://docs.chunkr.ai"
            target="_blank"
            rel="noopener noreferrer"
            style={{ color: 'inherit', textDecoration: 'underline' }}
          >
            <span className="faq-highlight">documentation</span>
          </a>
          , join our{' '}
          <a
            href="https://discord.gg/XzKWFByKzW"
            target="_blank"
            rel="noopener noreferrer"
            style={{ color: 'inherit', textDecoration: 'underline' }}
          >
            <span className="faq-highlight">Discord community</span>
          </a>
          , or{' '}
          <a
            href="mailto:support@chunkr.ai"
            style={{ color: 'inherit', textDecoration: 'underline' }}
          >
            email support
          </a>
          . Growth, Scale and enterprise customers get <span className="faq-highlight">priority support</span> with dedicated channels and faster response times.
        </>
      ),
    },
  ];

  const [openFaqIndex, setOpenFaqIndex] = useState<number | null>(null);
  const toggleFaq = (index: number) => {
    setOpenFaqIndex((prev) => (prev === index ? null : index));
  };

  // Comprehensive JSON-LD schemas for Home page
  const homeSchemas = [
    {
      "@context": "https://schema.org",
      "@type": "Organization",
      "name": "Chunkr",
      "url": "https://www.chunkr.ai",
      "logo": "https://www.chunkr.ai/favicon.svg",
      "sameAs": [
        "https://github.com/lumina-ai-inc/chunkr",
        "https://discord.gg/XzKWFByKzW",
        "https://x.com/chunkrai"
      ],
      "contactPoint": {
        "@type": "ContactPoint",
        "contactType": "sales",
        "availableLanguage": ["English"],
        "url": "https://cal.com/team/chunkr-ai/chunkr-contact"
      }
    },
    {
      "@context": "https://schema.org",
      "@type": "WebSite",
      "name": "Chunkr",
      "url": "https://www.chunkr.ai",
      "description": "Document Intelligence API for parsing and data extraction from PDFs, images, and spreadsheets"
    },
    {
      "@context": "https://schema.org",
      "@type": "SoftwareApplication",
      "name": "Chunkr Document Intelligence API",
      "applicationCategory": "DeveloperApplication",
      "operatingSystem": "Web",
      "url": "https://www.chunkr.ai",
      "description": "Parse PDFs, images, and spreadsheets into LLM-ready HTML/Markdown or JSON with OCR, layout detection, and schema-based extraction",
      "offers": {
        "@type": "Offer",
        "price": "0",
        "priceCurrency": "USD",
        "description": "200 pages free to get started"
      },
      "featureList": [
        "PDF Parsing",
        "Image OCR",
        "Spreadsheet Processing",
        "Layout Detection",
        "Table Extraction",
        "Schema-based Data Extraction",
        "Markdown Output",
        "HTML Output",
        "JSON Output"
      ]
    },
    {
      "@context": "https://schema.org",
      "@type": "Product",
      "name": "Chunkr Document Intelligence API",
      "description": "Parse PDFs, images, and spreadsheets into LLM-ready data with advanced OCR and layout analysis",
      "brand": {
        "@type": "Brand",
        "name": "Chunkr"
      },
      "offers": {
        "@type": "AggregateOffer",
        "priceCurrency": "USD",
        "lowPrice": "0",
        "offerCount": "3"
      }
    },
    {
      "@context": "https://schema.org",
      "@type": "BreadcrumbList",
      "itemListElement": [
        {
          "@type": "ListItem",
          "position": 1,
          "name": "Home",
          "item": "https://www.chunkr.ai/"
        },
        {
          "@type": "ListItem",
          "position": 2,
          "name": "Pricing",
          "item": "https://www.chunkr.ai/pricing"
        },
        {
          "@type": "ListItem",
          "position": 3,
          "name": "Blog",
          "item": "https://www.chunkr.ai/blog"
        }
      ]
    },
    {
      "@context": "https://schema.org",
      "@type": "FAQPage",
      "mainEntity": [
        {
          "@type": "Question",
          "name": "How is data handled?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "We are SOC2 and HIPAA compliant with customizable zero data retention by default. Documents are processed securely and deleted based on the expiration time you set. Enterprise customers get additional controls and audit trails."
          }
        },
        {
          "@type": "Question",
          "name": "What document/file types are supported?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "PDFs, images (PNG/JPEG/TIFF), Word docs, spreadsheets (CSV/XLSX), PowerPoint, scanned documents, and more. We support ~100 languages with multilingual document processing."
          }
        },
        {
          "@type": "Question",
          "name": "Can you handle complex things like handwriting, forms, formulas?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Yes. Our vision models handle handwritten text, complex forms, mathematical formulas, tables, charts, technical diagrams, and maintain structure and reading order."
          }
        },
        {
          "@type": "Question",
          "name": "What can I do with Chunkr?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Document parsing, data extraction, RAG preparation, automated workflows, and content analysis. Use the Parse API for Markdown/HTML or Extract API for structured JSON with schemas."
          }
        },
        {
          "@type": "Question",
          "name": "On-prem availability?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Yes, on-premises deployment is available for Enterprise customers."
          }
        },
        {
          "@type": "Question",
          "name": "Is there a free trial?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Yes. 200 pages included for free—no credit card required."
          }
        }
      ]
    }
  ];

  return (
    <>
      <SEO
        title="Chunkr | Document Intelligence API for Parsing, Data Extraction, and Document Pipelines | Complex documents to high-quality data"
        description="Parse PDFs, images, and spreadsheets into LLM-ready HTML/Markdown or JSON. OCR, layout detection, reading order, bounding boxes, citations, and schema-based extraction."
        keywords="document ai, document parsing api, data extraction api, ocr api, pdf parsing, image parsing, spreadsheet parsing, excel api, ppt parsing, powerpoint parsing, word document parsing, table extraction, form extraction, invoice processing, receipt ocr, layout detection, reading order, bounding boxes, citations, rag, llm-ready data, schema extraction, json schema, markdown output, html output, document intelligence, vision language model, vlm, native excel support, csv parsing, xlsx api, document ocr, intelligent document processing, idp"
        canonical="https://www.chunkr.ai/"
        ogType="website"
        ogImage="https://www.chunkr.ai/og-image.webp"
        ogUrl="https://www.chunkr.ai/"
        ogImageAlt="Chunkr | Document Intelligence API for Parsing, Data Extraction, and Document Pipelines | Complex documents to high-quality data"
        jsonLd={homeSchemas}
      >
        {/* Additional specific meta tags for Home */}
        <meta name="apple-mobile-web-app-title" content="Chunkr" />
        <meta name="application-name" content="Chunkr" />

        {/* Preconnect to external domains for performance */}
        <link rel="preconnect" href="https://fonts.googleapis.com" />
        <link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
        <link rel="dns-prefetch" href="https://www.google-analytics.com" />

        {/* Alternate language versions */}
        <link rel="alternate" hrefLang="en" href="https://www.chunkr.ai/" />
        <link rel="alternate" hrefLang="x-default" href="https://www.chunkr.ai/" />
      </SEO>

      {/* Skip to main content for accessibility (also good for SEO) */}
      <a href="#main-content" className="skip-to-main">Skip to main content</a>

      {/* Header with Navigation */}
      <SharedHeader showExtendBanner />

      {/* Main Content */}
      <main id="main-content" role="main" aria-label="Main content" className="container">

        {/* Hero Section with H1 */}
        <section aria-labelledby="hero-heading" className="hero-section">
          <div className="hero-content">
            <h1 id="hero-heading" className="hero-heading heading-1">
              <span className="hero-title-line">
                Complex, messy
              </span>
              <span className="hero-title-line with-arrow">
                documents
                <svg className="arrow-down-svg" xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36" fill="none">
                  <path d="M6 4.5C6 3.73075 6.57906 3.09674 7.32507 3.0101L7.5 3H17.25C20.0528 3 22.3427 5.19642 22.4922 7.96195L22.5 8.25L22.5 27.8775L27.4393 22.9393C27.9801 22.3986 28.8309 22.357 29.4193 22.8146L29.5607 22.9393C30.1014 23.4801 30.143 24.3309 29.6854 24.9194L29.5607 25.0607L22.0607 32.5607C22.0076 32.6138 21.9515 32.662 21.893 32.7055L21.7261 32.813L21.557 32.8932L21.399 32.9462L21.2227 32.9835L21.1347 32.994L21 33L20.8871 32.9958L20.6989 32.9696L20.5318 32.9254L20.3652 32.8595L20.2189 32.781L20.0806 32.6854L19.9393 32.5607L12.4393 25.0607C11.8536 24.4749 11.8536 23.5251 12.4393 22.9393C12.9801 22.3986 13.8309 22.357 14.4193 22.8146L14.5607 22.9393L19.5 27.8775L19.5 8.25C19.5 7.08046 18.6077 6.11933 17.4667 6.0103L17.25 6H7.5C6.67157 6 6 5.32843 6 4.5Z" fill="currentColor" />
                </svg>
              </span>
              <span className="hero-subtitle heading-2">
                high-quality data
              </span>
            </h1>

            <p className="hero-description body-text-lg">
              Industry leading VLMs + computer-vision that deliver
              unmatched accuracy. Fast, and at scale.
            </p>

            <div className="hero-features">
              <FeatureLink
                href="#features"
                label="features"
                colorClass={`green ${activeSection === 'features' ? 'active' : ''}`}
                hoverTexts={["parse", "extract", "workflows", "features"]}
                disableHover={isMobile}
              />
              <FeatureLink
                href="#models"
                label="models"
                colorClass={`orange ${activeSection === 'models' ? 'active' : ''}`}
                hoverTexts={["parse-1", "layout-1", "order-1", "models"]}
                disableHover={isMobile}
              />
              <FeatureLink
                href="#security"
                label="security"
                colorClass={`yellow ${activeSection === 'security' ? 'active' : ''}`}
                hoverTexts={["soc2", "hipaa", "zdr", "security"]}
                disableHover={isMobile}
              />
              <FeatureLink
                href="#faq"
                label="faq"
                colorClass={`purple ${activeSection === 'faq' ? 'active' : ''}`}
                hoverTexts={["get-help", "quick-answers", "faq"]}
                disableHover={isMobile}
              />
            </div>

            <div className="hero-cta">
              <a
                href={isAuthenticated ? "/dashboard" : "/login"}
                className="btn btn-primary"
                onClick={(e) => {
                  e.preventDefault();
                  handleGetStarted();
                }}
              >
                Get Started
              </a>
              <a href="https://cal.com/team/chunkr-ai/chunkr-contact" target="_blank" rel="noopener noreferrer" className="btn btn-secondary">Book Demo</a>
            </div>
          </div>
        </section>

        {/* Value Proposition Section */}
        <section
          id="features"
          aria-labelledby="value-prop-heading"
          className="value-proposition-section"
          ref={valuePropRef}
        >
          <div className="value-prop-scroll-container">
            <div className="value-prop-sticky-viewport">
              <div className="value-prop-content">
                {/* Static features tag */}
                <div className="value-prop-tag">
                  <span className="feature-tag">/features</span>
                </div>

                {/* Main title */}
                <h2 id="value-prop-heading" className="value-prop-heading heading-1">
                  <span className="value-prop-title-line heading-1">
                    Simple API toolkit
                  </span>
                  <span className="value-prop-title-line heading-1">
                    to build incredible products
                  </span>
                </h2>

                {/* Dynamic content section */}
                <div className="value-prop-dynamic-content">
                  <div className="value-prop-feature-header">
                    <h3 className="value-prop-feature-title body-text-lg">
                      {valueSection <= 2 ? (
                        <div className="feature-title-with-lottie">
                          <LazyLottie
                            key="parse-animation"
                            animationPath="parse"
                            loop={false}
                            autoplay={true}
                            className="feature-lottie-icon"
                          />
                          <RandomLetterSwap
                            key='parse'
                            label='Parse'
                            reverse={false}
                          />
                        </div>
                      ) : (
                        <div className="feature-title-with-lottie">
                          <LazyLottie
                            key="extract-animation"
                            animationPath="extract"
                            loop={false}
                            autoplay={true}
                            className="feature-lottie-icon"
                          />
                          <RandomLetterSwap
                            key='extract'
                            label='Extract'
                            reverse={false}
                          />
                        </div>
                      )}
                    </h3>
                  </div>

                  {/* Progress divider line */}
                  <div className="progress-divider">
                    <div
                      className="progress-divider-fill"
                      style={{
                        '--progress-width': `${scrollProgress * 100}%`
                      } as React.CSSProperties}
                    />
                  </div>

                  <div className="value-prop-feature">
                    <div className="value-prop-feature-description body-text-lg">
                      <RandomLetterSwap
                        key={valueSection <= 2 ? 'parse-desc' : 'extract-desc'}
                        label={valueSection <= 2
                          ? 'Get perfect HTML/Markdown + precise layout analysis for any kind of document.'
                          : 'Turn documents into structured data with citations & confidence scores using natural language.'}
                        reverse={false}
                      />
                    </div>

                    <div className="value-prop-cards-container">
                      {/* Parse Cards - visible in first half of scroll */}
                      <div
                        className={`value-prop-cards parse-scrollable ${valueSection <= 2 ? 'cards-visible' : 'cards-hidden'}`}
                        style={{
                          // Mobile: scroll transform
                          // Short height laptop: show 2 cards at a time, cycle through pairs
                          // Desktop: no scroll, cards stay in place
                          transform: isMobile
                            ? `translateY(${Math.min(0, Math.max(-(200 * 6 + 24 * 5), -scrollProgress * (200 * 8 + 24 * 7)))}px)`
                            : isShortHeight
                              ? (() => {
                                // For Parse section (0-0.5 progress)
                                const parseProgress = scrollProgress * 2; // Normalize to 0-1 for Parse
                                // Show cards 0-1 for first half, cards 2-3 for second half
                                // One row height (168px) + gap (24px)
                                const rowHeight = 168 + 24;
                                return parseProgress < 0.5
                                  ? `translateY(0px)`
                                  : `translateY(-${rowHeight}px)`;
                              })()
                              : 'none'
                        }}
                      >
                        <FeatureCard
                          key="parse-card-1"
                          title="Perfect HTML/Markdown"
                          summary="Clean, LLM-ready Markdown & HTML from any document."
                          detail="Complex tables, charts, formulas, handwriting, forms, and more across file-types and domains."
                          bgImage={featureParseCard1}
                          showDetailByDefault={isMobile}
                          forceHover={!isMobile && hoveredCards.has(0)}
                        />
                        <FeatureCard
                          key="parse-card-2"
                          title="Granular bounding-boxes"
                          summary="Exact element coordinates for reliable citations."
                          detail="Precise bounding boxes for every segment and word. Build solid highlighting and citations."
                          bgImage={featureParseCard2}
                          showDetailByDefault={isMobile}
                          forceHover={!isMobile && hoveredCards.has(1)}
                        />
                        <FeatureCard
                          key="parse-card-3"
                          title="Reading-order intact"
                          summary="Preserve natural reading flow for the most complex layouts."
                          detail="Our models handle a variety of edge cases, like newspapers and large technical blueprints."
                          bgImage={featureParseCard3}
                          showDetailByDefault={isMobile}
                          forceHover={!isMobile && hoveredCards.has(2)}
                        />
                        <FeatureCard
                          key="parse-card-4"
                          title="Utilities"
                          summary="Token-aware chunking, rich metadata, and advanced vision tasks."
                          detail="RAG-optimized chunks, image-crops, metadata, native spreadsheet support, and more."
                          bgImage={featureParseCard4}
                          showDetailByDefault={isMobile}
                          forceHover={!isMobile && hoveredCards.has(3)}
                        />
                      </div>

                      {/* Extract Cards - visible in second half of scroll */}
                      <div
                        className={`value-prop-cards parse-scrollable ${valueSection >= 3 ? 'cards-visible' : 'cards-hidden'}`}
                        style={{
                          // Mobile: scroll transform
                          // Short height laptop: show 2 cards at a time, cycle through pairs
                          // Desktop: no scroll, cards stay in place
                          transform: isMobile
                            ? `translateY(${Math.min(0, Math.max(-(200 * 6 + 24 * 5), -scrollProgress * (200 * 8 + 24 * 7)))}px)`
                            : isShortHeight
                              ? (() => {
                                // For Extract section (0.5-1.0 progress)
                                const extractProgress = (scrollProgress - 0.5) * 2; // Normalize to 0-1 for Extract
                                // Show cards 0-1 for first half, cards 2-3 for second half
                                // One row height (168px) + gap (24px)
                                const rowHeight = 168 + 24;
                                return extractProgress < 0.5
                                  ? `translateY(0px)`
                                  : `translateY(-${rowHeight}px)`;
                              })()
                              : 'none'
                        }}
                      >
                        <FeatureCard
                          key="extract-card-1"
                          title="Schema compliance"
                          summary="Define your structure with Pydantic or Zod and get exact JSON output."
                          detail="Handles deeply nested objects, arrays, unions, and every JSON Schema type."
                          bgImage={featureExtractCard1}
                          showDetailByDefault={isMobile}
                          forceHover={!isMobile && hoveredCards.has(4)}
                        />
                        <FeatureCard
                          key="extract-card-2"
                          title="Multi-level citations"
                          summary="Segment, word, and spreadsheet range citations for every field."
                          detail="Segment, word, and spreadsheet range citations with exact bboxes for every extracted value."
                          bgImage={featureExtractCard2}
                          showDetailByDefault={isMobile}
                          forceHover={!isMobile && hoveredCards.has(5)}
                        />
                        <FeatureCard
                          key="extract-card-3"
                          title="Confidence metrics"
                          summary="High/Low confidence scores with citation status for each field."
                          detail="Quality signals for human-in-the-loop workflows. Flag low-confidence items for review."
                          bgImage={featureExtractCard3}
                          showDetailByDefault={isMobile}
                          forceHover={!isMobile && hoveredCards.has(6)}
                        />
                        <FeatureCard
                          key="extract-card-4"
                          title="Agent-powered loop"
                          summary="Specialized agent reviews and corrects extraction output."
                          detail="Engine for schema compliance, citations, and confidence scores—guarantees quality."
                          bgImage={featureExtractCard4}
                          showDetailByDefault={isMobile}
                          forceHover={!isMobile && hoveredCards.has(7)}
                        />
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Mobile-only static sections */}
          <div className="mobile-features-static">
            {/* Parse Section */}
            <div className="mobile-feature-section">
              <div className="value-prop-content">
                <div className="mobile-feature-header">
                  <h3 className="value-prop-feature-title body-text-lg">
                    <div className="feature-title-with-lottie">
                      <LazyLottie
                        key="mobile-parse-animation"
                        animationPath="parse"
                        loop={false}
                        autoplay={true}
                        className="feature-lottie-icon"
                      />
                      <span>Parse</span>
                    </div>
                  </h3>
                </div>

                <div className="mobile-feature-description body-text-lg">
                  Get perfect HTML/Markdown + precise bounding boxes for every element.
                </div>

                <div className="mobile-feature-cards">
                  <FeatureCard
                    key="mobile-parse-card-1"
                    title="Perfect HTML/Markdown"
                    summary="Clean, LLM-ready Markdown & HTML from any document."
                    detail="Handle complex tables, images/charts, formulas, handwriting, forms, and more across file-types and domains."
                    showDetailByDefault={true}
                  />
                  <FeatureCard
                    key="mobile-parse-card-2"
                    title="Granular bounding-boxes"
                    summary="Exact element coordinates for reliable citations."
                    detail="Segment, line, and word-level coordinates for every piece of content in your document."
                    showDetailByDefault={true}
                  />
                  <FeatureCard
                    key="mobile-parse-card-3"
                    title="Intelligent OCR"
                    summary="Extract text from images, scans, and any visual content."
                    detail="State-of-the-art vision models that handle low-quality scans, handwriting, and complex layouts."
                    showDetailByDefault={true}
                  />
                  <FeatureCard
                    key="mobile-parse-card-4"
                    title="Postprocessing"
                    summary="Token-aware chunking, rich metadata, and advanced vision tasks."
                    detail="RAG-optimized chunks, comprehensive file metadata, and handles complex elements like distant chart legends."
                    showDetailByDefault={true}
                  />
                </div>
              </div>
            </div>

            {/* Extract Section */}
            <div className="mobile-feature-section">
              <div className="value-prop-content">
                <div className="mobile-feature-header">
                  <h3 className="value-prop-feature-title body-text-lg">
                    <div className="feature-title-with-lottie">
                      <LazyLottie
                        key="mobile-extract-animation"
                        animationPath="extract"
                        loop={false}
                        autoplay={true}
                        className="feature-lottie-icon"
                      />
                      <span>Extract</span>
                    </div>
                  </h3>
                </div>

                <div className="mobile-feature-description body-text-lg">
                  Turn docs into structured data with citations & confidence scores.
                </div>

                <div className="mobile-feature-cards">
                  <FeatureCard
                    key="mobile-extract-card-1"
                    title="Schema compliance"
                    summary="Define your structure with Pydantic or Zod and get exact JSON output."
                    detail="Handles deeply nested objects, arrays, unions, and every JSON Schema type. No extra fields, no missing data."
                    showDetailByDefault={true}
                  />
                  <FeatureCard
                    key="mobile-extract-card-2"
                    title="Multi-level citations"
                    summary="Segment, word, and spreadsheet range citations for every field."
                    detail="Segment, word, and spreadsheet range citations with exact bboxes for every extracted value."
                    showDetailByDefault={true}
                  />
                  <FeatureCard
                    key="mobile-extract-card-3"
                    title="Confidence metrics"
                    summary="High/Low confidence scores with citation status for each field."
                    detail="Built-in quality signals for human-in-the-loop workflows. Flag low-confidence extractions for review."
                    showDetailByDefault={true}
                  />
                  <FeatureCard
                    key="mobile-extract-card-4"
                    title="Agent-powered loop"
                    summary="Specialized agent reviews and corrects extraction output."
                    detail="Ensures perfect schema compliance, generates all citations, and assigns confidence scores—guaranteeing quality."
                    showDetailByDefault={true}
                  />
                </div>
              </div>
            </div>
          </div>
        </section>

        {/* Models Section */}
        <section
          id="models"
          aria-labelledby="models-heading"
          className="models-section"
          ref={modelsRef}
        >
          <div className="models-scroll-container">
            <div className="models-sticky-viewport">
              <div className="models-content">
                {/* Static models tag */}
                <div className="value-prop-tag">
                  <span className="models-tag">/models</span>
                </div>

                {/* Main title */}
                <h2 id="models-heading" className="models-heading heading-1">
                  <span className="models-title-line heading-1">
                    Purpose-built intelligence
                  </span>
                </h2>

                {/* Dynamic content section */}
                <div className="models-dynamic-content">
                  <div className="models-feature-header">
                    <h3 className="models-feature-title body-text-lg">
                      <div className="feature-title-with-lottie">
                        <RandomLetterSwap
                          key={modelSection === 1 ? 'parse-1' : modelSection === 2 ? 'layout-1' : 'order-1'}
                          label={modelSection === 1 ? 'parse-1' : modelSection === 2 ? 'layout-1' : 'order-1'}
                          reverse={false}
                        />
                      </div>
                    </h3>
                  </div>

                  {/* Progress divider line */}
                  <div className="progress-divider">
                    <div
                      className="progress-divider-fill"
                      style={{
                        '--progress-width': `${modelScrollProgress * 100}%`
                      } as React.CSSProperties}
                    />
                  </div>

                  <div className="models-feature">
                    <div className="models-feature-description body-text-lg">
                      <RandomLetterSwap
                        key={modelSection === 1 ? 'parse-desc' : modelSection === 2 ? 'layout-desc' : 'order-desc'}
                        label={modelSection === 1
                          ? 'Our in-house VLM achieves SOTA accuracy on tables, formulas, images, forms and more - while maintaining production grade speeds.'
                          : modelSection === 2
                            ? 'Trained on 1M+ human-tagged pages, our layout model identifies document structure for over 20 domains and 17 segment types.'
                            : 'State-of-the-art reading order detection that achieves 95% accuracy, approaching human-level performance.'}
                        reverse={false}
                      />
                    </div>

                    <div className="models-chart-container">
                      {modelSection === 1 ? (
                        <div className="chart-wrapper">
                          <ParseChart className="model-parse-chart" />
                        </div>
                      ) : modelSection === 2 ? (
                        <div className="chart-wrapper">
                          <LayoutChart className="model-layout-chart" />
                        </div>
                      ) : (
                        <div className="chart-wrapper">
                          <OrderChart className="model-order-chart" />
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Mobile-only static sections */}
          <div className="mobile-models-static">
            {/* Parse-1 Section */}
            <div className="mobile-model-section">
              <div className="models-content">
                <div className="mobile-model-header">
                  <h3 className="models-feature-title body-text-lg">
                    <div className="feature-title-with-lottie">
                      <span>parse-1</span>
                    </div>
                  </h3>
                </div>

                <div className="mobile-model-description body-text-lg">
                  Our in-house VLM achieves SOTA accuracy on tables, formulas, images, forms and more - while maintaining production grade speeds.
                </div>

                <div className="mobile-model-chart">
                  <ParseChart className="model-parse-chart" />
                </div>
              </div>
            </div>

            {/* Layout-1.5 Section */}
            <div className="mobile-model-section">
              <div className="models-content">
                <div className="mobile-model-header">
                  <h3 className="models-feature-title body-text-lg">
                    <div className="feature-title-with-lottie">
                      <span>layout-1</span>
                    </div>
                  </h3>
                </div>

                <div className="mobile-model-description body-text-lg">
                  Trained on 1M+ human-tagged pages, our layout model identifies document structure across 20 domains and 16 segment types.
                </div>

                <div className="mobile-model-chart">
                  <LayoutChart className="model-layout-chart" />
                </div>
              </div>
            </div>

            {/* Order-1.5 Section */}
            <div className="mobile-model-section">
              <div className="models-content">
                <div className="mobile-model-header">
                  <h3 className="models-feature-title body-text-lg">
                    <div className="feature-title-with-lottie">
                      <span>order-1</span>
                    </div>
                  </h3>
                </div>

                <div className="mobile-model-description body-text-lg">
                  State-of-the-art reading order detection that achieves 95% position accuracy, approaching human-level performance.
                </div>

                <div className="mobile-model-chart">
                  <OrderChart className="model-order-chart" />
                </div>
              </div>
            </div>
          </div>
        </section>

        {/* Security Section */}
        <section
          id="security"
          aria-labelledby="security-heading"
          className="value-proposition-section security-section"
          style={{ '--accent-green': 'var(--accent-yellow)' } as React.CSSProperties}
        >
          <div className="security-scroll-container">
            <div className="security-sticky-viewport">
              <div className="value-prop-content">
                <div className="value-prop-tag">
                  <span className="feature-tag">/security</span>
                </div>

                <h2 id="security-heading" className="value-prop-heading heading-1">
                  <span className="value-prop-title-line heading-1">
                    Enterprise-grade
                  </span>
                  <span className="value-prop-title-line heading-1">
                    compliance + trust
                  </span>
                </h2>

                <div className="value-prop-feature">
                  <div className="value-prop-feature-description body-text-lg">
                    The security and privacy of your data are foundational to our platform. Visit our{' '}
                    <a
                      href="https://trust.chunkr.ai"
                      target="_blank"
                      rel="noopener noreferrer"
                      style={{ color: 'var(--accent-yellow)', fontWeight: '300' }}
                    >
                      trust center
                    </a>
                    {' '}for details.
                  </div>

                  <div className="value-prop-cards">
                    <FeatureCard
                      animated={false}
                      headline="SOC 2 Type II"
                      subtitle={<>
                        + type I
                      </>}
                      title="SOC 2 Type II"
                      hoverLink="Trust center"
                      hoverLinkUrl="https://trust.chunkr.ai"
                    />
                    <FeatureCard
                      animated={false}
                      headline="HIPAA Compliant"
                      subtitle={<>
                        BAA available
                      </>}
                      title="HIPAA Compliant"
                      hoverLink="Trust center"
                      hoverLinkUrl="https://trust.chunkr.ai"
                    />
                    <FeatureCard
                      animated={false}
                      headline="0 Data Retention"
                      subtitle={<>
                        Custom deletion
                      </>}
                      title="Zero Data Retention"
                      hoverLink="Docs"
                      hoverLinkUrl="https://docs.chunkr.ai/docs/task-system/task-handling#data-retention"
                    />
                    <FeatureCard
                      animated={false}
                      headline="99.99% Uptime"
                      subtitle={<div className="feature-card-subtitle-dot-container">
                        <span
                          className={`status-dot ${healthCheckLoading ? 'loading' : isHealthy ? 'healthy' : 'unhealthy'}`}
                          aria-hidden="true"
                        />{' '}
                        <a
                          href="https://status.chunkr.ai/"
                          target="_blank"
                          rel="noopener noreferrer"
                          style={{ fontWeight: '300' }}
                        >
                          {healthCheckLoading ? 'Checking...' : isHealthy ? 'Healthy' : 'Issues Detected'}
                        </a>
                      </div>}
                      title="Enterprise SLA"
                      hoverLink="Uptime Monitor"
                      hoverLinkUrl="https://status.chunkr.ai"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>


        {/* FAQ Section - final section before footer */}
        <section
          id="faq"
          aria-labelledby="faq-heading"
          className="value-proposition-section faq-section"
          itemScope
          itemType="https://schema.org/FAQPage"
          style={{ '--accent-green': 'var(--accent-purple)' } as React.CSSProperties}
        >
          <div className="faq-scroll-container">
            <div className="faq-sticky-viewport">
              <div className="value-prop-content">
                <div className="value-prop-tag">
                  <span className="feature-tag">/faq</span>
                </div>

                <h2 id="faq-heading" className="value-prop-heading heading-1">
                  <span className="value-prop-title-line heading-1">Quick answers</span>
                </h2>

                <div className="value-prop-feature-description body-text-lg">
                  For more information, visit our{' '}
                  <a
                    href="https://docs.chunkr.ai"
                    target="_blank"
                    rel="noopener noreferrer"
                    style={{ color: 'var(--accent-purple)', fontWeight: '300' }}
                  >
                    docs
                  </a>
                  {' '}or{' '}
                  <a
                    href="mailto:contact@chunkr.ai"
                    style={{ color: 'var(--accent-purple)', fontWeight: '300' }}
                  >
                    reach out
                  </a>
                  .
                </div>

                <div className="value-prop-feature">


                  <div className="faq-accordion" role="list">
                    {faqItems.map((item, index) => (
                      <div
                        key={`faq-item-${index}`}
                        className={`faq-item ${openFaqIndex === index ? 'open' : ''}`}
                        role="listitem"
                        itemScope
                        itemProp="mainEntity"
                        itemType="https://schema.org/Question"
                      >
                        <h3 className="faq-question-heading">
                          <button
                            id={`faq-question-${index}`}
                            type="button"
                            className="faq-question"
                            aria-expanded={openFaqIndex === index}
                            aria-controls={`faq-panel-${index}`}
                            onClick={() => toggleFaq(index)}
                          >
                            <span className="faq-question-text" itemProp="name">
                              {item.question}
                            </span>
                            <span className="faq-chevron" aria-hidden="true">
                              <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none">
                                <path d="M5 7.5L10 12.5L15 7.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                              </svg>
                            </span>
                          </button>
                        </h3>

                        <div
                          id={`faq-panel-${index}`}
                          className="faq-answer-wrapper"
                          role="region"
                          aria-labelledby={`faq-question-${index}`}
                        >
                          <div className="faq-answer" itemScope itemProp="acceptedAnswer" itemType="https://schema.org/Answer">
                            <div className="faq-answer-text body-text" itemProp="text">
                              {item.answer}
                            </div>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>

        <CTASection />

      </main>
      <SharedFooter />

      {/* Cookie Consent Banner (GDPR/CCPA Compliance) */}
      <aside role="complementary" aria-label="Cookie consent" className="cookie-consent">
        {/* Cookie consent implementation */}
      </aside>

    </>
  );
};

export default Home;
