'use client';
import React, { useState } from 'react';
import { ChevronDown } from 'lucide-react';
import Link from 'next/link';
import { useLanguage } from '@client/contexts/LanguageContext';

export default function FAQPage() {
  const { t } = useLanguage();
  const [openItem, setOpenItem] = useState<string | null>(null);
  const [activeCategoryKey, setActiveCategoryKey] = useState('gettingStarted');

  const faqCategories = [
    {
      key: 'gettingStarted',
      category: t('landing.faq.category.GettingStarted', 'Getting Started'),
      icon: '🚀',
      items: [
        { q: t('landing.faq.items.GettingStarted.0.q', 'How quickly can I get RestroAgent running?'), a: t('landing.faq.items.GettingStarted.0.a', 'Most restaurants are fully live within 2 hours. The process: upload your menu (or connect your POS), configure your AI personality, and forward your phone number. Our onboarding team guides you through every step.') },
        { q: t('landing.faq.items.GettingStarted.1.q', 'Do I need any technical knowledge?'), a: t('landing.faq.items.GettingStarted.1.a', "None at all. If you can use a smartphone, you can set up RestroAgent. We've designed the entire process to be handled by restaurant owners and managers, not IT teams.") },
        { q: t('landing.faq.items.GettingStarted.2.q', 'What do I need to get started?'), a: t('landing.faq.items.GettingStarted.2.a', 'Just your menu (PDF, image, or POS export), your phone number, and 2 hours. We handle everything else.') },
        { q: t('landing.faq.items.GettingStarted.3.q', 'Is there a free trial?'), a: t('landing.faq.items.GettingStarted.3.a', 'Yes — 14 days, full access to all features on your chosen plan. No credit card required to start.') },
      ],
    },
    {
      key: 'aiAccuracy',
      category: t('landing.faq.category.AIAccuracy', 'AI & Accuracy'),
      icon: '🧠',
      items: [
        { q: t('landing.faq.items.AIAccuracy.0.q', 'How accurate is the AI at taking orders?'), a: t('landing.faq.items.AIAccuracy.0.a', 'Our average order accuracy is 98.7% across all restaurants. The AI is trained specifically on restaurant ordering patterns and asks clarifying questions when unsure rather than guessing.') },
        { q: t('landing.faq.items.AIAccuracy.1.q', 'Can the AI handle complex orders with modifications?'), a: t('landing.faq.items.AIAccuracy.1.a', "Yes. The AI handles substitutions, allergies, cooking preferences, combo modifications, and multi-item orders. It's been trained on millions of real restaurant conversations.") },
        { q: t('landing.faq.items.AIAccuracy.2.q', "What happens when the AI can't handle a request?"), a: t('landing.faq.items.AIAccuracy.2.a', 'The AI escalates to a human staff member via real-time alert on your dashboard and mobile app. You set the escalation rules — we never leave a customer without a response.') },
        { q: t('landing.faq.items.AIAccuracy.3.q', 'Does the AI learn from my restaurant over time?'), a: t('landing.faq.items.AIAccuracy.3.a', 'Yes. The AI improves based on corrections you make and feedback from your customers. After 30 days, most restaurants see a 15-20% improvement in accuracy.') },
      ],
    },
    {
      key: 'integrations',
      category: t('landing.faq.category.Integrations', 'Integrations'),
      icon: '🔌',
      items: [
        { q: t('landing.faq.items.Integrations.0.q', 'Which POS systems do you integrate with?'), a: t('landing.faq.items.Integrations.0.a', "We integrate with 50+ POS systems including Square, Toast, Clover, Lightspeed, Revel, TouchBistro, and more. If yours isn't listed, contact us — we can usually build the integration within 2 weeks.") },
        { q: t('landing.faq.items.Integrations.1.q', 'Can I connect to delivery platforms?'), a: t('landing.faq.items.Integrations.1.a', 'Yes. We integrate with Uber Eats, DoorDash, Grubhub, Deliveroo, and more. Orders from all channels flow into a single dashboard.') },
        { q: t('landing.faq.items.Integrations.2.q', 'What payment processors do you support?'), a: t('landing.faq.items.Integrations.2.a', "Stripe, Square, PayPal, Braintree, and most major processors. Payment collection happens through your existing processor — we don't touch your money.") },
        { q: t('landing.faq.items.Integrations.3.q', 'Can I use my existing phone number?'), a: t('landing.faq.items.Integrations.3.a', 'Yes. You simply forward your existing number to RestroAgent. Customers call the same number they always have.') },
      ],
    },
    {
      key: 'pricingBilling',
      category: t('landing.faq.category.PricingBilling', 'Pricing & Billing'),
      icon: '💳',
      items: [
        { q: t('landing.faq.items.PricingBilling.0.q', 'Can I change my plan at any time?'), a: t('landing.faq.items.PricingBilling.0.a', 'Yes. Upgrades take effect immediately; downgrades apply at the next billing cycle. There are no long-term contracts on monthly plans.') },
        { q: t('landing.faq.items.PricingBilling.1.q', 'What counts as a "conversation"?'), a: t('landing.faq.items.PricingBilling.1.a', "A conversation is a single continuous interaction with one customer — whether it's a 2-message order or a 20-message booking with modifications. Starter plan includes 500/month; Growth and Enterprise are unlimited.") },
        { q: t('landing.faq.items.PricingBilling.2.q', 'Do you offer discounts for multiple locations?'), a: t('landing.faq.items.PricingBilling.2.a', 'Yes. Enterprise plan covers unlimited locations at a flat rate. For 3-10 locations, contact us for a custom Growth plan quote.') },
        { q: t('landing.faq.items.PricingBilling.3.q', 'Is there a setup fee?'), a: t('landing.faq.items.PricingBilling.3.a', 'No setup fees on any plan. You pay only the monthly or annual subscription.') },
      ],
    },
    {
      key: 'securityPrivacy',
      category: t('landing.faq.category.SecurityPrivacy', 'Security & Privacy'),
      icon: '🔒',
      items: [
        { q: t('landing.faq.items.SecurityPrivacy.0.q', 'Is customer data secure?'), a: t('landing.faq.items.SecurityPrivacy.0.a', "Yes. All data is encrypted in transit (TLS 1.3) and at rest (AES-256). We're GDPR compliant and SOC 2 Type II certified.") },
        { q: t('landing.faq.items.SecurityPrivacy.1.q', 'Do you sell customer data?'), a: t('landing.faq.items.SecurityPrivacy.1.a', 'Never. Customer data belongs to you, the restaurant. We never sell, share, or use your customer data for any purpose other than providing the service.') },
        { q: t('landing.faq.items.SecurityPrivacy.2.q', 'Are conversations recorded?'), a: t('landing.faq.items.SecurityPrivacy.2.a', 'Voice calls are transcribed (not stored as audio by default). You can enable call recording for quality assurance. All recordings are stored in your account and can be deleted at any time.') },
        { q: t('landing.faq.items.SecurityPrivacy.3.q', 'Can I delete my data?'), a: t('landing.faq.items.SecurityPrivacy.3.a', 'Yes. You can export or delete all your data at any time from your account settings. Upon cancellation, data is deleted within 30 days.') },
      ],
    },
  ];

  const activeGroup = faqCategories.find(c => c.key === activeCategoryKey);

  return (
    <>
      {/* Hero */}
      <section className="py-20 sm:py-24 text-center relative overflow-hidden">
        <div className="absolute inset-0 -z-10">
          <div className="absolute top-0 left-1/3 w-64 sm:w-80 h-64 sm:h-80 bg-orange-400/15 dark:bg-orange-500/8 rounded-full blur-3xl" />
          <div className="absolute bottom-0 right-1/3 w-48 sm:w-64 h-48 sm:h-64 bg-teal-400/10 dark:bg-teal-500/6 rounded-full blur-3xl" />
        </div>
        <div className="max-w-2xl mx-auto px-4 sm:px-6 lg:px-8">
          <p className="text-xs font-semibold text-orange-500 uppercase tracking-widest mb-4">{t('landing.faq.hero.badge', 'Help center')}</p>
          <h1 className="text-4xl sm:text-5xl font-bold text-gray-900 dark:text-white mb-4">{t('landing.faq.hero.title', 'Frequently Asked Questions')}</h1>
          <p className="text-lg sm:text-xl text-gray-500 dark:text-gray-400">{t('landing.faq.hero.subtitle', "Everything you need to know about RestroAgent. Can't find your answer?")}{' '}
            <Link href="/contact" className="text-orange-500 hover:text-orange-600 font-semibold relative group inline-block">
              {t('landing.faq.hero.contact_link', 'Contact us.')}
              <span className="absolute -bottom-0.5 left-0 right-0 h-px bg-orange-500 opacity-0 scale-x-0 group-hover:opacity-100 group-hover:scale-x-100 transition-all duration-200" />
            </Link>
          </p>
        </div>
      </section>

      <section className="pb-20 sm:pb-24 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6 sm:gap-8">
          {/* Category Nav */}
          <div className="lg:col-span-1">
            {/* Mobile: horizontal scroll */}
            <div className="lg:sticky lg:top-24">
              <div className="flex lg:flex-col gap-2 overflow-x-auto pb-2 lg:pb-0 lg:space-y-1 lg:overflow-visible">
                {faqCategories?.map(cat => (
                  <button key={cat.key} onClick={() => setActiveCategoryKey(cat.key)}
                    className={`flex-shrink-0 lg:flex-shrink flex items-center gap-2 sm:gap-3 px-3 sm:px-4 py-2.5 sm:py-3 rounded-xl text-sm font-medium text-left transition-all duration-200 whitespace-nowrap lg:whitespace-normal ${activeCategoryKey === cat.key ? 'bg-orange-50 dark:bg-orange-950/30 text-orange-600 dark:text-orange-400 border border-orange-100 dark:border-orange-900/30 shadow-sm' : 'text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800 hover:text-gray-900 dark:hover:text-white border border-transparent'}`}>
                    <span>{cat?.icon}</span>
                    <span className="hidden sm:inline">{cat.category}</span>
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* FAQ Items */}
          <div className="lg:col-span-3">
            {activeGroup && (
              <div>
                <div className="flex items-center gap-3 mb-6 sm:mb-8">
                  <span className="text-2xl sm:text-3xl">{activeGroup?.icon}</span>
                  <h2 className="text-xl sm:text-2xl font-bold text-gray-900 dark:text-white">{activeGroup?.category}</h2>
                </div>
                <div className="space-y-2.5 sm:space-y-3">
                  {activeGroup?.items?.map((item, i) => {
                    const key = `${activeCategoryKey}-${i}`;
                    const open = openItem === key;
                    return (
                      <div key={i} className={`rounded-xl border overflow-hidden transition-all duration-200 ${open ? 'border-orange-200 dark:border-orange-800 shadow-sm shadow-orange-100/50 dark:shadow-orange-900/20' : 'border-gray-100 dark:border-gray-800 hover:border-orange-100 dark:hover:border-orange-900/30'} bg-white dark:bg-gray-900`}>
                        <button onClick={() => setOpenItem(open ? null : key)}
                          className="w-full flex items-center justify-between px-4 sm:px-6 py-3.5 sm:py-4 text-left hover:bg-orange-50/50 dark:hover:bg-orange-900/10 transition-colors">
                          <span className="font-semibold text-sm text-gray-900 dark:text-white pr-4">{item?.q}</span>
                          <ChevronDown size={16} strokeWidth={2} className={`flex-shrink-0 transition-all duration-200 ${open ? 'rotate-180 text-orange-500' : 'text-gray-400'}`} />
                        </button>
                        {open && (
                          <div className="px-4 sm:px-6 pb-4 sm:pb-5 text-sm text-gray-500 dark:text-gray-400 leading-relaxed border-t border-gray-50 dark:border-gray-800 pt-3 sm:pt-4">
                            {item?.a}
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              </div>
            )}
          </div>
        </div>
      </section>

      {/* CTA */}
      <section className="py-14 sm:py-16 bg-gray-50 dark:bg-[#0d0f14] border-t border-gray-100 dark:border-gray-800">
        <div className="max-w-2xl mx-auto px-4 text-center">
          <h3 className="text-xl sm:text-2xl font-bold text-gray-900 dark:text-white mb-3">{t('landing.faq.cta.title', 'Still have questions?')}</h3>
          <p className="text-gray-500 dark:text-gray-400 mb-6">{t('landing.faq.cta.subtitle', 'Our team responds within 4 hours during business hours.')}</p>
          <Link href="/contact" className="inline-flex items-center gap-2 px-6 py-3 rounded-xl bg-orange-500 hover:bg-orange-600 text-white font-semibold text-sm shadow-lg shadow-orange-500/25 hover:shadow-orange-500/40 hover:-translate-y-0.5 transition-all duration-200 active:scale-95">
            {t('landing.faq.cta.contact_support', 'Contact Support')}
          </Link>
        </div>
      </section>
    </>
  );
}
