import { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { HelpCircle, Zap, ArrowRight, MessageSquare, Package, ShoppingCart, CreditCard, LifeBuoy, Shield, Rocket } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import QuestionBox from "@/components/QuestionBox";
import { cn } from "@/lib/utils";

// ─── Data ─────────────────────────────────────────────────────────────────────
const CATEGORIES = [
  {
    id: "getting-started",
    label: "Getting Started",
    icon: Rocket,
    questions: [
      {
        q: "What is ChatSKU?",
        a: "ChatSKU is a B2B ChatCommerce plugin that adds AI-powered product search, chat, and quote request functionality to any website. Your customers can search your catalog, ask questions, and submit RFQs through a conversational interface — without you rebuilding your site.",
      },
      {
        q: "How does it work?",
        a: "You upload your product catalog (via CSV, PDF, or manual entry), customize your widget's look and feel, then copy one line of embed code to your website. Your customers can immediately start searching products and submitting quote requests through the chat widget.",
      },
      {
        q: "How long does it take to set up?",
        a: "Most businesses go live the same day. Uploading your catalog and configuring the widget typically takes a few hours. Embedding the code on your site takes minutes.",
      },
      {
        q: "Do I need a developer?",
        a: "No. If you can paste a line of code into your website (similar to adding Google Analytics), you can install ChatSKU. We provide step-by-step instructions for every major platform.",
      },
      {
        q: "What platforms does ChatSKU work with?",
        a: "Any website that allows custom HTML — WordPress, Shopify, Wix, Squarespace, Webflow, or your own custom-built site. If you can add a script tag, ChatSKU works.",
      },
    ],
  },
  {
    id: "product-catalog",
    label: "Product & Catalog",
    icon: Package,
    questions: [
      {
        q: "How do I add my products?",
        a: "Three ways: upload a CSV file with flexible column mapping, upload a PDF catalog (we extract products automatically using AI), or add products manually through the dashboard.",
      },
      {
        q: "Does it support product variants?",
        a: "Yes. ChatSKU automatically detects and groups variants (like sizes, colors, and materials) using smart SKU and name matching. Customers see variants in an expandable view within the chat.",
      },
      {
        q: "Can I include product images?",
        a: "Yes. You can upload up to 10 images per product via drag-and-drop or import from URLs during CSV upload. Images are automatically optimized for fast loading.",
      },
      {
        q: "What if my catalog changes frequently?",
        a: "You can update products anytime through the dashboard or re-upload a CSV. Changes are reflected in the widget immediately.",
      },
      {
        q: "What if my catalog isn't in a CSV or PDF?",
        a: "No problem. We can work with whatever you have. If your products live in a PDF catalog, we extract them automatically using AI. If you have an HTML product listing or an online catalog with no cart, we can pull from that too. And if your products are managed in an existing eCommerce platform or ERP system, we can connect to your backend and sync your catalog directly. However your products are stored today, we'll get them into ChatSKU — that's part of our white glove service.",
      },
    ],
  },
  {
    id: "chat-widget",
    label: "The Chat Widget",
    icon: MessageSquare,
    questions: [
      {
        q: "How smart is the AI chat?",
        a: "The AI is trained on your specific catalog. It understands product names, SKUs, descriptions, brands, specs, and variants. Customers can search using natural language like \"heavy-duty safety gloves in large\" and get accurate results.",
      },
      {
        q: "Is it just a chatbot?",
        a: "No. Unlike generic chatbots, ChatSKU is built specifically for B2B commerce. It knows your products, shows real product cards with images and pricing, and lets customers build and submit quotes directly in the conversation.",
      },
      {
        q: "Can I customize how the widget looks?",
        a: "Yes. You can set your brand's primary color, greeting message, widget position, and placeholder text. The widget is designed to blend with your existing site.",
      },
      {
        q: "Does it work on mobile?",
        a: "Yes. The widget is fully responsive and works on any screen size.",
      },
      {
        q: "What happens outside business hours?",
        a: "The AI chat works 24/7. Customers can search products and submit quote requests at any time. You'll receive an email notification for every new quote.",
      },
    ],
  },
  {
    id: "quotes-orders",
    label: "Quotes & Orders",
    icon: ShoppingCart,
    questions: [
      {
        q: "How does the quote process work?",
        a: "Customers browse products through the AI chat, add items to their quote, and submit a request. The quote appears in your dashboard where you can review it, apply pricing or discounts, add notes, and send it back to the customer.",
      },
      {
        q: "Can I set different prices for different customers?",
        a: "Yes. You can create customer groups and assign group-based discounts — either percentage or fixed amount — so your pricing tiers are applied automatically.",
      },
      {
        q: "Do customers need to create an account to submit a quote?",
        a: "Customers provide their name, email, and company details when submitting a quote. They can optionally create an account to track their quote history and save their information for future requests.",
      },
      {
        q: "Can I export quotes?",
        a: "Yes. Quotes can be exported to CSV for use in your existing accounting or ERP systems.",
      },
    ],
  },
  {
    id: "pricing-plans",
    label: "Pricing & Plans",
    icon: CreditCard,
    questions: [
      {
        q: "How does pricing work?",
        a: "Every plan is custom. We tailor pricing based on your catalog size, feature needs, and team requirements. Reach out to us and we'll put together a plan that fits.",
      },
      {
        q: "Is there a free trial?",
        a: "Yes. We offer a free trial so you can experience ChatSKU with your own catalog before committing.",
      },
      {
        q: "Can I cancel anytime?",
        a: "Yes. No long-term contracts or cancellation fees.",
      },
    ],
  },
  {
    id: "onboarding-support",
    label: "Onboarding & Support",
    icon: LifeBuoy,
    questions: [
      {
        q: "Do you offer onboarding help?",
        a: "Yes. We provide white glove onboarding for every customer. Our team will help you configure your widget, import your catalog, and get live on your site. You're never left figuring it out alone.",
      },
      {
        q: "Can you set everything up for me?",
        a: "Absolutely. Our white glove service covers full setup — from catalog import and widget configuration to embedding on your site. Just hand us your catalog and we'll take care of the rest.",
      },
      {
        q: "How do I get help after launch?",
        a: "Every customer gets direct access to our support team. We're here for troubleshooting, catalog updates, configuration changes, or anything else you need.",
      },
      {
        q: "What if I need a feature you don't have yet?",
        a: "We're building ChatSKU based on real customer feedback. Reach out to us at hello@chatsku.com — we actively prioritize features based on what our users need.",
      },
    ],
  },
  {
    id: "security-privacy",
    label: "Security & Privacy",
    icon: Shield,
    questions: [
      {
        q: "Is my data secure?",
        a: "Yes. All data is encrypted in transit and at rest. We follow industry-standard security practices for data protection.",
      },
      {
        q: "Who owns my product data?",
        a: "You do. Your product catalog, customer information, and quote data belong to you. We never sell or share your data with third parties.",
      },
      {
        q: "Is ChatSKU GDPR compliant?",
        a: "Yes. We provide data processing agreements, support data deletion requests, and give you full control over your customer data.",
      },
      {
        q: "Is there spam protection on the widget?",
        a: "Yes. The widget includes hCaptcha protection to prevent bot submissions and spam quote requests.",
      },
    ],
  },
];

// ─── Page ─────────────────────────────────────────────────────────────────────
const FAQ = () => {
  const [activeCategory, setActiveCategory] = useState("getting-started");

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            setActiveCategory(entry.target.id);
          }
        });
      },
      { rootMargin: "-20% 0px -70% 0px" }
    );

    CATEGORIES.forEach((cat) => {
      const el = document.getElementById(cat.id);
      if (el) observer.observe(el);
    });

    return () => observer.disconnect();
  }, []);

  const scrollToCategory = (id: string) => {
    const el = document.getElementById(id);
    if (el) {
      const offset = 96;
      const top = el.getBoundingClientRect().top + window.scrollY - offset;
      window.scrollTo({ top, behavior: "smooth" });
    }
  };

  return (
    <div className="min-h-screen bg-background">
      <Navbar />
      <main className="pt-24">
        {/* Header */}
        <section className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 text-center mb-14">
          <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full border border-primary/30 bg-primary/10 mb-4">
            <HelpCircle className="w-3 h-3 text-primary" />
            <span className="text-xs font-semibold text-primary">FAQ</span>
          </div>
          <h1 className="font-display font-bold text-4xl sm:text-5xl text-foreground mb-4">
            Everything you need to know
          </h1>
          <p className="text-muted-foreground text-lg">
            Can't find your answer?{" "}
            <a
              href="mailto:hello@chatsku.com"
              className="text-primary hover:underline underline-offset-4"
            >
              Email us at hello@chatsku.com
            </a>
          </p>
        </section>

        {/* Body: Sidebar + Content */}
        <section className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 mb-20">
          <div className="flex gap-10 items-start">
            {/* Sticky Sidebar */}
            <aside className="hidden lg:block w-56 flex-shrink-0 sticky top-24">
              <nav className="flex flex-col gap-1">
                {CATEGORIES.map((cat) => {
                  const Icon = cat.icon;
                  return (
                    <button
                      key={cat.id}
                      onClick={() => scrollToCategory(cat.id)}
                      className={cn(
                        "flex items-center gap-2.5 px-3 py-2 rounded-lg text-sm font-medium text-left transition-colors",
                        activeCategory === cat.id
                          ? "bg-primary/10 text-primary"
                          : "text-muted-foreground hover:text-foreground hover:bg-secondary"
                      )}
                    >
                      <Icon className="w-4 h-4 flex-shrink-0" />
                      {cat.label}
                    </button>
                  );
                })}
              </nav>
            </aside>

            {/* Accordion Content */}
            <div className="flex-1 min-w-0 space-y-12">
              {CATEGORIES.map((cat) => {
                const Icon = cat.icon;
                return (
                  <div key={cat.id} id={cat.id} className="scroll-mt-28">
                    <div className="flex items-center gap-3 mb-5">
                      <div className="w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0">
                        <Icon className="w-4 h-4 text-primary" />
                      </div>
                      <h2 className="font-display font-bold text-xl text-foreground">
                        {cat.label}
                      </h2>
                    </div>
                    <Accordion type="single" collapsible className="space-y-2">
                      {cat.questions.map((faq, i) => (
                        <AccordionItem
                          key={i}
                          value={`${cat.id}-${i}`}
                          className="border border-border rounded-xl px-5 bg-card"
                        >
                          <AccordionTrigger className="text-sm font-semibold text-foreground hover:no-underline py-4 text-left">
                            {faq.q}
                          </AccordionTrigger>
                          <AccordionContent className="text-sm text-muted-foreground leading-relaxed pb-4">
                            {faq.a}
                          </AccordionContent>
                        </AccordionItem>
                      ))}
                    </Accordion>
                  </div>
                );
              })}
            </div>
          </div>
        </section>

        {/* Bottom CTA */}
        <section className="border-t border-border bg-secondary/30 py-16">
          <div className="max-w-2xl mx-auto px-4 text-center mb-8">
            <h2 className="font-display font-bold text-2xl sm:text-3xl text-foreground mb-3">
              Still have questions?
            </h2>
            <p className="text-muted-foreground">
              Ask us below and we'll get back to you — usually within a few hours.
            </p>
          </div>
          <div className="max-w-2xl mx-auto px-4">
            <QuestionBox />
          </div>
          <div className="flex justify-center mt-8">
            <Button
              asChild
              size="default"
              className="bg-primary text-primary-foreground hover:bg-primary/90 font-semibold glow-teal-sm"
            >
              <Link to="/signup">
                Get Started Free <ArrowRight className="w-4 h-4" />
              </Link>
            </Button>
          </div>
        </section>
      </main>
      <Footer />
    </div>
  );
};

export default FAQ;
