/* global React */
/* Home page — split hero matching the reference screenshot, then tiles. */

function Home({ navigate }) {
  // Hero collage rotates through 3 agents at a time, swapping every 10s
  // so every owner gets surfaced over the course of a session.
  const pool = React.useMemo(() => (window.AGENTS_DATA || []).filter((a) => a.photo), []);
  const pickTrio = React.useCallback((avoid = []) => {
    if (pool.length === 0) return [];
    const avoidSet = new Set(avoid.map((a) => a?.name));
    const fresh = pool.filter((a) => !avoidSet.has(a.name));
    const source = fresh.length >= 3 ? fresh : pool;
    return [...source].sort(() => Math.random() - 0.5).slice(0, 3);
  }, [pool]);

  const [heroAgents, setHeroAgents] = React.useState(() => pickTrio());
  const [tick, setTick] = React.useState(0);

  React.useEffect(() => {
    const id = setInterval(() => {
      setHeroAgents((prev) => pickTrio(prev));
      setTick((t) => t + 1);
    }, 10000);
    return () => clearInterval(id);
  }, [pickTrio]);

  const [a1, a2, a3] = heroAgents;

  return (
    <div className="page">
      {/* Split hero */}
      <section className="hero">
        <div className="hero-grid">
          <div>
            <h1 className="hero-h1">The freedom of business ownership. The support of a proven system.</h1>
            <p className="hero-sub">Start your business in DFW with training, mentorship, and a district focused on helping entrepreneurs grow long term.



            </p>
            <div className="hero-ctas">
              <a href="#/opportunities" className="btn-pill-dark" onClick={(e) => {e.preventDefault();navigate("opportunities");}}>Explore the Opportunites

              </a>
              <a href="#/about" className="btn-pill-outline" onClick={(e) => {e.preventDefault();navigate("about");}}>District 52

              </a>
            </div>
          </div>

          <div className="collage">
            {/* Decorative dotted ring connecting the cards */}
            <svg viewBox="0 0 500 520" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", pointerEvents: "none" }} aria-hidden="true">
              <path d="M 120 180 Q 60 320 220 420" stroke="rgba(0,0,0,0.12)" strokeWidth="1.5" strokeDasharray="3 5" fill="none" />
              <path d="M 340 90 Q 460 180 380 340" stroke="rgba(0,0,0,0.10)" strokeWidth="1.5" strokeDasharray="3 5" fill="none" />
            </svg>

            {/* Card 1 — top left */}
            {a1 &&
            <div
              key={`a1-${tick}`}
              className="portrait-card portrait-card-shuffle"
              style={{ left: 0, top: 60, width: 200, height: 240, animationDelay: "0ms" }}>
              
                <img src={a1.photo} alt={a1.name} />
                <div className="portrait-meta">
                  {a1.name}
                  <span className="sub">{a1.city}</span>
                </div>
              </div>
            }

            {/* Card 2 — top right */}
            {a2 &&
            <div
              key={`a2-${tick}`}
              className="portrait-card portrait-card-shuffle portrait-card-shuffle--right"
              style={{ right: 0, top: 0, width: 240, height: 300, animationDelay: "140ms" }}>
              
                <img src={a2.photo} alt={a2.name} />
                <div className="portrait-meta">
                  {a2.name}
                  <span className="sub">{a2.city}</span>
                </div>
              </div>
            }

            {/* Card 3 — bottom center */}
            {a3 &&
            <div
              key={`a3-${tick}`}
              className="portrait-card portrait-card-shuffle portrait-card-shuffle--bottom"
              style={{ left: 90, bottom: 0, width: 220, height: 200, animationDelay: "280ms" }}>
              
                <img src={a3.photo} alt={a3.name} />
                <div className="portrait-meta">
                  {a3.name}
                  <span className="sub">{a3.city}</span>
                </div>
              </div>
            }

            {/* Floating cards mirroring the screenshot's tags */}

            </div>
        </div>
      </section>

      {/* Trust strip — auto-scrolling marquee of all 43 agencies */}
      <section className="trust-strip">
        <h2 className="trust-strip-title">TRUSTED BY 44 AGENCIES ACROSS THE METROPLEX</h2>
        <TrustMarquee />
      </section>

      {/* Feature cards (3-up) — mirroring the screenshot's lower row */}
      <section className="section">
        <div style={{ textAlign: "center", marginBottom: 56 }}>
          <div className="eyebrow" style={{ marginBottom: 14 }}>The Future Agent Program</div>
          <h2 style={{ font: "600 56px/1.07 var(--font-display)", letterSpacing: "-0.6px", margin: "0 0 16px", textWrap: "balance" }}>Everything you need to build a business without building it alone.

          </h2>
          <p style={{ font: "var(--type-lead-airy)", letterSpacing: "var(--type-lead-airy-ls)", color: "var(--color-ink-muted-80)", margin: 0, maxWidth: 640, marginLeft: "auto", marginRight: "auto" }}>Build your future with the backing of experienced leaders, proven systems, and a team invested in your success.


          </p>
        </div>

        <div className="feature-cards">
          <div className="feature-card">
            <div className="ico">
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3" y="4" width="18" height="18" rx="2"></rect>
                <line x1="16" y1="2" x2="16" y2="6"></line>
                <line x1="8" y1="2" x2="8" y2="6"></line>
                <line x1="3" y1="10" x2="21" y2="10"></line>
              </svg>
            </div>
            <h3>8-week training.</h3>
            <p>Classroom in Dallas Thursdays - Friday. Weekly Zoom calls. Your own desk from week one.</p>
            <a className="arrow" href="#/opportunities" onClick={(e) => {e.preventDefault();navigate("opportunities");}}>
              See the curriculum
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>
            </a>
          </div>

          <div className="feature-card">
            <div className="ico">
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
                <circle cx="9" cy="7" r="4"></circle>
                <path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
                <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
              </svg>
            </div>
            <h3>1:1 Training</h3>
            <p>Work with one of our existing agents or district staff members</p>
            <a className="arrow" href="#/agents" onClick={(e) => {e.preventDefault();navigate("agents");}}>
              Meet the agents
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>
            </a>
          </div>

          <div className="feature-card">
            <div className="ico">
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <line x1="12" y1="1" x2="12" y2="23"></line>
                <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"></path>
              </svg>
            </div>
            <h3>Residual Income</h3>
            <p>Insurance is one of the few industries where the work you do today can continue paying you for years to come. Instead of starting at zero every month, you build a book of business that creates long-term residual income and ownership.</p>
            <a className="arrow" href="#/contact" onClick={(e) => {e.preventDefault();navigate("contact");}}>
              Talk to a recruiter
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>
            </a>
          </div>
        </div>
      </section>

      {/* Dark stat band */}
      <section className="stat-band">
        <div className="stat-band-inner">
          <div className="eyebrow" style={{ color: "var(--color-body-muted)", marginBottom: 18 }}>By the numbers</div>
          <h2>District 52</h2>
          <p>District 52 has placed new agents in DFW since 1989. 



          </p>
          <div className="stat-grid">
            <div><span className="stat-num">342</span><span className="stat-label">Topper Club Winners (Top 10% of agencies within the company)</span></div>
            <div><span className="stat-num">101</span><span className="stat-label">President's Council Winners (Top 1% of agencies within the company)</span></div>
            <div><span className="stat-num">12</span><span className="stat-label">District Managers produced from our District office (Most in the company)</span></div>
            <div><span className="stat-num">1:1</span><span className="stat-label">Mentorship by district and some of the top agents within the company</span></div>
          </div>
        </div>
      </section>

      {/* Google reviews — rotating 5-star testimonials */}
      <ReviewsCarousel />

      {/* CTA */}
      <section className="cta-tile">
        <h2>Apply to the Best Small Business Opportunity in America.</h2>
        <p></p>
        <div style={{ display: "inline-flex", gap: 12 }}>
          <a href="#/opportunities" className="btn-pill-dark" onClick={(e) => {e.preventDefault();navigate("opportunities");}}>Start an application</a>
          <a href="#/contact" className="btn-pill-outline" onClick={(e) => {e.preventDefault();navigate("contact");}}>Schedule a call</a>
        </div>
      </section>
    </div>);

}

