// About Us · Google Reviews · FAQ · Quote CTA · Footer · Sticky mobile CTA
const ST = window.Tokens;
const SA = window.Atoms;

const GOOGLE_REVIEWS_PLACEHOLDER = [
  {
    name: "—",
    locale: "—",
    days: "—",
    rating: 5,
    text: "Verified Google/customer feedback will live here after Nigel approves the real source.",
    verified: false,
    placeholder: true,
  },
  {
    name: "—",
    locale: "—",
    days: "—",
    rating: 5,
    text: "Embed your most recent Google review here — we don't publish anything that isn't verified.",
    verified: false,
    placeholder: true,
  },
  {
    name: "—",
    locale: "—",
    days: "—",
    rating: 5,
    text: "Embed your most recent Google review here — we don't publish anything that isn't verified.",
    verified: false,
    placeholder: true,
  },
];

function normalizeGoogleReviewPayload(payload) {
  if (!Array.isArray(payload)) return GOOGLE_REVIEWS_PLACEHOLDER;

  const normalized = payload
    .map((r) => ({
      name: typeof r.name === "string" ? r.name : "Google customer",
      locale: typeof r.locale === "string" ? r.locale : "Google",
      days: typeof r.days === "string" && r.days.length ? r.days : (typeof r.relativeTime === "string" ? r.relativeTime : "Recently"),
      rating: Number.isFinite(Number(r.rating)) ? Math.max(1, Math.min(5, Math.round(Number(r.rating)))) : 5,
      text: typeof r.text === "string" ? r.text : "",
      verified: Boolean(r.googleVerified),
      placeholder: false,
    }))
    .filter((r) => r.text && r.text.trim().length > 3);

  return normalized.length ? normalized : GOOGLE_REVIEWS_PLACEHOLDER;
}

function getGoogleReviewsFromWindow() {
  const data = window.APEX_GOOGLE_REVIEWS;
  const reviews = normalizeGoogleReviewPayload(data);

  return {
    reviews,
    sourceLabel: window.APEX_GOOGLE_PLACE_ID ? `Google Reviews (${window.APEX_GOOGLE_PLACE_ID})` : "Google Reviews",
    sourceUrl: window.APEX_GOOGLE_REVIEWS_SOURCE_URL || "https://google.com",
    summary: window.APEX_GOOGLE_REVIEWS_SUMMARY || null,
  };
}

