// components/faq.jsx
// Section 6/7. FAQ with multi-sport tabs.
// Block E: fixed click bug (key mismatch, toggle used item.q but loop used cat.id-i),
// peach left-border + chevron rotation for open state, email auto-linking, smooth height
// transition via grid-template-rows trick.

function FAQAnswer({ text }) {
  // Auto-link occurrences of hey@fanish.app as a peach mailto, and turn other
  // bare email addresses into mailtos as well.
  const parts = [];
  const re = /([\w.+-]+@[\w-]+\.[\w.-]+)/g;
  let last = 0;
  let m;
  let key = 0;
  while ((m = re.exec(text)) !== null) {
    if (m.index > last) parts.push(text.slice(last, m.index));
    const email = m[1];
    parts.push(
      <a
        key={"em-" + (key++)}
        href={"mailto:" + email}
        className="faq-a-mail"
      >
        {email}
      </a>
    );
    last = m.index + email.length;
  }
  if (last < text.length) parts.push(text.slice(last));
  return <p>{parts}</p>;
}

function FAQSection({ activeOpenItem, onItemHandled, onIntent, isLaunched }) {
  const C = window.COPY;
  const [activeTab, setActiveTab] = React.useState(C.faq.categories[0].id);
  const [openItems, setOpenItems] = React.useState({});

  // Block E2: tabs that are coming-soon (Formula 1, US Open) form the "other sports"
  // group. We render a thin vertical divider before the first such tab to visually
  // separate them from the World Cup tabs.
  const firstOtherSportIdx = C.faq.categories.findIndex((c) => c.comingSoon);

  // Block B: bottom-of-FAQ CTA. Mirrors header CTA: pre-launch opens modal,
  // post-launch deep-links to the platform store with platform detection.
  const giveItATry = () => {
    const ua = navigator.userAgent || "";
    const isIOS = /iPhone|iPad|iPod/i.test(ua);
    const isAndroid = /Android/i.test(ua);
    if (isIOS && C.iosLaunched && C.cta.appStoreUrl) {
      window.trackEvent("header_cta_click", { source: "faq", origin: "give_it_a_try", platform: "ios" });
      window.trackEvent("app_store_redirect", { source: "faq", origin: "give_it_a_try", platform: "ios" });
      window.location.href = C.cta.appStoreUrl;
    } else if (isAndroid && C.androidLaunched && C.cta.googlePlayUrl) {
      window.trackEvent("app_store_redirect", { source: "faq", origin: "give_it_a_try", platform: "android" });
      window.location.href = C.cta.googlePlayUrl;
    } else if (isAndroid) {
      window.trackEvent("header_cta_click", { source: "faq", origin: "give_it_a_try", platform: "android" });
      onIntent && onIntent("faq", "android");
    } else if (C.iosLaunched && C.cta.appStoreUrl) {
      window.trackEvent("app_store_redirect", { source: "faq", origin: "give_it_a_try", platform: "ios" });
      window.location.href = C.cta.appStoreUrl;
    } else {
      window.trackEvent("header_cta_click", { source: "faq", origin: "give_it_a_try" });
      onIntent && onIntent("faq", "android");
    }
  };

  // Stable key helper. Used by render AND toggle so they always agree.
  const itemKey = (cat, item, i) => item.id || `${cat.id}-${i}`;

  // Allow external code (e.g. "See what we're working on" link) to open a specific item.
  React.useEffect(() => {
    if (!activeOpenItem) return;
    for (const cat of C.faq.categories) {
      if (cat.items && cat.items.find((it) => it.id === activeOpenItem)) {
        setActiveTab(cat.id);
        setOpenItems((prev) => ({ ...prev, [activeOpenItem]: true }));
        setTimeout(() => {
          const el = document.getElementById(activeOpenItem);
          if (el) el.scrollIntoView({ behavior: "smooth", block: "center" });
        }, 100);
        break;
      }
    }
    onItemHandled && onItemHandled();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeOpenItem]);

  const onTabChange = (id, label) => {
    setActiveTab(id);
    window.trackEvent("faq_tab_change", { source: "faq", tab: label });
  };

  const toggle = (key, item, category) => {
    const willOpen = !openItems[key];
    setOpenItems((prev) => ({ ...prev, [key]: willOpen }));
    if (willOpen) {
      window.trackEvent("faq_question_open", {
        source: "faq",
        question: item.q,
        category,
      });
    }
  };

  const cat = C.faq.categories.find((c) => c.id === activeTab);
  const showSub = !!(C.faq.sub && C.faq.sub.length);

  // Print mode: render every category back-to-back so the printed PDF has the full FAQ.
  const printMode = typeof document !== "undefined" &&
    document.body && document.body.classList.contains("print-mode");

  if (printMode) {
    return (
      <section
        id="faq"
        aria-labelledby="faq-heading"
        className="section-cream faq"
      >
        <div className="container">
          <div className="section-head">
            <h2 id="faq-heading" className="section-h2">{C.faq.heading}</h2>
            {showSub && <p className="section-sub">{C.faq.sub}</p>}
          </div>

          {C.faq.categories.map((pc) => (
            <div key={pc.id} className="faq-print-cat">
              <h3 className="faq-print-cat-h">{pc.label}</h3>
              {pc.comingSoon ? (
                <div className="faq-coming-soon">
                  <p>{pc.comingSoonText}</p>
                </div>
              ) : (
                <div className="faq-panel">
                  {(pc.items || []).map((item, i) => (
                    <div
                      key={item.id || `${pc.id}-${i}`}
                      id={item.id || undefined}
                      className="faq-item open"
                    >
                      <div className="faq-q">
                        <span className="faq-q-text">{item.q}</span>
                      </div>
                      <div className="faq-a-wrap open">
                        <div className="faq-a-inner">
                          <div className="faq-a">
                            <FAQAnswer text={item.a} />
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          ))}
        </div>
      </section>
    );
  }

  return (
    <section
      id="faq"
      aria-labelledby="faq-heading"
      className="section-cream faq"
    >
      <div className="container">
        <div className="section-head">
          <h2 id="faq-heading" className="section-h2">{C.faq.heading}</h2>
          {showSub && <p className="section-sub">{C.faq.sub}</p>}
        </div>

        <div className="faq-tabs" role="tablist">
          {C.faq.categories.map((c, idx) => (
            <React.Fragment key={c.id}>
              {idx === firstOtherSportIdx && firstOtherSportIdx > 0 && (
                <span className="faq-tabs-divider" aria-hidden="true" />
              )}
              <button
                role="tab"
                aria-selected={activeTab === c.id}
                className={"faq-tab" + (activeTab === c.id ? " active" : "")}
                data-track="faq_tab_change"
                onClick={() => onTabChange(c.id, c.label)}
              >
                {c.label}
              </button>
            </React.Fragment>
          ))}
        </div>

        <div className="faq-panel" role="tabpanel">
          {cat && cat.comingSoon && (
            <div className="faq-coming-soon ph-mark" data-ph="Coming soon">
              <p>{cat.comingSoonText}</p>
            </div>
          )}

          {cat && cat.items && cat.items.map((item, i) => {
            const key = itemKey(cat, item, i);
            const isOpen = !!openItems[key];
            return (
              <div
                key={key}
                id={item.id || undefined}
                className={"faq-item" + (isOpen ? " open" : "")}
              >
                <button
                  type="button"
                  className="faq-q"
                  aria-expanded={isOpen}
                  data-track="faq_question_open"
                  onClick={() => toggle(key, item, cat.label)}
                >
                  <span className="faq-q-text">{item.q}</span>
                  <span className={"faq-q-chev" + (isOpen ? " open" : "")}>
                    <IconChevron open={isOpen} />
                  </span>
                </button>
                {/* Smooth height transition via grid-template-rows trick.
                    Always rendered so we can animate the close. */}
                <div className={"faq-a-wrap" + (isOpen ? " open" : "")}>
                  <div className="faq-a-inner">
                    <div className="faq-a">
                      <FAQAnswer text={item.a} />
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

window.FAQSection = FAQSection;
