/* FAQ page — sectioned accordion with search + sticky sidebar */

function FAQPage() {
  const [query, setQuery] = React.useState("");
  const [activeSection, setActiveSection] = React.useState(window.FAQ_SECTIONS[0]?.id);
  const sections = window.FAQ_SECTIONS;

  // Filter sections by query (matches q + a text).
  const filtered = React.useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return sections;
    return sections
      .map((s) => {
        const items = s.items.filter((it) => {
          const aText = Array.isArray(it.a) ? it.a.join(" ") : it.a;
          return (
            it.q.toLowerCase().includes(q) ||
            aText.toLowerCase().includes(q)
          );
        });
        return { ...s, items };
      })
      .filter((s) => s.items.length > 0);
  }, [query, sections]);

  const matchCount = filtered.reduce((n, s) => n + s.items.length, 0);

  // Track which section is in view for the sidebar highlight
  React.useEffect(() => {
    const ids = sections.map((s) => s.id);
    const els = ids.map((id) => document.getElementById(id)).filter(Boolean);
    if (!els.length) return;
    const io = new IntersectionObserver((entries) => {
      // Pick the topmost visible section
      const visible = entries
        .filter((e) => e.isIntersecting)
        .sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top);
      if (visible[0]) setActiveSection(visible[0].target.id);
    }, { rootMargin: "-30% 0px -55% 0px", threshold: 0 });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, [sections, filtered]);

  // SEO
  React.useEffect(() => {
    document.title = "FAQ — Innoveev";
    const desc = "Answers about working with Innoveev: engagements, engineering, pricing, geography, and bilingual delivery.";
    const setMeta = (name, content, attr = "name") => {
      let el = document.head.querySelector(`meta[${attr}="${name}"]`);
      if (!el) {
        el = document.createElement("meta");
        el.setAttribute(attr, name);
        document.head.appendChild(el);
      }
      el.setAttribute("content", content);
    };
    setMeta("description", desc);

    // FAQPage structured data
    const jsonLd = {
      "@context": "https://schema.org",
      "@type": "FAQPage",
      mainEntity: window.FAQ_ITEMS.map((it) => ({
        "@type": "Question",
        name: it.q,
        acceptedAnswer: {
          "@type": "Answer",
          text: Array.isArray(it.a) ? it.a.join("\n\n") : it.a,
        },
      })),
    };
    const id = "ld-faq";
    document.getElementById(id)?.remove();
    const script = document.createElement("script");
    script.id = id;
    script.type = "application/ld+json";
    script.text = JSON.stringify(jsonLd);
    document.head.appendChild(script);
  }, []);

  return (
    <>
      <Nav />

      <header className="faq-hero">
        <div className="mesh" aria-hidden="true">
          <span className="mesh__blob mesh__blob--1"></span>
          <span className="mesh__blob mesh__blob--2"></span>
          <span className="mesh__blob mesh__blob--3"></span>
          <span className="mesh__fade-bottom"></span>
        </div>
        <div className="container">
          <div className="faq-hero__head">
            <span className="eyebrow">Help center · Updated weekly</span>
            <h1 className="faq-hero__title">
              Questions, <em>answered</em>.
            </h1>
            <p className="faq-hero__lede">
              Everything you need to know about working with Innoveev — how engagements
              start, what we charge, how four offices keep one studio in step.
            </p>

            <div className="faq-search">
              <span className="faq-search__icon" aria-hidden="true">
                <svg width="18" height="18" viewBox="0 0 20 20" fill="none">
                  <circle cx="9" cy="9" r="6" stroke="currentColor" strokeWidth="1.6"/>
                  <path d="m17 17-3.5-3.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
                </svg>
              </span>
              <input
                type="search"
                className="faq-search__field"
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="Search the FAQ (try pricing, Arabic, retainer…)"
                aria-label="Search the FAQ"
              />
              {query ? (
                <span className="faq-search__count">{matchCount} match{matchCount === 1 ? "" : "es"}</span>
              ) : null}
            </div>
          </div>
        </div>
      </header>

      <section className="section section--tight">
        <div className="container faq-layout">
          <aside className="faq-aside">
            <h2 className="faq-aside__title">Topics</h2>
            <ul className="faq-aside__list">
              {sections.map((s) => (
                <li key={s.id} className="faq-aside__item">
                  <a
                    href={`#${s.id}`}
                    className={activeSection === s.id ? "is-active" : ""}
                    data-cursor="Jump"
                  >
                    <span className="faq-aside__num">{s.num}</span>
                    <span>{s.title}</span>
                    <span className="faq-aside__count">{s.items.length}</span>
                  </a>
                </li>
              ))}
            </ul>

            <div className="faq-aside__cta">
              <h3>Still nothing?</h3>
              <p>
                Send us a short note. Most replies come back within one working day,
                often the same hour during DXB business hours.
              </p>
              <a href="index.html#contact" className="btn btn--primary btn--small">
                Email the studio <Arrow />
              </a>
            </div>
          </aside>

          <div className="faq-main">
            {filtered.length === 0 ? (
              <div className="faq-empty">
                <p className="faq-empty__title">No matches for "{query}".</p>
                <p>Try a broader term, or <a href="index.html#contact" style={{ color: "var(--accent)", textDecoration: "underline" }}>ask the studio directly</a>.</p>
              </div>
            ) : filtered.map((s) => (
              <FAQSection key={s.id} section={s} query={query} />
            ))}

            <div className="faq-closing">
              <h2 className="faq-closing__title">Question we missed? <em>Tell us.</em></h2>
              <p className="faq-closing__lede">
                If you read all the way down and still didn't find what you needed,
                that's our fault. A short message goes straight to the founding team.
              </p>
              <div className="faq-closing__ctas">
                <a href="index.html#contact" className="btn btn--primary">
                  Contact the studio <Arrow />
                </a>
                <a href="blog.html" className="btn btn--secondary">
                  Read the blog
                </a>
              </div>
            </div>
          </div>
        </div>
      </section>

      <Footer />
      <TweaksUI />
      <BuildMode />
      <KeyboardEggs />
      <CookieBanner />
      <CustomCursor enabled={window.useTweaksDefaults.cursor} />
    </>
  );
}