// ============ ABOUT US (replaces Service Area page) ============
function AboutUs() {
  return (
    <section id="about" style={{ background: ST.ivory }}>
      <div className="apex-about-grid">
        <div>
          <Eyebrow>About Apex</Eyebrow>
          <h2 className="apex-h2" style={{ ...SA.heading, marginTop: 12 }}>
            Local. Composed. Generous.
          </h2>
          <hr style={{ width: 64, height: 1, background: ST.gold, border: 0, margin: "16px 0 0" }} />
          <p style={{ ...SA.body, marginTop: 18, fontSize: 16, lineHeight: 1.65 }}>
            A small Fort Wayne team. <em style={{ fontStyle: "italic", color: ST.burgundy }}>Quoted before we arrive</em>,
            cleaned to the same checklist every time, and a phone number that gets answered.
          </p>

          {/* Specific stats — voice pillar I */}
          <div className="apex-about-stats">
            <div className="apex-stat">
              <span className="apex-stat-num">2+</span>
              <p className="apex-stat-label">Cities &amp; surrounding areas</p>
              <p className="apex-stat-sub">Fort Wayne and the surrounding areas</p>
            </div>
            <div className="apex-stat">
              <span className="apex-stat-num">60s</span>
              <p className="apex-stat-label">To a real quote</p>
              <p className="apex-stat-sub">Three quick questions — no call required</p>
            </div>
            <div className="apex-stat">
              <span className="apex-stat-num">100%</span>
              <p className="apex-stat-label">Verified reviews</p>
              <p className="apex-stat-sub">Google &amp; direct feedback only</p>
            </div>
          </div>
        </div>

        <aside className="apex-about-photo">
          <div className="apex-about-photo-stack">
            {/* Tall main photo with stewardship pull-quote */}
            <div style={{ position: "relative", borderRadius: 28, overflow: "hidden",
                          border: `1px solid ${ST.borderGold}`,
                          boxShadow: "0 28px 70px rgba(91,22,25,0.22)" }}>
              <img src="/assets/hero-warm-living.jpg" alt="A bright, freshly cleaned home"
                   style={{ display: "block", width: "100%", aspectRatio: "4/5", objectFit: "cover",
                            filter: "saturate(1.06) contrast(1.04)" }} />
              <div style={{ position: "absolute", left: 18, right: 18, bottom: 18,
                            background: "rgba(248,245,238,0.95)", backdropFilter: "blur(8px)",
                            border: `1px solid ${ST.border}`, borderRadius: 18, padding: 16 }}>
                <p style={{ margin: 0, fontFamily: ST.fontSans, fontSize: 11, fontWeight: 700,
                            textTransform: "uppercase", letterSpacing: "0.30em", color: ST.burgundyAccent }}>
                  Stewardship
                </p>
                <p style={{ margin: "6px 0 0", fontFamily: ST.fontSerif, fontWeight: 400, fontSize: 19,
                            lineHeight: 1.2, letterSpacing: "0.02em", color: ST.burgundy }}>
                  A clean home you can feel — not just one that looks clean.
                </p>
              </div>
            </div>

            {/* Second smaller photo — kitchen detail */}
            <div className="apex-about-photo-small">
              <img src="/assets/hero-warm-kitchen.jpg" alt="Soft morning light in a clean kitchen"
                   style={{ display: "block", width: "100%", height: "100%", objectFit: "cover",
                            filter: "saturate(1.06) contrast(1.04)" }} />
            </div>

            {/* Third tiny photo — bedroom detail */}
            <div className="apex-about-photo-tiny">
              <img src="/assets/apex-recurring.jpeg" alt="Freshly made bed"
                   style={{ display: "block", width: "100%", height: "100%", objectFit: "cover",
                            filter: "saturate(1.06) contrast(1.04)" }} />
            </div>
          </div>
        </aside>
      </div>
    </section>
  );
}

