// Hero — mobile-first, CTA-prioritized.
// Layout order on mobile: trust chip → H1 → quick-promise sub → BIG CTA → reassurance row → photo.
// Layout on tablet+: two columns with photo collage on the right.

const HT = window.Tokens;

function Hero({ onQuote, headline, ctaLabel, showReviews = true }) {
  const HEADLINE = headline || "Fort Wayne home cleaning, quoted in sixty seconds.";
  // Split headline on a comma so the accent half can be colored.
  const commaIdx = HEADLINE.indexOf(",");
  const head1 = commaIdx >= 0 ? HEADLINE.slice(0, commaIdx + 1) : HEADLINE;
  const head2 = commaIdx >= 0 ? HEADLINE.slice(commaIdx + 1).trim() : "";
  return (
    <section style={{
      position: "relative",
      color: HT.charcoal,
      overflow: "hidden",
    }}>
      {/* Hero photograph — client-provided, full background, opaque, right-aligned, subtle fade-in */}
      <div style={{ position: "absolute", inset: 0, zIndex: 0, overflow: "hidden",
                    opacity: 0, animation: "apex-fade-in 2.4s ease-out 0.6s both" }}>
        <img src="/assets/hero-cleaner-photo.jpg"
          alt="Apex Cleaning Solutions team member in a warm Fort Wayne home."
          width="2400" height="1350"
          fetchpriority="high" loading="eager" decoding="async"
          style={{ width: "100%", height: "100%", objectFit: "cover",
                   objectPosition: "70% center" }} />
      </div>
      {/* Ivory fade from the left so the headline stays readable
          while the cleaner on the right side shows through clearly. */}
      <div style={{
        position: "absolute", inset: 0, zIndex: 1,
        background: "linear-gradient(90deg, rgba(248,245,238,0.96) 0%, rgba(248,245,238,0.82) 28%, rgba(248,245,238,0.40) 54%, rgba(248,245,238,0.05) 100%)",
      }} />

      <div className="apex-hero-grid" style={{ position: "relative", zIndex: 2 }}>
        <div className="apex-hero-text">
          <h1 className="apex-h1" style={{
            margin: 0,
            fontFamily: HT.fontSerif, fontWeight: 400,
            lineHeight: 0.98, letterSpacing: "0.01em",
            color: HT.burgundy,
          }}>
            {head1}{head2 && " "}
            {head2 && <span style={{ color: HT.burgundyAccent }}>{head2}</span>}
          </h1>
          <hr style={{ width: 64, height: 1, background: HT.gold, border: 0, margin: "18px 0 0" }} />

          {/* PRIMARY CTA — quote form is the lead capture. */}
          <div className="apex-cta-stack" style={{ marginTop: 22 }}>
            <BigQuoteButton onClick={onQuote} label={ctaLabel} />
          </div>

          {/* SECONDARY CTA — phone fallback for visitors not ready to fill a form. */}
          <div style={{ marginTop: 12 }}>
            <BigQuoteButton
              href="tel:+12602547999"
              label="Call Us! 260-254-7999"
              showArrow={false}
              variant="secondary"
              ariaLabel="Call Apex Cleaning at 260-254-7999"
            />
          </div>

          {/* Compact Google reviews widget */}
          {showReviews && <HeroGoogleReviews />}
        </div>

        {/* Right column intentionally empty — the hero background image
            anchors the cleaner subject on the right side of the frame. */}
      </div>
    </section>
  );
}

function ReassurePoint({ children }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={window.Tokens.gold}
           strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
        <polyline points="20 6 9 17 4 12"/>
      </svg>
      {children}
    </span>
  );
}

