"use client";

import React, { useState, useMemo, useEffect, Suspense } from "react";
import { useSearchParams } from "next/navigation";
// import ReusablePricing from "@/components/pricing/ReusablePricing";
// import "../../app/resources/faqs"; 

export const faqData = [
  {
    id: "about",
    name: "About Textspeed",
    blurb: "Company credentials, CPaaS platform capabilities, and why businesses trust Textspeed.",
    subs: [
      {
        id: "company-credentials",
        name: "Company & Credentials",
        q: [
          { q: "What is Textspeed Technology Pvt Ltd?", a: "Textspeed Technology Pvt Ltd is a premier CPaaS (Communication Platform as a Service) provider in India powering enterprise messaging, WhatsApp API, Bulk SMS, RCS, and AI Voice automation." },
          { q: "What is CPaaS and why does it matter?", a: "CPaaS allows businesses to integrate real-time communication capabilities (SMS, WhatsApp, Voice, Email) into their software via APIs without building backend telecom infrastructure." }
        ]
      },
      {
        id: "why-textspeed",
        name: "Why Textspeed",
        q: [
          { q: "Why choose Textspeed over other CPaaS providers?", a: "Textspeed offers 99.9% uptime guarantees, direct tier-1 telco routes, sub-5-second OTP delivery, no-code AI automation, and dedicated 24/7 technical support." }
        ]
      }
    ]
  },
  {
    id: "whatsapp",
    name: "WhatsApp API",
    blurb: "Official WhatsApp Business API, chatbots, broadcasts, sequence messaging and AI.",
    subs: [
      {
        id: "whatsapp-api",
        name: "WhatsApp Business API",
        q: [
          { q: "What does Textspeed do?", a: "Textspeed is an enterprise CPaaS platform offering WhatsApp Business API, Bulk SMS, RCS Messaging, Voice Solutions, and Omnichannel Automation for scalable customer communication." },
          { q: "What is the WhatsApp Business API?", a: "The WhatsApp Business API is Meta's official channel that lets businesses send and receive WhatsApp messages at scale through software instead of a phone app." },
          { q: "How is the WhatsApp Business API different from the WhatsApp Business App?", a: "Unlike the free WhatsApp Business App designed for small businesses on a single phone, the API supports multi-agent logins, automated broadcasts, AI chatbots, and CRM integrations." },
          { q: "How do I get WhatsApp Business API access?", a: "You can get instant WhatsApp Business API access through Textspeed by connecting your Meta Business Manager and verifying your phone number." },
          { q: "Can I use my existing WhatsApp number for the API?", a: "Yes, you can migrate an existing phone number to the WhatsApp Business API after deleting the existing WhatsApp account associated with that number." },
          { q: "How much does the WhatsApp Business API cost in India?", a: "Cost has two parts: Meta's per-conversation charge (utility, authentication, marketing, service) and your provider's platform fee." },
          { q: "How to get WhatsApp Green Tick?", a: "To get the WhatsApp Green Tick (Official Business Account status), your Meta Business Manager must be verified, and your brand must meet Meta's notable brand guidelines. Textspeed assists with green tick applications." }
        ]
      },
      {
        id: "whatsapp-chatbot",
        name: "WhatsApp Chatbot",
        q: [
          { q: "What is a WhatsApp chatbot?", a: "A WhatsApp chatbot is an automated assistant that replies to customers on WhatsApp instantly, 24/7, without a human agent." },
          { q: "Can I build AI chatbots on Textspeed?", a: "Yes, Textspeed provides a no-code visual builder and AI integration to deploy smart WhatsApp chatbots in minutes." }
        ]
      }
    ]
  },
  {
    id: "sms",
    name: "Bulk SMS",
    blurb: "Promotional, transactional, OTP and DLT — the questions Indian businesses ask about running SMS at scale.",
    subs: [
      {
        id: "transactional-sms",
        name: "Transactional SMS & DLT",
        q: [
          { q: "What is DLT registration for SMS?", a: "DLT (Distributed Ledger Technology) is a mandatory blockchain-based registration mandated by TRAI in India for sending bulk commercial SMS." },
          { q: "What is transactional SMS?", a: "Transactional SMS is a message triggered by a customer action or an account event, such as OTPs, order updates, and alerts." },
          { q: "How fast is OTP delivery on Textspeed?", a: "Textspeed routes OTPs through tier-1 direct carrier routes, delivering messages in under 2 to 5 seconds with 99.9% delivery rates." }
        ]
      }
    ]
  },
  {
    id: "rcs",
    name: "RCS & Omnichannel",
    blurb: "Rich Communication Services, AI Voice, Email and unified omnichannel routing.",
    subs: [
      {
        id: "rcs-messaging",
        name: "RCS Messaging",
        q: [
          { q: "What is RCS Messaging?", a: "RCS (Rich Communication Services) is the next-gen evolution of SMS featuring rich media, carousels, action buttons, and verified brand branding right inside Android messages." },
          { q: "How does Omnichannel routing work?", a: "Omnichannel routing automatically dispatches messages across WhatsApp, SMS, RCS, and Email based on delivery fallback rules and customer channel preference." }
        ]
      }
    ]
  }
];