function FAQSection({ section, query }) {
  // Open the first item by default; remember per section
  const defaultValue = `${section.id}-0`;
  return (
    <section id={section.id} className="faq-section">
      <div className="faq-section__head">
        <span className="faq-section__num">{section.num}</span>
        <h2 className="faq-section__title">{section.title}</h2>
        <p className="faq-section__dek">{section.dek}</p>
      </div>

      <Accordion type="single" defaultValue={defaultValue}>
        {section.items.map((it, i) => {
          const value = `${section.id}-${i}`;
          const meta = `${section.num}.${String(i + 1).padStart(2, "0")}`;
          return (
            <AccordionItem key={value} value={value}>
              <AccordionTrigger>
                <Highlight text={it.q} query={query} />
              </AccordionTrigger>
              <AccordionContent>
                {(Array.isArray(it.a) ? it.a : [it.a]).map((para, j) => (
                  <p key={j}>
                    <Highlight text={para} query={query} />
                  </p>
                ))}
              </AccordionContent>
            </AccordionItem>
          );
        })}
      </Accordion>
    </section>
  );
}

function Highlight({ text, query }) {
  if (!query || !query.trim()) return text;
  const q = query.trim();
  const re = new RegExp(`(${q.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})`, "ig");
  const parts = text.split(re);
  return (
    <>
      {parts.map((p, i) =>
        p.toLowerCase() === q.toLowerCase()
          ? <mark key={i} className="faq-mark">{p}</mark>
          : <React.Fragment key={i}>{p}</React.Fragment>
      )}
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<FAQPage />);