window.Home = Home;

/* ============================================================
   TrustMarquee — infinitely scrolling horizontal list of agencies.
   Hover/focus pauses, prefers-reduced-motion freezes it.
   ============================================================ */
const TRUST_AGENCIES = (window.AGENTS_DATA || []).map((a) => a.agency);


function TrustMarquee() {
  return (
    <div className="marquee" aria-label="District 52 agencies">
      <div className="marquee-track">
        {[0, 1].map((copy) =>
        <div className="marquee-group" key={copy} aria-hidden={copy === 1 ? "true" : undefined}>
            {TRUST_AGENCIES.map((name, i) =>
          <React.Fragment key={i}>
                <span className="marquee-item">{name}</span>
                <span className="marquee-dot" aria-hidden="true">·</span>
              </React.Fragment>
          )}
          </div>
        )}
      </div>
    </div>);

}

/* ============================================================
   ReviewsCarousel — rotating 5-star Google reviews. Auto-advances
   every 10s; pauses on hover; dots + arrows for manual control.
   ============================================================ */
const GOOGLE_REVIEWS_URL = "https://share.google/MZiB1z0FUt9eq8dne";

const D52_REVIEWS = [
  { name: "Joy Pike", meta: "Local Guide · 63 reviews", text: "Gary and his team are the absolute best! Pretty sure there isn't enough space for me to list all the positives in this review. Caring, supportive and knowledgeable are at the top. Could not ask for better leadership. Special shout out to Collin and Amy for all of their hard work!" },
  { name: "Dean Hansen", meta: "Local Guide · 98 reviews", text: "While talking with Farmers agents all across the country, we discuss the support we get from our District offices. Some are good, some are better, and only one is District 52 with Gary, Brenda, Amy, Collin, Antonio, and Tosca! We are so blessed to have their guidance, support, and encouragement which is second to none. We love District 52!" },
  { name: "Sabrina Hosein", meta: "4 reviews", text: "Excellent service and a knowledgeable team. They are always helpful, patient and responsive. They are honest, attentive, and focused on finding the best solutions — not just selling policies. It's comforting to know you can count on a team that values relationships and long-term trust." },
  { name: "Brian Berridge", meta: "4 reviews", text: "Gary Edmonds and his staff are 1 of 1! Not enough good things can be said about Gary and the way that he conducts not only his business but himself, and it carries over to his staff." },
  { name: "Tyler Wimpee", meta: "5 reviews", text: "Best district office with Farmers Insurance. Their staff is very helpful in every way possible." },
  { name: "Lorraine Rodriguez", meta: "1 review", text: "Unbeatable service from the best Farmers district office around — and their team is world-class!" },
  { name: "Lori Hernandez", meta: "Local Guide · 28 reviews", text: "Amazing district manager! Gary and his staff go above and beyond to help my agency succeed! Thank you!" },
];

