"use client";

import { useState } from "react";
import { motion } from "framer-motion";
import { ChevronDown } from "@/components/ui/icons";
import AnimatedButton from "@/components/ui/AnimatedButton";

/**
 * FAQ — centered column of expandable glass cards (distinct from the
 * split-accordion used in Our Expertise). Answers stay mounted
 * (height-animated only) so every Q&A is crawlable, and the section emits
 * FAQPage JSON-LD for rich results. Brand-strict.
 */
const FAQS = [
  {
    q: "How much does a project cost?",
    a: "It depends on scope — a focused MVP sits in a very different range than an enterprise platform. After a free discovery call we break your idea into milestones and give you a fixed, no-surprises quote. You'll always know what you're paying for before we write a line of code.",
  },
  {
    q: "How long does it take to launch?",
    a: "Most MVPs ship in 8–14 weeks; larger platforms run in phased releases. We agree on the timeline at kickoff and you see working software every week — so progress is something you watch, not something you take on faith.",
  },
  {
    q: "How do we communicate during the project?",
    a: "You get a dedicated project lead, a shared Slack channel and a weekly demo call. Roadmap, budget and progress live in a dashboard you can open anytime. No black boxes, no surprises in week ten.",
  },
  {
    q: "Can you take over an existing codebase or team?",
    a: "Yes. We start with a code and architecture audit, give you an honest report on what's worth keeping, then either embed senior engineers alongside your team or take delivery ownership end-to-end — whichever fits.",
  },
  {
    q: "Who owns the code and intellectual property?",
    a: "You do — completely. Code, designs, infrastructure and documentation are yours, in your repositories and accounts, with a full handover. We're also happy to sign an NDA before the first conversation.",
  },
  {
    q: "How do we get started?",
    a: "Book a free discovery call. We'll dig into your idea, map the scope and send a proposal with timeline and fixed pricing — usually within a few days. From yes to kickoff takes about a week.",
  },
];

const EASE = [0.21, 0.47, 0.32, 0.98];

const container = { hidden: {}, show: { transition: { staggerChildren: 0.07 } } };
const rise = {
  hidden: { opacity: 0, y: 28 },
  show: { opacity: 1, y: 0, transition: { duration: 0.55, ease: EASE } },
};

/**
 * @param {Object}   [props]
 * @param {{q:string,a:string}[]} [props.items]  Q&A pairs (defaults to the home FAQ set).
 * @param {string}   [props.subtitle]            Line under the heading.
 * @param {boolean}  [props.emitSchema]          Emit FAQPage JSON-LD (off when the page already does).
 */
export default function Faq({ items = FAQS, subtitle = "The things teams usually ask before working with us.", emitSchema = true, showCta = true } = {}) {
  // All closed by default; -1 = none open.
  const [open, setOpen] = useState(-1);

  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "FAQPage",
    mainEntity: items.map(({ q, a }) => ({
      "@type": "Question",
      name: q,
      acceptedAnswer: { "@type": "Answer", text: a },
    })),
  };

  return (
    <section className="relative overflow-hidden bg-background py-14 text-foreground md:py-16">
      {/* FAQ rich-results schema */}
      {emitSchema && (
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
        />
      )}

      <div className="pointer-events-none absolute left-1/2 top-0 h-[26rem] w-[40rem] -translate-x-1/2 rounded-full bg-primary/10 blur-[150px]" />

      <div className="container relative">
        {/* Header */}
        <motion.div
          variants={rise}
          initial="hidden"
          whileInView="show"
          viewport={{ once: true, amount: 0.5 }}
          className="mx-auto max-w-2xl text-center"
        >
          <span className="inline-flex items-center gap-2 rounded-full border border-border bg-surface/60 px-4 py-1.5 text-xs font-semibold uppercase tracking-wider text-muted-foreground backdrop-blur">
            <span className="h-1.5 w-1.5 rounded-full bg-primary" />
            FAQ
          </span>
          <h2 className="mt-5 font-heading text-3xl font-bold leading-[1.12] tracking-tight sm:text-4xl md:text-5xl">
            Questions,{" "}
            <span className="animate-text-shimmer bg-gradient-to-r from-primary via-accent to-primary bg-clip-text text-transparent">
              answered.
            </span>
          </h2>
          <p className="mx-auto mt-4 max-w-md text-base text-muted-foreground">
            {subtitle}
          </p>
        </motion.div>

        {/* Card accordion — centered column */}
        <motion.div
          variants={container}
          initial="hidden"
          whileInView="show"
          viewport={{ once: true, amount: 0.1 }}
          className="mt-12 gap-4 lg:columns-2"
        >
          {items.map(({ q, a }, i) => {
            const isOpen = i === open;
            return (
              <motion.div
                key={q}
                variants={rise}
                className={
                  "mb-4 overflow-hidden rounded-2xl border break-inside-avoid transition-all duration-300 " +
                  (isOpen
                    ? "border-primary/50 bg-surface shadow-xl shadow-primary/10"
                    : "border-border bg-surface/50 hover:border-primary/30 hover:bg-surface/80")
                }
              >
                <button
                  onClick={() => setOpen(isOpen ? -1 : i)}
                  aria-expanded={isOpen}
                  className="flex w-full items-center gap-4 px-6 py-5 text-left"
                >
                  <h3
                    className={
                      "flex-1 font-heading text-base font-semibold leading-snug transition-colors sm:text-lg " +
                      (isOpen ? "text-primary" : "text-foreground")
                    }
                  >
                    {q}
                  </h3>
                  <span
                    className={
                      "flex h-8 w-8 shrink-0 items-center justify-center rounded-full border transition-all duration-300 " +
                      (isOpen
                        ? "rotate-180 border-primary/40 bg-primary/15 text-primary"
                        : "border-border text-muted-foreground")
                    }
                  >
                    <ChevronDown className="h-4 w-4" />
                  </span>
                </button>

                {/* Answer — mounted always, height animated */}
                <motion.div
                  initial={false}
                  animate={{ height: isOpen ? "auto" : 0, opacity: isOpen ? 1 : 0 }}
                  transition={{ duration: 0.4, ease: EASE }}
                  className="overflow-hidden"
                >
                  <p className="px-6 pb-6 text-[15px] leading-relaxed text-muted-foreground">
                    {a}
                  </p>
                </motion.div>
              </motion.div>
            );
          })}
        </motion.div>

        {/* CTA banner — full width at the end */}
        {showCta && (
          <motion.div
            variants={rise}
            initial="hidden"
            whileInView="show"
            viewport={{ once: true }}
            className="relative mt-8 overflow-hidden rounded-2xl border border-primary/40 bg-gradient-to-r from-primary/15 via-surface to-accent/10"
          >
            <div className="pointer-events-none absolute -right-10 -top-10 h-32 w-32 rounded-full bg-primary/25 blur-3xl" />
            <div className="relative flex flex-col gap-4 px-7 py-7 sm:flex-row sm:items-center sm:justify-between">
              <div>
                <h3 className="font-heading text-lg font-semibold sm:text-xl">
                  Still have questions?
                </h3>
                <p className="mt-1 text-sm text-muted-foreground">
                  Tell us about your project — we reply within 24 hours.
                </p>
              </div>
              <AnimatedButton href="/contact" size="sm" className="shrink-0">
                Ask us anything
              </AnimatedButton>
            </div>
          </motion.div>
        )}
      </div>
    </section>
  );
}
