import { useEffect, useState, type ReactNode } from "react";
import { Plus, HelpCircle } from "lucide-react";
import AnimateIn from "@/components/AnimateIn";

/**
 * Dark-premium FAQ accordion on a white background.
 * - Green accent (#0e6305), gold highlights (#d4af37)
 * - One open at a time
 * - Smooth expand/collapse via grid-rows animation
 * - Plus/minus icon rotation
 * - Fade-in on scroll via <AnimateIn />
 * - Optional live keyword highlighting via `highlight` prop
 */

export type FAQItem = {
  question: string;
  answer: string;
};

interface FAQSectionProps {
  title?: string;
  subtitle?: string;
  eyebrow?: string;
  items: FAQItem[];
  /** When true, render section background/padding. Set false when embedding. */
  standalone?: boolean;
  /**
   * Optional keyword to highlight inside each question and answer.
   * Case-insensitive, whole-match-preserving (original capitalization kept).
   */
  highlight?: string;
}

/** Escape a user-provided string so it is safe to use inside a RegExp. */
function escapeRegExp(str: string): string {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

/**
 * Split `text` around occurrences of `keyword` and wrap each match in a
 * subtle yellow/gold <mark>, preserving the original capitalization of the
 * matched substring.
 */
function highlightText(text: string, keyword: string): ReactNode {
  const kw = keyword.trim();
  if (!kw) return text;
  const re = new RegExp(`(${escapeRegExp(kw)})`, "gi");
  const parts = text.split(re);
  return parts.map((part, i) =>
    re.test(part) && part.toLowerCase() === kw.toLowerCase() ? (
      <mark
        key={i}
        className="rounded-[4px] px-1 py-0.5 bg-[#fff3b0] text-slate-900 font-semibold ring-1 ring-[#d4af37]/40"
      >
        {part}
      </mark>
    ) : (
      <span key={i}>{part}</span>
    ),
  );
}

export default function FAQSection({
  title = "Frequently Asked Questions",
  subtitle = "Everything you need to know about DoItEasy services. Can't find what you're looking for? Our team is one message away.",
  eyebrow = "FAQ",
  items,
  standalone = true,
  highlight,
}: FAQSectionProps) {
  const hasHighlight = Boolean(highlight && highlight.trim().length > 0);

  // When the user is actively searching, open all matching items so the
  // highlight is visible without extra clicks. Otherwise default to first open.
  const [openIndex, setOpenIndex] = useState<number | null>(0);
  const [openAll, setOpenAll] = useState<boolean>(false);

  useEffect(() => {
    if (hasHighlight) {
      setOpenAll(true);
    } else {
      setOpenAll(false);
      setOpenIndex(0);
    }
  }, [hasHighlight]);

  const toggle = (i: number) =>
    setOpenIndex((curr) => (curr === i ? null : i));

  const body = (
    <div className="max-w-[900px] mx-auto px-4 sm:px-6">
      <AnimateIn>
        <div className="text-center mb-12">
          <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full border border-[#0e6305]/30 bg-[#0e6305]/5 text-[#0e6305] text-xs font-bold uppercase tracking-widest mb-4">
            <HelpCircle className="w-3.5 h-3.5" />
            {eyebrow}
          </div>
          <h2 className="text-3xl md:text-5xl font-black leading-tight text-slate-900">
            {title.split(" ").map((word, i, arr) =>
              i === arr.length - 1 ? (
                <span
                  key={i}
                  className="bg-gradient-to-r from-[#0e6305] to-[#d4af37] bg-clip-text text-transparent"
                >
                  {word}
                </span>
              ) : (
                <span key={i}>{word} </span>
              ),
            )}
          </h2>
          <p className="mt-4 text-slate-600 text-base md:text-lg leading-relaxed max-w-2xl mx-auto">
            {subtitle}
          </p>
        </div>
      </AnimateIn>

      <div className="space-y-3">
        {items.map((item, i) => {
          const isOpen = openAll || openIndex === i;
          return (
            <AnimateIn key={i} delay={i * 60}>
              <div
                className={`group rounded-2xl border bg-white transition-all duration-300 overflow-hidden
                  ${
                    isOpen
                      ? "border-[#0e6305]/40 shadow-[0_10px_40px_-12px_rgba(14,99,5,0.25)]"
                      : "border-slate-200 hover:border-[#0e6305]/30 hover:shadow-[0_8px_30px_-12px_rgba(14,99,5,0.15)]"
                  }`}
              >
                <button
                  type="button"
                  onClick={() => toggle(i)}
                  aria-expanded={isOpen}
                  aria-controls={`faq-panel-${i}`}
                  className="w-full flex items-center justify-between gap-4 px-5 sm:px-7 py-5 text-left"
                >
                  <span
                    className={`text-base sm:text-lg font-bold leading-snug transition-colors ${
                      isOpen ? "text-[#0e6305]" : "text-slate-900"
                    }`}
                  >
                    {hasHighlight
                      ? highlightText(item.question, highlight!)
                      : item.question}
                  </span>
                  <span
                    className={`shrink-0 w-9 h-9 rounded-full flex items-center justify-center transition-all duration-300 ${
                      isOpen
                        ? "bg-gradient-to-br from-[#0e6305] to-[#22c55e] text-white rotate-45 shadow-md shadow-[#0e6305]/30"
                        : "bg-slate-100 text-slate-600 group-hover:bg-[#0e6305]/10 group-hover:text-[#0e6305]"
                    }`}
                  >
                    <Plus className="w-5 h-5" />
                  </span>
                </button>

                <div
                  id={`faq-panel-${i}`}
                  className={`grid transition-[grid-template-rows] duration-300 ease-in-out ${
                    isOpen ? "grid-rows-[1fr]" : "grid-rows-[0fr]"
                  }`}
                >
                  <div className="overflow-hidden">
                    <div className="px-5 sm:px-7 pb-6 pt-0">
                      <div className="h-px w-full bg-gradient-to-r from-transparent via-[#d4af37]/30 to-transparent mb-4" />
                      <p className="text-slate-600 leading-relaxed text-[15px]">
                        {hasHighlight
                          ? highlightText(item.answer, highlight!)
                          : item.answer}
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            </AnimateIn>
          );
        })}
      </div>
    </div>
  );

  if (!standalone) return body;

  return (
    <section className="relative bg-white py-20 md:py-28 overflow-hidden">
      {/* soft accent backdrop */}
      <div
        aria-hidden="true"
        className="absolute top-0 left-1/2 -translate-x-1/2 w-[900px] h-[300px] rounded-full bg-[#0e6305]/5 blur-[120px] pointer-events-none"
      />
      <div
        aria-hidden="true"
        className="absolute bottom-0 right-0 w-[500px] h-[300px] rounded-full bg-[#d4af37]/5 blur-[120px] pointer-events-none"
      />
      <div className="relative">{body}</div>
    </section>
  );
}