function FaqContent() {
  const searchParams = useSearchParams();
  const qParam = searchParams.get("q");
  const searchInputRef = React.useRef(null);

  // 2. STATE MANAGEMENT
  const [activeTab, setActiveTab] = useState(0);
  const [activeSubTab, setActiveSubTab] = useState(0);
  const [openFaqIndex, setOpenFaqIndex] = useState(0); // Keeps the first FAQ open by default
  const [searchQuery, setSearchQuery] = useState("");
  const [isFocused, setIsFocused] = useState(false);

  const quickTags = [
    "WhatsApp API pricing",
    "DLT registration",
    "Green tick verification",
    "Smart fallback",
    "OTP delivery",
    "API integration"
  ];

  useEffect(() => {
    if (qParam) {
      setSearchQuery(qParam);
      
      // Auto-match question in faqData
      let foundCategoryIndex = -1;
      let foundSubIndex = -1;
      let foundFaqIndex = -1;
      const lowerQ = qParam.toLowerCase();

      faqData.forEach((cat, cIndex) => {
        cat.subs.forEach((sub, sIndex) => {
          sub.q.forEach((faq, qIndex) => {
            if (foundCategoryIndex === -1) {
              if (
                faq.q.toLowerCase().includes(lowerQ) || 
                lowerQ.includes(faq.q.toLowerCase()) ||
                cat.name.toLowerCase().includes(lowerQ) ||
                sub.name.toLowerCase().includes(lowerQ)
              ) {
                foundCategoryIndex = cIndex;
                foundSubIndex = sIndex;
                foundFaqIndex = qIndex;
              }
            }
          });
        });
      });

      if (foundCategoryIndex !== -1) {
        setActiveTab(foundCategoryIndex);
        setActiveSubTab(foundSubIndex);
        setOpenFaqIndex(foundFaqIndex);
      }

      setTimeout(() => {
        if (searchInputRef.current) {
          searchInputRef.current.focus();
        }
      }, 100);
    }
  }, [qParam]);

  // Derived state for the currently active data
  const currentCategory = faqData[activeTab];
  const currentSubcategory = currentCategory?.subs[activeSubTab];

  // 3. HANDLERS
  const handleTabChange = (index) => {
    setActiveTab(index);
    setActiveSubTab(0); // Reset sub-tab when main tab changes
    setOpenFaqIndex(0); // Reset accordion
  };

  const handleSubTabChange = (index) => {
    setActiveSubTab(index);
    setOpenFaqIndex(0); // Reset accordion
  };

  const toggleFaq = (index) => {
    setOpenFaqIndex((prevIndex) => (prevIndex === index ? null : index));
  };

  // Basic Search Logic (Filters flat list of all questions)
  const searchResults = useMemo(() => {
    if (searchQuery.trim().length < 2) return [];
    const query = searchQuery.toLowerCase();
    const results = [];
    
    faqData.forEach((cat, cIndex) => {
      cat.subs.forEach((sub, sIndex) => {
        sub.q.forEach((faq) => {
          if (faq.q.toLowerCase().includes(query) || faq.a.toLowerCase().includes(query) || sub.name.toLowerCase().includes(query)) {
            results.push({ ...faq, cIndex, sIndex, path: `${cat.name} › ${sub.name}` });
          }
        });
      });
    });
    return results.slice(0, 7); // Limit to top 7 results
  }, [searchQuery]);

  const handleSearchSelect = (result) => {
    setActiveTab(result.cIndex);
    setActiveSubTab(result.sIndex);
    const sub = faqData[result.cIndex]?.subs[result.sIndex];
    if (sub) {
      const idx = sub.q.findIndex((faq) => faq.q === result.q);
      if (idx !== -1) {
        setOpenFaqIndex(idx);
      }
    }
    setSearchQuery(result.q);
    setTimeout(() => {
      const panEl = document.querySelector(".fq-pan");
      if (panEl) {
        panEl.scrollIntoView({ behavior: "smooth", block: "start" });
      }
    }, 150);
  };

  return (
    <>
      {/* HERO & SEARCH SECTION */}
      <section className="fqhero">
        <span className="fq-orb o1"></span>
        <span className="fq-orb o2"></span>
        <div className="wrap fqh-in">
          <span className="eyebrow">Help Centre · Frequently Asked Questions</span>
          <h1>Everything you need to know about <span className="grad">business messaging in India</span></h1>
          <p>WhatsApp Business API, Bulk SMS, RCS Messaging, Voice Solutions, Email and Automation.</p>
          
          <div className="fq-search" style={{ position: "relative" }}>
            <svg className="si" viewBox="0 0 24 24" fill="none">
              <circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="2"/>
              <path d="M16.5 16.5L21 21" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
            </svg>
            <input 
              ref={searchInputRef}
              type="text" 
              placeholder="Search 240+ questions — try 'DLT', 'green tick', 'OTP'…" 
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              onFocus={() => setIsFocused(true)}
              onBlur={() => setTimeout(() => setIsFocused(false), 250)}
              style={{
                borderColor: (searchQuery || isFocused) ? "#3b82f6" : "",
                boxShadow: (searchQuery || isFocused) ? "0 0 25px rgba(59, 130, 246, 0.4)" : ""
              }}
            />
            
            {/* SEARCH DROPDOWN */}
            {searchResults.length > 0 && (
              <div className="fq-res on" style={{ display: "block", zIndex: 100 }}>
                {searchResults.map((res, i) => (
                  <div key={i} className="r" onClick={() => handleSearchSelect(res)} style={{ cursor: "pointer" }}>
                    <b style={{ color: "#000" }}>{res.q}</b>
                    <span style={{ color: "#3b82f6", display: "block", fontSize: "12px", marginTop: "2px" }}>{res.path}</span>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* QUICK TAG PILLS */}
          <div style={{ display: "flex", flexWrap: "wrap", gap: "8px", justifyContent: "center", marginTop: "16px" }}>
            {quickTags.map((tag, idx) => (
              <button
                key={idx}
                onClick={() => {
                  setSearchQuery(tag);
                  if (searchInputRef.current) searchInputRef.current.focus();
                }}
                style={{
                  background: "rgba(255, 255, 255, 0.08)",
                  border: "1px solid rgba(255, 255, 255, 0.15)",
                  color: "#e2e8f0",
                  padding: "6px 14px",
                  borderRadius: "20px",
                  fontSize: "13px",
                  fontWeight: 500,
                  cursor: "pointer",
                  transition: "all 0.2s"
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.background = "rgba(59, 130, 246, 0.2)";
                  e.currentTarget.style.borderColor = "#3b82f6";
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.background = "rgba(255, 255, 255, 0.08)";
                  e.currentTarget.style.borderColor = "rgba(255, 255, 255, 0.15)";
                }}
              >
                {tag}
              </button>
            ))}
          </div>
        </div>
      </section>

      {/* MAIN TAB NAVIGATOR */}
      <div className="fq-nav">
        <div className="wrap">
          <div className="fq-tabs">
            {faqData.map((cat, index) => (
              <button 
                key={cat.id} 
                className={`fq-t ${activeTab === index ? "on" : ""}`}
                onClick={() => handleTabChange(index)}
              >
                {cat.name}
                <span className="ct">
                  {cat.subs.reduce((acc, sub) => acc + sub.q.length, 0)}
                </span>
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* CATEGORY & ACCORDION PANEL */}
      <section className="fq-pan">
        <div className="wrap">
          <div className="fq-ph">
            <h2>{currentCategory.name} — frequently asked questions</h2>
            <p>{currentCategory.blurb}</p>
          </div>

          {/* SUB TABS */}
          <div className="fq-subs">
            {currentCategory.subs.map((sub, index) => (
              <button 
                key={sub.id} 
                className={`fq-s ${activeSubTab === index ? "on" : ""}`}
                onClick={() => handleSubTabChange(index)}
              >
                {sub.name} <b style={{ opacity: 0.55 }}>{sub.q.length}</b>
              </button>
            ))}
          </div>

          {/* ACCORDION LIST */}
          <div className="fq-list">
            {currentSubcategory?.q.map((faq, index) => {
              const isOpen = openFaqIndex === index;
              return (
                <div key={index} className={`fq-i ${isOpen ? "open" : ""}`}>
                  <button className="fq-q" onClick={() => toggleFaq(index)} aria-expanded={isOpen}>
                    <h3>{faq.q}</h3>
                    <span className="pl">
                      <svg viewBox="0 0 24 24" fill="none">
                        <path d="M12 5v14M5 12h14" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round"/>
                      </svg>
                    </span>
                  </button>
                  <div className="fq-a" style={{ maxHeight: isOpen ? "600px" : "0" }}>
                    <p>{faq.a}</p>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </section>

      {/* REUSABLE PRICING COMPONENT INJECTED HERE */}
      <section className="faq-pricing-section" style={{ background: "var(--bg-tint)", padding: "60px 0" }}>
         {/* <ReusablePricing /> */}
      </section>
    </>
  );
}

export default function FaqClient() {
  return (
    <Suspense fallback={<div>Loading FAQs...</div>}>
      <FaqContent />
    </Suspense>
  );
}