function Stars({ rating = 5 }) {
  const pct = Math.max(0, Math.min(100, (rating / 5) * 100));
  const gid = "rvgrad-" + String(rating).replace(".", "_");
  return (
    <div className="rv-stars" aria-label={rating + " out of 5 stars"}>
      <svg width="0" height="0" style={{ position: "absolute" }} aria-hidden="true">
        <defs>
          <linearGradient id={gid}>
            <stop offset={pct + "%"} stopColor="#fbbc04" />
            <stop offset={pct + "%"} stopColor="#e0e0e0" />
          </linearGradient>
        </defs>
      </svg>
      {[0, 1, 2, 3, 4].map((i) => {
        const full = i < Math.floor(pct / 20);
        const isPartial = !full && i === Math.floor(pct / 20) && pct % 20 !== 0;
        return (
          <svg key={i} viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"
            fill={full ? "#fbbc04" : isPartial ? `url(#${gid})` : "#e0e0e0"}>
            <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26" />
          </svg>
        );
      })}
    </div>
  );
}

function ReviewsCarousel() {
  const { useState, useEffect, useRef } = React;
  const [i, setI] = useState(0);
  const paused = useRef(false);
  const n = D52_REVIEWS.length;

  useEffect(() => {
    const id = setInterval(() => {
      if (!paused.current) setI((v) => (v + 1) % n);
    }, 10000);
    return () => clearInterval(id);
  }, [n]);

  const go = (d) => setI((v) => (v + d + n) % n);
  const r = D52_REVIEWS[i];

  return (
    <section
      className="reviews"
      onMouseEnter={() => { paused.current = true; }}
      onMouseLeave={() => { paused.current = false; }}
    >
      <div className="reviews-inner">
        <div className="reviews-head">
          <div className="reviews-google">
            <svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true"><path fill="#4285F4" d="M23 12.27c0-.85-.07-1.66-.21-2.45H12v4.62h6.18c-.27 1.42-1.08 2.62-2.3 3.43v2.85h3.72c2.18-2 3.4-4.95 3.4-8.45z"/><path fill="#34A853" d="M12 23c3.11 0 5.71-1.03 7.61-2.78l-3.72-2.85c-1.03.69-2.35 1.1-3.89 1.1-2.99 0-5.52-2.02-6.43-4.73H1.74v2.94A11.99 11.99 0 0 0 12 23z"/><path fill="#FBBC05" d="M5.57 13.74A7.18 7.18 0 0 1 5.17 12c0-.6.1-1.19.27-1.74V7.32H1.74A11.99 11.99 0 0 0 0 12c0 1.94.46 3.76 1.28 5.36l4.29-3.62z"/><path fill="#EA4335" d="M12 4.75c1.69 0 3.2.58 4.4 1.72l3.3-3.3C17.71 1.19 15.11 0 12 0 7.31 0 3.25 2.69 1.28 6.64l4.29 3.62C6.48 7.55 9.01 4.75 12 4.75z"/></svg>
            <span>Google Reviews</span>
          </div>
          <div className="reviews-rating">
            <strong>4.9</strong>
            <Stars rating={4.9} />
          </div>
        </div>

        <div className="reviews-stage">
          <button className="reviews-arrow" aria-label="Previous review" onClick={() => go(-1)}>
            <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"></polyline></svg>
          </button>

          <blockquote key={i} className="reviews-card">
            <Stars />
            <p className="reviews-text">"{r.text}"</p>
            <div className="reviews-author">
              <span className="reviews-avatar" aria-hidden="true">{r.name.split(" ").map((w) => w[0]).slice(0, 2).join("")}</span>
              <span>
                <span className="reviews-name">{r.name}</span>
                <span className="reviews-meta">{r.meta}</span>
              </span>
            </div>
          </blockquote>

          <button className="reviews-arrow" aria-label="Next review" onClick={() => go(1)}>
            <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"></polyline></svg>
          </button>
        </div>

        <div className="reviews-dots">
          {D52_REVIEWS.map((_, d) => (
            <button key={d} className={"reviews-dot" + (d === i ? " on" : "")} aria-label={"Review " + (d + 1)} onClick={() => setI(d)} />
          ))}
        </div>

        <a className="reviews-cta" href={GOOGLE_REVIEWS_URL} target="_blank" rel="noopener noreferrer">
          Read all reviews on Google
          <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>
        </a>
      </div>
    </section>);

}