// Compact Google reviews widget — sits inside the hero text column.
// Hydrates from window.APEX_GOOGLE_REVIEWS* globals seeded by index.html.
// Re-reads on the "apex:integrations-updated" event so backend overrides take effect.
function HeroGoogleReviews() {
  const T = window.Tokens;

  const read = () => ({
    summary: window.APEX_GOOGLE_REVIEWS_SUMMARY || null,
    sourceUrl: window.APEX_GOOGLE_REVIEWS_SOURCE_URL || "",
    reviews: Array.isArray(window.APEX_GOOGLE_REVIEWS) ? window.APEX_GOOGLE_REVIEWS : [],
  });
  const [{ summary, reviews }, setData] = React.useState(read);
  React.useEffect(() => {
    const sync = () => setData(read());
    sync();
    window.addEventListener("apex:integrations-updated", sync);
    return () => window.removeEventListener("apex:integrations-updated", sync);
  }, []);

  const hasSummary = !!(summary && Number(summary.count) > 0 && Number(summary.rating) > 0);
  const ratingNum = hasSummary ? Number(summary.rating) : 5;
  const ratingText = ratingNum.toFixed(1);
  const count = hasSummary ? Number(summary.count) : null;
  const snippet = reviews[0] && (reviews[0].text || reviews[0].body || reviews[0].snippet);

  return (
    <a href="https://www.google.com/maps/place/?q=place_id:ChIJezH5hIxMRioROwHnb6NpHZg" target="_blank" rel="noopener noreferrer"
      id="hero-google-embed"
      data-embed="google-places-compact"
      aria-label={count
        ? `Read all ${count} verified Google reviews`
        : "Read verified Google reviews"}
      style={{
        display: "block", marginTop: 22, maxWidth: 440,
        background: "rgba(255,255,255,0.85)",
        border: `1px solid ${T.border}`,
        borderRadius: 18,
        padding: 16,
        backdropFilter: "blur(8px)",
        boxShadow: "0 8px 24px rgba(91,22,25,0.10)",
        textDecoration: "none", color: "inherit",
      }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0, flexWrap: "wrap" }}>
          <svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true" style={{ flex: "none" }}>
            <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>
          <span style={{ fontFamily: T.fontSans, fontSize: 13, fontWeight: 700, color: T.charcoal }}>
            Google Reviews
          </span>
          <span style={{ display: "inline-flex", gap: 1, color: T.gold, flex: "none" }} aria-hidden="true">
            {Array.from({ length: 5 }).map((_, i) => (
              <svg key={i} width="13" height="13" viewBox="0 0 24 24" fill="currentColor">
                <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>
          <span style={{ fontFamily: T.fontSans, fontSize: 12, fontWeight: 700, color: T.burgundy }}>
            {ratingText}{count ? ` (${count})` : ""}
          </span>
        </div>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={T.burgundyAccent}
             strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" style={{ flex: "none" }}
             aria-hidden="true">
          <path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>
        </svg>
      </div>

      <p style={{ margin: "12px 0 0", fontFamily: T.fontSerif, fontWeight: 400,
                  fontSize: 16, lineHeight: 1.4, letterSpacing: "0.01em", color: T.charcoal }}>
        {count
          ? `Trusted by ${count}+ Fort Wayne homeowners — every review independently verified by Google.`
          : "Trusted by Fort Wayne homeowners — every review independently verified by Google."}
      </p>

      {snippet && (
        <p style={{ margin: "10px 0 0", fontFamily: T.fontSerif, fontStyle: "italic",
                    fontSize: 14, lineHeight: 1.45,
                    color: "rgba(31,29,29,0.78)",
                    borderLeft: `2px solid ${T.gold}`, paddingLeft: 10 }}>
          “{String(snippet).slice(0, 140)}{String(snippet).length > 140 ? "…" : ""}”
        </p>
      )}

      <p style={{ margin: "10px 0 0", fontFamily: T.fontMono, fontSize: 10.5,
                  textTransform: "uppercase", letterSpacing: "0.18em",
                  color: "rgba(31,29,29,0.55)" }}>
        Read all reviews →
      </p>
    </a>
  );
}

// The big, animated, psychology-tuned primary CTA.
// Larger than any other element, gold-rule micro-animation, arrow tail elongates.
function BigQuoteButton({ onClick, href, label, showArrow = true, variant = "primary", ariaLabel }) {
  const [hover, setHover] = React.useState(false);
  const T = window.Tokens;
  const text = label || "Get a 60-second Quote";
  const secondary = variant === "secondary";

  const bg = secondary ? (hover ? T.burgundy : "transparent")
                       : (hover ? T.burgundyAccent : T.burgundy);
  const fg = secondary && !hover ? T.burgundy : "#fff";
  const shadow = secondary
    ? (hover ? "0 14px 32px rgba(91,22,25,0.22)" : "0 4px 14px rgba(91,22,25,0.08)")
    : (hover ? "0 22px 50px rgba(91,22,25,0.40)" : "0 16px 36px rgba(91,22,25,0.30)");

  const style = {
    all: "unset", cursor: "pointer", position: "relative",
    display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 14,
    width: "100%", maxWidth: 420,
    background: bg,
    color: fg,
    fontFamily: T.fontSans, fontWeight: 700, fontSize: 16,
    textTransform: "uppercase", letterSpacing: "0.18em",
    padding: "20px 24px", minHeight: 62,
    borderRadius: 10,
    border: secondary ? `2px solid ${T.burgundy}` : "none",
    boxShadow: shadow,
    transform: hover ? "translateY(-1px)" : "translateY(0)",
    transition: "background 240ms, color 240ms, box-shadow 280ms, transform 220ms",
    boxSizing: "border-box", overflow: "hidden",
    textDecoration: "none", textAlign: "center",
  };

  const children = (
    <React.Fragment>
      <span>{text}</span>
      {showArrow && (
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
          <span style={{
            width: hover ? 26 : 18, height: 1.6, background: fg, borderRadius: 1,
            transition: "width 240ms cubic-bezier(.16,1,.3,1)",
          }} />
          <svg width="12" height="14" viewBox="0 0 12 14" fill="none" stroke="currentColor"
               strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <path d="m4 3 5 4-5 4"/>
          </svg>
        </span>
      )}
      {/* Animated gold underline */}
      <span aria-hidden="true" style={{
        position: "absolute", left: 18, right: 18, bottom: 10, height: 1,
        background: T.gold,
        transformOrigin: "left center",
        transform: hover ? "scaleX(1)" : "scaleX(0.18)",
        transition: "transform 360ms cubic-bezier(.16,1,.3,1)",
      }}/>
    </React.Fragment>
  );

  const commonProps = {
    onMouseEnter: () => setHover(true),
    onMouseLeave: () => setHover(false),
    style,
    "aria-label": ariaLabel,
  };

  return href
    ? <a href={href} {...commonProps}>{children}</a>
    : <button onClick={onClick} {...commonProps}>{children}</button>;
}


window.Hero = Hero;