// ============ GOOGLE REVIEWS (carousel) ============
function GoogleReviews() {
  const [{ reviews, summary }, setReviewState] = React.useState(() => getGoogleReviewsFromWindow());
  const [current, setCurrent] = React.useState(0);
  const trackRef = React.useRef(null);
  const containerRef = React.useRef(null);
  const autoRef = React.useRef(null);
  const [cardsPerView, setCardsPerView] = React.useState(1);
  const [isPaused, setIsPaused] = React.useState(false);

  React.useEffect(() => {
    const apply = () => setReviewState(getGoogleReviewsFromWindow());
    apply();

    const onIntegrationUpdate = () => setReviewState(getGoogleReviewsFromWindow());
    window.addEventListener("apex:integrations-updated", onIntegrationUpdate);

    return () => window.removeEventListener("apex:integrations-updated", onIntegrationUpdate);
  }, []);

  // Responsive cards-per-view
  React.useEffect(() => {
    const calc = () => {
      const w = window.innerWidth;
      if (w >= 1280) setCardsPerView(3);
      else if (w >= 768) setCardsPerView(2);
      else setCardsPerView(1);
    };
    calc();
    window.addEventListener("resize", calc);
    return () => window.removeEventListener("resize", calc);
  }, []);

  const total = reviews.length;
  const maxSlide = Math.max(0, total - cardsPerView);

  // Clamp current when cardsPerView changes
  React.useEffect(() => {
    setCurrent((c) => Math.min(c, Math.max(0, total - cardsPerView)));
  }, [cardsPerView, total]);

  // Auto-advance
  React.useEffect(() => {
    if (isPaused || total <= cardsPerView) return;
    autoRef.current = setInterval(() => {
      setCurrent((c) => (c >= maxSlide ? 0 : c + 1));
    }, 5000);
    return () => clearInterval(autoRef.current);
  }, [isPaused, maxSlide, total, cardsPerView]);

  const goTo = (idx) => setCurrent(Math.max(0, Math.min(idx, maxSlide)));
  const prev = () => goTo(current - 1);
  const next = () => goTo(current + 1);

  const hasSummary = !!(summary && Number(summary.count) > 0 && Number(summary.rating) > 0);
  const ratingText = hasSummary
    ? `${Number(summary.rating).toFixed(1)} ★ (${Number(summary.count)} reviews)`
    : "Google review source pending (configure APEX_GOOGLE_MAPS_API_KEY).";
  const showArrows = total > cardsPerView;
  const dots = Array.from({ length: maxSlide + 1 }, (_, i) => i);

  const sourceUrl = window.APEX_GOOGLE_REVIEWS_SOURCE_URL || "https://google.com";

  return (
    <section id="reviews" style={{ background: ST.white, borderTop: `1px solid ${ST.border}`, borderBottom: `1px solid ${ST.border}` }}>
      <div className="apex-section">
        <Eyebrow>Reviews</Eyebrow>
        <h2 className="apex-h2" style={{ ...SA.heading, marginTop: 12 }}>
          Earned feedback only.
        </h2>
        <hr style={{ width: 64, height: 1, background: ST.gold, border: 0, margin: "16px 0 0" }} />
        <p style={{ margin: "16px 0 0", fontFamily: ST.fontMono, fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.16em", color: "rgba(31,29,29,0.55)" }}>
          {ratingText}
        </p>

        {/* Carousel */}
        <div
          className="apex-reviews-carousel"
          ref={containerRef}
          onMouseEnter={() => setIsPaused(true)}
          onMouseLeave={() => setIsPaused(false)}
          style={{ marginTop: 32 }}
        >
          {/* Left arrow */}
          {showArrows && (
            <button
              className="apex-carousel-arrow apex-carousel-arrow--left"
              onClick={prev}
              disabled={current === 0}
              aria-label="Previous reviews"
            >
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M15 18l-6-6 6-6"/>
              </svg>
            </button>
          )}

          {/* Track */}
          <div className="apex-carousel-track" ref={trackRef}
            style={{ transform: `translateX(-${current * (100 / cardsPerView)}%)` }}>
            {reviews.map((r, i) => (
              <div className="apex-carousel-slide" key={`${r.name}-${i}`}
                style={{ flex: `0 0 ${100 / cardsPerView}%` }}>
                <ReviewCard {...r} />
              </div>
            ))}
          </div>

          {/* Right arrow */}
          {showArrows && (
            <button
              className="apex-carousel-arrow apex-carousel-arrow--right"
              onClick={next}
              disabled={current >= maxSlide}
              aria-label="Next reviews"
            >
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M9 18l6-6-6-6"/>
              </svg>
            </button>
          )}

          {/* Dots */}
          {dots.length > 1 && (
            <div className="apex-carousel-dots">
              {dots.map((i) => (
                <button
                  key={i}
                  className={`apex-carousel-dot ${i === current ? "apex-carousel-dot--active" : ""}`}
                  onClick={() => goTo(i)}
                  aria-label={`Go to review slide ${i + 1}`}
                />
              ))}
            </div>
          )}

          {/* "Read all on Google" link */}
          <div style={{ textAlign: "center", marginTop: 20 }}>
            <a href={sourceUrl} target="_blank" rel="noopener noreferrer"
              style={{ fontFamily: ST.fontSans, fontSize: 13, fontWeight: 600, color: ST.burgundyAccent, textDecoration: "none" }}>
              Read all reviews on Google →
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}

function ReviewCard({ name, locale, days, rating, text, placeholder }) {
  const T = window.Tokens;
  return (
    <article style={{
      position: "relative",
      background: placeholder ? "transparent" : T.white,
      border: placeholder ? `1px dashed ${T.borderStrong}` : `1px solid ${T.border}`,
      borderRadius: 20, padding: "22px 22px 20px",
      boxShadow: placeholder ? "none" : "0 4px 12px rgba(31,29,29,0.06)",
      display: "flex", flexDirection: "column", gap: 12,
    }}>
      {/* Open quote ornament */}
      <span style={{ fontFamily: T.fontSerif, fontSize: 56, lineHeight: 0.8,
                     color: T.gold, marginTop: -6, marginBottom: -16 }}>“</span>
      <p style={{ margin: 0, fontFamily: T.fontSerif, fontWeight: 400, fontSize: 18,
                  lineHeight: 1.35, letterSpacing: "0.01em",
                  color: placeholder ? "rgba(31,29,29,0.42)" : T.charcoal,
                  fontStyle: placeholder ? "italic" : "normal" }}>
        {text}
      </p>
      <hr style={{ width: 36, height: 1, background: T.gold, border: 0, margin: "4px 0 0" }} />
      <footer style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10 }}>
        <div>
          <p style={{ margin: 0, fontFamily: T.fontSans, fontSize: 13, fontWeight: 700, color: T.burgundy }}>
            {name}{locale !== "—" && <span style={{ color: "rgba(31,29,29,0.55)", fontWeight: 500 }}> · {locale}</span>}
          </p>
          <p style={{ margin: "2px 0 0", fontFamily: T.fontMono, fontSize: 10.5,
                      textTransform: "uppercase", letterSpacing: "0.16em", color: "rgba(31,29,29,0.55)" }}>
            {days && days !== "—" ? days : ""}
          </p>
        </div>
        <Stars count={rating} dim={placeholder} />
      </footer>
    </article>
  );
}

function Stars({ count, dim }) {
  return (
    <span style={{ display: "inline-flex", gap: 1, color: dim ? "rgba(200,161,90,0.35)" : "#C8A15A" }}>
      {Array.from({ length: 5 }).map((_, i) => (
        <svg key={i} width="14" height="14" viewBox="0 0 24 24" fill={i < count ? "currentColor" : "none"} stroke="currentColor" strokeWidth="1.4">
          <path d="M12 2 14.6 9 22 9.5 16.4 14.4 18.2 22 12 17.8 5.8 22 7.6 14.4 2 9.5 9.4 9z"/>
        </svg>
      ))}
    </span>
  );
}

function GoogleG() {
  return (
    <svg width="14" height="14" viewBox="0 0 18 18" aria-hidden="true">
      <path fill="#4285F4" d="M17.64 9.2c0-.64-.06-1.25-.16-1.84H9v3.49h4.84a4.14 4.14 0 0 1-1.79 2.71v2.26h2.9c1.7-1.56 2.68-3.86 2.68-6.62z"/>
      <path fill="#34A853" d="M9 18c2.43 0 4.47-.8 5.96-2.18l-2.9-2.26c-.8.54-1.84.86-3.06.86A5.32 5.32 0 0 1 3.96 10.7H.96v2.34A9 9 0 0 0 9 18z"/>
      <path fill="#FBBC05" d="M3.96 10.7A5.41 5.41 0 0 1 3.68 9c0-.59.1-1.17.28-1.7V4.96H.96A9 9 0 0 0 0 9c0 1.45.35 2.83.96 4.04l3-2.34z"/>
      <path fill="#EA4335" d="M9 3.58c1.32 0 2.5.46 3.44 1.35l2.58-2.58A9 9 0 0 0 .96 4.96l3 2.34A5.36 5.36 0 0 1 9 3.58z"/>
    </svg>
  );
}

// ============ FAQ ============
function FAQ() {
  const faq = window.Content.faq;
  const [openIdx, setOpenIdx] = React.useState(0);
  return (
    <section id="faq" style={{ background: ST.ivory }}>
      <div className="apex-section">
        <Eyebrow>FAQ</Eyebrow>
        <h2 className="apex-h2" style={{ ...SA.heading, marginTop: 12 }}>
          Straight answers before anyone books.
        </h2>
        <hr style={{ width: 64, height: 1, background: ST.gold, border: 0, margin: "16px 0 0" }} />
        <div className="apex-faq-grid" style={{ marginTop: 32 }}>
          {faq.map((entry, i) => (
            <FAQRow key={entry.q} entry={entry} open={openIdx === i} onToggle={() => setOpenIdx(openIdx === i ? -1 : i)} />
          ))}
        </div>
      </div>
    </section>
  );
}

function FAQRow({ entry, open, onToggle }) {
  return (
    <div style={{
      background: open ? "#EFE6E2" : ST.mist,
      border: `1px solid ${open ? "rgba(91,22,25,0.18)" : "rgba(91,22,25,0.12)"}`,
      borderRadius: 18, padding: 20,
      transition: "background 220ms ease, border-color 220ms ease",
    }}>
      <button onClick={onToggle} style={{
        all: "unset", cursor: "pointer", width: "100%",
        display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12,
      }}>
        <span style={{ fontFamily: ST.fontSans, fontWeight: 700, color: ST.burgundy, fontSize: 15, flex: 1, textAlign: "left" }}>
          {entry.q}
        </span>
        <span style={{
          width: 30, height: 30, borderRadius: 999, flex: "none",
          background: open ? ST.burgundy : ST.white,
          color: open ? "#fff" : ST.burgundyAccent,
          border: open ? "none" : `1px solid ${ST.border}`,
          display: "grid", placeItems: "center",
          transform: open ? "rotate(45deg)" : "rotate(0deg)",
          transition: "transform 240ms cubic-bezier(.16,1,.3,1), background 200ms ease",
        }}>
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none"><path d="M6 2v8M2 6h8" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>
        </span>
      </button>
      {open && (
        <div>
          <hr style={{ width: 48, height: 1, background: ST.gold, border: 0, margin: "14px 0 12px" }} />
          <p style={{ margin: 0, fontFamily: ST.fontSans, fontSize: 13.5, lineHeight: 1.65, color: "rgba(31,29,29,0.78)" }}>
            {entry.a}
          </p>
        </div>
      )}
    </div>
  );
}

// ============ QUOTE CTA ============
function QuoteCTA({ onQuote, ctaLabel }) {
  const label = ctaLabel || "Get a 60-second Quote";
  return (
    <section id="quote-cta" style={{ background: ST.ivory, padding: "0 0 64px" }}>
      <div className="apex-cta-wrap">
        <div style={{
          position: "relative", overflow: "hidden",
          background: ST.burgundy, color: "#fff",
          border: `1px solid ${ST.borderGold}`,
          borderRadius: 28,
          padding: "36px 28px 38px",
          boxShadow: "0 28px 70px rgba(91,22,25,0.28)",
        }}>
          <svg style={{ position: "absolute", top: 22, right: 24, opacity: 0.32 }}
               width="44" height="44" viewBox="0 0 24 24" aria-hidden="true">
            <path fill={ST.gold} d="M12 2 L13.5 10.5 L22 12 L13.5 13.5 L12 22 L10.5 13.5 L2 12 L10.5 10.5 Z"/>
          </svg>

          <div className="apex-cta-head">
            <p style={{ margin: 0, fontFamily: ST.fontSans, fontSize: 13, fontWeight: 700,
                        textTransform: "uppercase", letterSpacing: "0.30em", color: ST.gold }}>
              Ready when you are
            </p>
            <PrimaryButton onClick={onQuote} style={{
              background: "#fff", color: ST.burgundy,
              boxShadow: "0 14px 34px rgba(0,0,0,0.22)",
              fontSize: 14, padding: "14px 20px", minHeight: 52,
            }}>
              {label}
              <Icons.ArrowRight size={16} />
            </PrimaryButton>
          </div>

          <h3 className="apex-h2" style={{ margin: "20px 0 0", fontFamily: ST.fontSerif, fontWeight: 400,
                                            lineHeight: 1.08, letterSpacing: "0.01em", color: "#fff" }}>
            Move-out clean, deep reset, or recurring — quoted in sixty seconds.
          </h3>
          <hr style={{ width: 60, height: 1, background: ST.gold, border: 0, margin: "16px 0 0" }} />
          <p style={{ margin: "16px 0 0", fontFamily: ST.fontSans, fontSize: 14, lineHeight: 1.6,
                      color: "rgba(255,255,255,0.78)" }}>
            Tell us the property, deadline, and condition. We'll send a focused scope and timing — no checkout, no call required.
          </p>
        </div>
      </div>
    </section>
  );
}

// ============ FOOTER ============
function Footer() {
  return (
    <footer style={{ borderTop: `1px solid ${ST.border}`, background: ST.mist, color: ST.charcoal }}>
      <div className="apex-footer">
        <div className="apex-footer-mast">
          <div style={{ display: "flex", alignItems: "baseline", gap: 12 }}>
            <span style={{ fontFamily: ST.fontSerif, fontSize: 30, letterSpacing: "0.18em", color: ST.burgundy, lineHeight: 1 }}>APEX</span>
            <span style={{ width: 10, height: 1, background: ST.gold, transform: "translateY(-7px)" }} />
            <span style={{ fontFamily: ST.fontSans, fontSize: 10, fontWeight: 600, letterSpacing: "0.30em", textTransform: "uppercase", color: "rgba(31,29,29,0.65)", transform: "translateY(-3px)" }}>
              Cleaning Solutions
            </span>
          </div>
          <PrimaryButton href="#quote-cta">
            Get a 60-second Quote <Icons.ArrowRight size={16}/>
          </PrimaryButton>
        </div>

        <div className="apex-footer-cols">
          <FooterCol h="Services" links={[["Move-Out Cleaning","#"],["Deep Cleaning","#"],["Apartment Turnover","#"],["Recurring Cleaning","#"]]} />
          <FooterCol h="Company"  links={[["About","#about"],["Reviews","#reviews"],["FAQ","#faq"]]} />
          <FooterCol h="Contact"  links={[["Support@apexcleaningfw.com","mailto:support@apexcleaningfw.com"], ["(260) 254-7999","tel:+12602547999"], ["Fort Wayne and surrounding areas",""]]} muted/>
        </div>

        <p style={{ margin: "32px 0 0", textAlign: "center", fontFamily: ST.fontSans, fontSize: 12, color: "rgba(31,29,29,0.55)" }}>
          © {new Date().getFullYear()} Apex Cleaning Solutions · Brand Guidelines v2.0
        </p>
      </div>
    </footer>
  );
}

function FooterCol({ h, links, muted }) {
  return (
    <div>
      <h3 style={{ margin: "0 0 14px", fontFamily: ST.fontSans, fontSize: 11, fontWeight: 700,
                   textTransform: "uppercase", letterSpacing: "0.24em", color: ST.burgundy }}>{h}</h3>
      <ul style={{ margin: 0, padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 7 }}>
        {links.map(([label, href]) => (
          <li key={label}>
            {href ? <a href={href} style={{ fontFamily: ST.fontSans, fontSize: 13, color: "rgba(31,29,29,0.7)", textDecoration: "none" }}>{label}</a>
                  : <span style={{ fontFamily: ST.fontSans, fontSize: 13, color: muted ? "rgba(31,29,29,0.7)" : ST.charcoal }}>{label}</span>}
          </li>
        ))}
      </ul>
    </div>
  );
}

// ============ STICKY MOBILE CTA ============
function StickyMobileCTA({ onQuote }) {
  return (
    <div className="apex-sticky-cta">
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, padding: 12 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <p style={{ margin: 0, fontFamily: ST.fontSans, fontSize: 10, fontWeight: 700,
                      textTransform: "uppercase", letterSpacing: "0.24em", color: ST.burgundyAccent }}>
            Quoted in 60 seconds
          </p>
          <p style={{ margin: "2px 0 0", fontFamily: ST.fontSerif, fontWeight: 400, fontSize: 16,
                      lineHeight: 1.1, letterSpacing: "0.01em", color: ST.burgundy }}>
            Move-out, deep, or recurring.
          </p>
        </div>
        <PrimaryButton onClick={onQuote} style={{
          fontSize: 13, padding: "12px 16px", minHeight: 48,
          textTransform: "uppercase", letterSpacing: "0.14em",
        }}>
          Quote
          <Icons.ArrowRight size={14} />
        </PrimaryButton>
      </div>
    </div>
  );
}

Object.assign(window, { AboutUs, GoogleReviews, FAQ, QuoteCTA, Footer, StickyMobileCTA });
