/* global React */
const { useState, useEffect, useRef } = React;

// ─────────────────────────────────────────────
// Logo — real PNG provided by client (white / black / green variants)
// Native aspect ratio ≈ 2675×709 (~3.77:1).
// ─────────────────────────────────────────────
function TGLogo({ height = 26, variant = "white" }) {
  const src =
    variant === "green" ? "assets/logo-green.png" :
    variant === "black" ? "assets/logo-black.png" :
    "assets/logo-white.png";
  return (
    <img
      src={src}
      alt="TRENDINGOLF"
      style={{ display: "block", height: `${height}px`, width: "auto" }}
    />
  );
}

// ─────────────────────────────────────────────
// Hero
// ─────────────────────────────────────────────
function Hero({ tweaks }) {
  const variant = tweaks.heroVariant; // image | split | card
  const cta = tweaks.ctaCopy;

  // Hero slideshow — rotates through 9 photos with a 6s interval and a soft
  // crossfade. Disabled if the user picks a specific photo from Tweaks.
  const HERO_SLIDESHOW = [
    "assets/hero/hero-sunset-swing.jpg",
    "assets/hero/hero-fairway-swing.jpg",
    "assets/hero/hero-bunker-spray.jpg",
    "assets/hero/hero-tee-clouds.jpg",
    "assets/hero/hero-red-swing.jpg",
    "assets/hero/hero-green-flag.jpg",
    "assets/hero/hero-putt-line.jpg",
    "assets/hero/hero-bunker-side.jpg",
    "assets/hero/hero-cheers.jpg",
  ];
  const HERO_PINNED = {
    sunset:   "assets/hero/hero-sunset-swing.jpg",
    fairway:  "assets/hero/hero-fairway-swing.jpg",
    original: "https://images.unsplash.com/photo-1535132011086-b8818f016104?auto=format&fit=crop&w=2000&q=80",
  };
  const isSlideshow = tweaks.heroImage === "slideshow";
  const [slideIdx, setSlideIdx] = useState(0);
  useEffect(() => {
    if (!isSlideshow) return;
    // Preload all images so the crossfade is smooth.
    HERO_SLIDESHOW.forEach((src) => { const img = new Image(); img.src = src; });
    const id = setInterval(() => {
      setSlideIdx((i) => (i + 1) % HERO_SLIDESHOW.length);
    }, 8000);
    return () => clearInterval(id);
  }, [isSlideshow]);
  const accentBgImage = isSlideshow
    ? HERO_SLIDESHOW[slideIdx]
    : (HERO_PINNED[tweaks.heroImage] || HERO_PINNED.sunset);

  const headlineByVariant = {
    image: (
      <>
        EL CIRCUITO QUE MUEVE TU <span className="green">JUEGO</span>
      </>
    ),
    split: (
      <>
        FIXTURE.<br/>
        RANKING.<br/>
        <span className="green">RESERVAS.</span>
      </>
    ),
    card: (
      <>
        ENTRA EN <span className="green">CANCHA</span>
      </>
    ),
  };

  // Renders the hero background. In slideshow mode, all images are stacked and
  // we fade between them by toggling the active class. In pinned mode it's a
  // single static layer.
  const HeroBg = ({ opacity = 1 }) => {
    if (isSlideshow) {
      return (
        <div className="hero__bg-stack" style={{ opacity }}>
          {HERO_SLIDESHOW.map((src, i) => (
            <div
              key={src}
              className={`hero__bg-slide ${i === slideIdx ? "is-active" : ""}`}
              style={{ backgroundImage: `url('${src}')` }}
              aria-hidden="true"
            />
          ))}
        </div>
      );
    }
    return (
      <div
        className="hero__bg"
        style={{ backgroundImage: `url('${accentBgImage}')`, opacity }}
      />
    );
  };

  return (
    <section className={`hero hero--${variant}`} id="top">
      {variant === "image" && (
        <>
          <HeroBg />
          <div className="hero__scanlines" />
        </>
      )}
      {variant === "split" && <div className="hero__scanlines" />}
      {variant === "card" && (
        <>
          <HeroBg opacity={0.55} />
          <div className="hero__scanlines" />
        </>
      )}

      <div className="wrap hero__content">
        {variant === "card" ? (
          <div className="hero__inner">
            <div>
              <div className="hero__eyebrow">TEMPORADA 2026 · AMBA</div>
              <h1 className="hero__headline">{headlineByVariant.card}</h1>
              <p className="hero__sub">
                Torneos semanales en los mejores clubes de Buenos Aires. Inscribite, jugá, sumá puntos para el ranking.
              </p>
              <div className="hero__ctas">
                <a className="btn btn--primary" href="https://www.adondejugamos.com/ad/reservasconsulta.php?tab=770" target="_blank" rel="noopener">
                  {cta} <span className="arrow">→</span>
                </a>
                <a className="btn btn--ghost" href="#fixture">VER FIXTURE</a>
              </div>
            </div>
            <FeaturedFixture />
          </div>
        ) : (
          <>
            <div className="hero__eyebrow">TEMPORADA 2026 · AMBA</div>
            <h1 className="hero__headline">{headlineByVariant[variant]}</h1>
            <p className="hero__sub">
              El circuito de torneos amateurs que recorre los mejores clubes del AMBA. Fixture semanal, resultados en vivo y próximamente rankings.
            </p>
            <div className="hero__ctas">
              <a className="btn btn--primary" href="https://www.adondejugamos.com/ad/reservasconsulta.php?tab=770" target="_blank" rel="noopener">
                {cta} <span className="arrow">→</span>
              </a>
              <a className="btn btn--ghost" href="#fixture">VER FIXTURE</a>
            </div>
          </>
        )}
      </div>

      <div className="hero__meta">
        <span className="dot" />
        <span>SEÑAL EN VIVO · TG.LIVE</span>
      </div>
    </section>
  );
}

function FeaturedFixture() {
  const [next, setNext] = useState(null);
  useEffect(() => {
    const handler = (e) => setNext(e.detail);
    window.addEventListener("tg:next-fixture", handler);
    return () => window.removeEventListener("tg:next-fixture", handler);
  }, []);
  if (!next) {
    return (
      <div className="hero__featured">
        <div className="hero__featured-label">PRÓXIMA FECHA</div>
        <div className="hero__featured-date">
          <span className="day">··</span>
          <span className="month">CARGANDO</span>
        </div>
        <div className="hero__featured-name">SINCRONIZANDO FIXTURE</div>
        <div className="hero__featured-meta">Conectando con golf.trendingolf.com…</div>
      </div>
    );
  }
  return (
    <div className="hero__featured">
      <div className="hero__featured-label">▶ PRÓXIMA FECHA</div>
      <div className="hero__featured-date">
        <span className="day">{String(next.day).padStart(2, "0")}</span>
        <span className="month">{next.monthShort}</span>
      </div>
      <div className="hero__featured-name">{next.club}</div>
      <div className="hero__featured-meta">{next.dow} · {next.price}</div>
      <a className="btn btn--primary btn--sm" href="https://www.adondejugamos.com/ad/reservasconsulta.php?tab=770" target="_blank" rel="noopener">
        RESERVAR <span className="arrow">→</span>
      </a>
    </div>
  );
}

// ─────────────────────────────────────────────
// Fixture — pulls from adondejugamos via fetcher
// ─────────────────────────────────────────────
function Fixture({ tweaks }) {
  // Try cache first → instant render on repeat visits.
  const cached = (window.TGFixtures && window.TGFixtures.loadCached()) || null;
  const today = new Date(); today.setHours(0,0,0,0);
  const initialCached = cached ? cached.filter(f => f.date >= today) : [];
  const [fixtures, setFixtures] = useState(initialCached);
  const [status, setStatus] = useState(initialCached.length ? "ok" : "loading"); // loading | ok | error | empty
  const [lastSync, setLastSync] = useState(null);

  useEffect(() => {
    let cancelled = false;
    async function load() {
      try {
        if (!fixtures.length) setStatus("loading");
        const data = await window.TGFixtures.load();
        if (cancelled) return;
        if (!data || data.length === 0) {
          if (!fixtures.length) { setStatus("empty"); setFixtures([]); }
          return;
        }
        setFixtures(data);
        setStatus("ok");
        setLastSync(new Date());
        // Emit next fixture for hero featured card
        window.dispatchEvent(new CustomEvent("tg:next-fixture", { detail: data[0] }));
      } catch (e) {
        console.error("Fixture load error", e);
        if (!cancelled && !fixtures.length) setStatus("error");
      }
    }
    load();
    const id = setInterval(load, 60 * 60 * 1000); // hourly
    return () => { cancelled = true; clearInterval(id); };
  }, []);

  const layoutClass = `fixture--${tweaks.fixtureLayout}`; // carousel | grid | list

  const tickerItems = fixtures.slice(0, 8).map((f) => `${f.dow.slice(0,3)} ${String(f.day).padStart(2,"0")}/${f.monthShort} · ${f.club}`);

  return (
    <section className={`fixture section ${layoutClass}`} id="fixture">
      {/* Marquee strip with dates */}
      <div className="fixture__strip">
        <div className="fixture__strip-track">
          {Array(2).fill(0).map((_, dup) => (
            <React.Fragment key={dup}>
              {(tickerItems.length ? tickerItems : ["TRENDINGOLF · TEMPORADA 2026", "FIXTURE · AMBA", "RANKING EN VIVO"]).map((item, i) => (
                <span key={`${dup}-${i}`}>
                  <span className="dot" />{item}
                </span>
              ))}
            </React.Fragment>
          ))}
        </div>
      </div>

      <div className="wrap">
        <div className="section-head">
          <div>
            <div className="section-eyebrow">FIXTURE · AUTO-SYNC</div>
            <h2 className="section-title">PRÓXIMAS <span className="green">FECHAS</span></h2>
          </div>
          <div>
            <p className="section-sub" style={{ marginBottom: "12px" }}>
              Datos en vivo desde la operación de TRENDINGOLF. Actualización automática cada hora.
            </p>
            <div className="fixture__source">
              <span className="live-dot" /> {status === "ok" && lastSync ? `SYNC ${lastSync.toLocaleTimeString("es-AR", {hour:"2-digit",minute:"2-digit"})}` : status === "loading" ? "CONECTANDO…" : status === "error" ? "OFFLINE — VOLVER A INTENTAR" : "SIN FECHAS"}
            </div>
          </div>
        </div>

        {status === "loading" && (
          <div className="fixture__state"><span className="blink" />SINCRONIZANDO FIXTURE…</div>
        )}
        {status === "error" && (
          <div className="fixture__state">
            NO PUDIMOS LEER EL FIXTURE EN VIVO.<br/>
            <a className="btn btn--ghost btn--sm" style={{marginTop: "16px"}} href="https://golf.trendingolf.com" target="_blank" rel="noopener">
              VER EN GOLF.TRENDINGOLF.COM →
            </a>
          </div>
        )}
        {status === "empty" && (
          <div className="fixture__state">NO HAY FECHAS PROGRAMADAS EN ESTE MOMENTO.</div>
        )}
        {status === "ok" && (
          <div className="fixture__rail">
            {fixtures.slice(0, 12).map((f, i) => (
              <FixtureCard key={i} f={f} isNext={i === 0} />
            ))}
          </div>
        )}
      </div>
    </section>
  );
}

function FixtureCard({ f, isNext }) {
  const rankingClass = f.isRanking ? "fcard--ranking" : "";
  return (
    <article className={`fcard ${isNext ? "fcard--next" : ""} ${rankingClass}`}>
      {f.isRanking && (
        <div className="fcard__corner">
          <span>★</span> RANKING{f.rankingLabel ? ` ${f.rankingLabel}` : ""}
        </div>
      )}
      {isNext && !f.isRanking && <div className="fcard__badge">▶ PRÓXIMA</div>}
      <div className="fcard__date">
        <div className="fcard__day">{String(f.day).padStart(2, "0")}</div>
        <div className="fcard__month-stack">
          <span className="fcard__month">{f.monthShort}</span>
          <span className="fcard__dow">{f.dow}</span>
        </div>
      </div>
      <h3 className="fcard__name">{f.club}</h3>
      <div className="fcard__meta">
        <div className="fcard__meta-row">
          <span className="fcard__meta-label">CIRCUITO</span>
          <span className="fcard__meta-value">TRENDINGOLF</span>
        </div>
        <div className="fcard__meta-row">
          <span className="fcard__meta-label">GREEN FEE</span>
          <span className="fcard__meta-value">{f.price}</span>
        </div>
      </div>
      <a className="fcard__cta" href={f.signupUrl} target="_blank" rel="noopener">
        RESERVAR <span>→</span>
      </a>
    </article>
  );
}

// ─────────────────────────────────────────────
// About
// ─────────────────────────────────────────────
function About() {
  return (
    <section className="about section" id="que-es">
      <div className="wrap">
        <div className="about__inner">
          <div className="about__copy">
            <div className="section-eyebrow">QUÉ ES TRENDINGOLF</div>
            <h2>UN CIRCUITO. <span style={{color:"var(--color-accent-primary)"}}>MUCHAS CANCHAS.</span></h2>
            <p>
              Organizamos torneos amateurs en los mejores clubes del AMBA. Cada semana, una cancha distinta. Cada torneo, una oportunidad de jugar, conocer y ranquear.
            </p>
            <p>
              Reservas, inscripciones y resultados viven en <strong style={{color:"var(--color-text-primary)"}}>golf.trendingolf.com</strong>. Acá te contamos qué se viene.
            </p>
            <div style={{display:"flex", gap:"12px", marginTop:"32px"}}>
              <a className="btn btn--primary" href="https://www.adondejugamos.com/ad/reservasconsulta.php?tab=770" target="_blank" rel="noopener">
                IR A RESERVAS <span className="arrow">→</span>
              </a>
            </div>
            <div className="about__stats">
              <div>
                <div className="stat__num">12+</div>
                <div className="stat__label">CLUBES DEL AMBA</div>
              </div>
              <div>
                <div className="stat__num">5+</div>
                <div className="stat__label">TORNEOS POR SEMANA</div>
              </div>
              <div>
                <div className="stat__num">2026</div>
                <div className="stat__label">TEMPORADA EN CURSO</div>
              </div>
              <div>
                <div className="stat__num">100%</div>
                <div className="stat__label">AMATEUR · ABIERTO</div>
              </div>
            </div>
          </div>

          <div className="about__viz">
            <div className="about__viz-inner" style={{
              backgroundImage: "url('https://cmsphoto.ww-cdn.com/superstatic/1602538/gal/original/gal-8703523.jpg?v=1536688365&force_webp=1')"
            }} />
            <div className="about__viz-tag">[ ESTANCIAS GC · 2024 ]</div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────
// Clubs
// ─────────────────────────────────────────────
function Clubs() {
  const clubs = [
    { name: "Highland Park CC", loc: "DEL VISO · BS.AS." },
    { name: "Los Lagartos CC", loc: "PILAR · BS.AS." },
    { name: "Golfer's CC", loc: "BERAZATEGUI · BS.AS." },
    { name: "Estancias GC", loc: "PILAR · BS.AS." },
    { name: "Club de Campo Los Pingüinos", loc: "ITUZAINGO · BS.AS." },
    { name: "Ituzaingo GC", loc: "ITUZAINGO · BS.AS." },
    { name: "Abril CC", loc: "HUDSON · BS.AS." },
    { name: "San Andrés GC", loc: "SAN ANDRÉS · BS.AS." },
    { name: "Club Campos de Golf Las Praderas de Luján", loc: "OPEN DOOR · BS.AS." },
    { name: "Haras Santa María", loc: "ESCOBAR · BS.AS." },
    { name: "La Colina Villa de Campo", loc: "OPEN DOOR · BS.AS." },
    { name: "La Martona CC", loc: "CAÑUELAS · BS.AS." },
  ];
  return (
    <section className="clubs section" id="clubes">
      <div className="wrap">
        <div className="section-head">
          <div>
            <div className="section-eyebrow">CLUBES · AMBA</div>
            <h2 className="section-title">DONDE <span className="green">JUGAMOS</span></h2>
          </div>
          <p className="section-sub">
            Recorremos los campos más emblemáticos del Área Metropolitana. Cada fecha, una cancha distinta.
          </p>
        </div>
        <div className="clubs__grid">
          {clubs.map((c, i) => (
            <div className="club" key={i}>
              <div className="club__num">CLUB / {String(i+1).padStart(2,"0")}</div>
              <div className="club__name">{c.name}</div>
              <div className="club__loc">{c.loc}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────
// Results — list of recent finished torneos pulled live from
// golf.trendingolf.com/golf/torneos.php (via TGResults loader).
// ─────────────────────────────────────────────

// Skeleton placeholder rows (rendered while we wait for live data on first
// visit — cached results from the previous load are preferred when available).
const RESULTS_SKELETON = Array.from({ length: 6 }, (_, i) => ({
  skeleton: true,
  id: i,
}));

function Results() {
  // Try cache first → instant render on repeat visits.
  const cached = (window.TGResults && window.TGResults.loadCached()) || null;
  const [items, setItems] = useState(cached ? cached.filter(t => t.date < new Date()).slice(0, 8) : RESULTS_SKELETON);
  const [status, setStatus] = useState(cached ? "live" : "loading"); // loading | live | error
  useEffect(() => {
    let cancelled = false;
    if (!window.TGResults) { setStatus("error"); setItems([]); return; }
    window.TGResults.load()
      .then((data) => {
        if (cancelled) return;
        const past = data.filter((t) => t.date < new Date()).slice(0, 8);
        if (past.length) {
          setItems(past);
          setStatus("live");
        } else if (!cached) {
          setStatus("error");
          setItems([]);
        }
      })
      .catch(() => {
        if (cancelled) return;
        if (!cached) { setStatus("error"); setItems([]); }
      });
    return () => { cancelled = true; };
  }, []);

  const last = items.find(t => !t.skeleton) || null;
  const eyebrow = last
    ? `ÚLTIMA FECHA · ${String(last.day).padStart(2,"0")}/${String(last.date.getMonth()+1).padStart(2,"0")} · ${last.venue}`
    : "TEMPORADA 2026";

  return (
    <section className="results section" id="resultados">
      <div className="wrap">
        <div className="section-head">
          <div>
            <div className="section-eyebrow">{eyebrow}</div>
            <h2 className="section-title">RESULTADOS <span className="green">RECIENTES</span></h2>
          </div>
          <a className="btn btn--ghost btn--sm" href="https://golf.trendingolf.com/golf/torneos.php" target="_blank" rel="noopener">
            VER TODOS LOS TORNEOS →
          </a>
        </div>

        <div className="results__list">
          <div className="results__head">
            <span>FECHA</span>
            <span>SEDE</span>
            <span className="col-mod">MODALIDAD</span>
            <span className="col-act" />
          </div>
          {items.map((t, i) => (
            t.skeleton ? (
              <div key={`sk-${t.id}`} className="results__row results__row--skeleton" aria-hidden="true">
                <span className="results__date">
                  <span className="sk sk--day" />
                  <span className="sk sk--month" />
                </span>
                <span className="results__venue">
                  <span className="sk sk--venue" />
                  <span className="sk sk--meta" />
                </span>
                <span className="col-mod"><span className="sk sk--mod" /></span>
                <span className="col-act"><span className="sk sk--act" /></span>
              </div>
            ) : (
            <a
              key={i}
              className="results__row"
              href="https://golf.trendingolf.com/golf/torneos.php"
              target="_blank"
              rel="noopener"
            >
              <span className="results__date">
                <span className="results__day">{String(t.day).padStart(2,"0")}</span>
                <span className="results__month">{t.monthShort} <span className="results__year">'{String(t.year).slice(2)}</span></span>
              </span>
              <span className="results__venue">
                <span className="results__venue-name">
                  {t.venue}
                  {t.isRanking && (
                    <span className="ranking-tag">
                      ★ RANKING{t.rankingLabel ? ` ${t.rankingLabel}` : ""}
                    </span>
                  )}
                </span>
                <span className="results__venue-meta">{t.dow}</span>
              </span>
              <span className="col-mod results__mod">{t.modality || "—"}</span>
              <span className="col-act results__act">TARJETAS →</span>
            </a>
            )
          ))}
          {status === "error" && items.length === 0 && (
            <div className="results__row results__row--empty">
              <span style={{gridColumn:"1 / -1", padding:"var(--space-6)", textAlign:"center", color:"var(--color-text-secondary)"}}>
                No pudimos sincronizar los resultados ahora. <a href="https://golf.trendingolf.com/golf/torneos.php" target="_blank" rel="noopener" style={{color:"var(--color-accent-primary)"}}>Ver en golf.trendingolf.com →</a>
              </span>
            </div>
          )}
          <div className="results__foot">
            <span>
              {status === "live" && <span className="dot dot--live" />}
              {status === "loading" && <span className="dot dot--loading" />}
              {status === "error" && <span className="dot dot--off" />}
              {status === "live" ? "DATOS EN VIVO" : status === "loading" ? "SINCRONIZANDO…" : "SIN CONEXIÓN A LA FUENTE"}
            </span>
            <span>FUENTE: GOLF.TRENDINGOLF.COM</span>
          </div>
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────
// Sponsors
// ─────────────────────────────────────────────
function Sponsors() {
  const partners = [
    { name: "Srixon", logo: "assets/sponsors/srixon.png", scale: 1.71 },
    { name: "WildGolf", logo: "assets/sponsors/wildgolf.png", scale: 1.0 },
    { name: "Colosso Wines", logo: "assets/sponsors/colosso.png", scale: 1.76 },
    { name: "TeeDel", logo: "assets/sponsors/teedel.png", scale: 1.0 },
  ];
  return (
    <section className="sponsors section--tight" id="sponsors">
      <div className="wrap" style={{ paddingBlock: "var(--space-12)" }}>
        <div className="section-head">
          <div>
            <div className="section-eyebrow">PARTNERS</div>
            <h2 className="section-title" style={{fontSize:"clamp(1.5rem, 3.5vw, 2.5rem)"}}>QUIENES NOS <span className="green">ACOMPAÑAN</span></h2>
          </div>
        </div>
      </div>
      <div className="sponsors__grid">
        {partners.map((p, i) => (
          <div className="sponsor" key={i} title={p.name} style={{ "--logo-scale": p.scale }}>
            <img src={p.logo} alt={p.name} loading="lazy" />
          </div>
        ))}
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────
// Viajes — feed of TEEDEL1 group trips
// ─────────────────────────────────────────────
function Viajes() {
  const trips = [
    {
      title: "Patagonia Open 2026: Chapelco Edition",
      sub: "El desafío Nicklaus en el corazón de la Cordillera",
      img: "https://teedel1.com/wp-content/uploads/2026/01/Chapelco-01-374x226.jpg",
      tag: "ARGENTINA · PATAGONIA",
      duration: "4 DÍAS · 3 NOCHES",
      price: "$690",
      priceOriginal: "$770",
      url: "https://teedel1.com/trip/patagonia-open-2026-chapelco-edition/",
    },
    {
      title: "Costa del Sol Golf Challenge",
      sub: "10 al 17 de Mayo 2026",
      img: "https://teedel1.com/wp-content/uploads/2022/03/Golf-Course-374x226.webp",
      tag: "ESPAÑA · COSTA DEL SOL",
      duration: "8 DÍAS · 7 NOCHES",
      price: "$2,890",
      priceOriginal: "$3,090",
      url: "https://teedel1.com/trip/costa-del-sol-golf-challenge/",
    },
    {
      title: "Miami Golfer's World Cup 2026",
      sub: "Trump National Doral & PGA National · 29 jun – 7 jul",
      img: "https://teedel1.com/wp-content/uploads/2026/01/course-the-fazio-374x226.jpg",
      tag: "USA · FLORIDA",
      duration: "9 DÍAS · 8 NOCHES",
      price: "$3,690",
      priceOriginal: "$4,680",
      url: "https://teedel1.com/trip/miami-golfers-world-cup-2026-trump-national-doral-pga-national/",
    },
    {
      title: "Stage 1: Trump National Doral",
      sub: "Blue Monster · 29 jun al 3 jul 2026",
      img: "https://teedel1.com/wp-content/uploads/2026/01/Blue-Monster-2-374x226.jpg",
      tag: "USA · FLORIDA",
      duration: "5 DÍAS · 4 NOCHES",
      price: "$2,190",
      priceOriginal: "$2,490",
      url: "https://teedel1.com/trip/miami-golfers-world-cup-2026-stage-1-trump-national-doral-blue-monster/",
    },
    {
      title: "Stage 2: PGA National & The Bear Trap",
      sub: "3 al 7 de julio 2026",
      img: "https://teedel1.com/wp-content/uploads/2025/12/course-champion-1920x720-1-374x226.webp",
      tag: "USA · FLORIDA",
      duration: "5 DÍAS · 4 NOCHES",
      price: "$1,790",
      priceOriginal: "$2,190",
      url: "https://teedel1.com/trip/pga-national-y-alentar-a-argentina/",
    },
    {
      title: "Punta Cana Golf Trophy",
      sub: "16 al 23 de agosto 2026",
      img: "https://teedel1.com/wp-content/uploads/2025/12/GRUPAL-374x226.webp",
      tag: "CARIBE · PUNTA CANA",
      duration: "8 DÍAS · 7 NOCHES",
      price: "$2,490",
      priceOriginal: null,
      url: "https://teedel1.com/trip/punta-cana-golf-trophy/",
    },
  ];
  return (
    <section className="viajes section" id="viajes">
      <div className="wrap">
        <div className="section-head">
          <div>
            <div className="section-eyebrow">VIAJES · TEEDEL1</div>
            <h2 className="section-title">JUGÁ EN LAS <span className="green">MEJORES CANCHAS</span> DEL MUNDO</h2>
          </div>
          <p className="section-sub">
            Programas grupales seleccionados con TEEDEL1 Golf Travel. Argentina, Caribe, España y USA.
          </p>
        </div>
        <div className="viajes__grid">
          {trips.map((t, i) => (
            <a className="viaje" key={i} href={t.url} target="_blank" rel="noopener">
              <div className="viaje__img" style={{ backgroundImage: `url('${t.img}')` }}>
                <div className="viaje__tag">{t.tag}</div>
                {t.priceOriginal && (
                  <div className="viaje__discount">
                    {Math.round((1 - parseInt(t.price.replace(/[^0-9]/g,"")) / parseInt(t.priceOriginal.replace(/[^0-9]/g,""))) * 100)}% OFF
                  </div>
                )}
              </div>
              <div className="viaje__body">
                <div className="viaje__duration">{t.duration}</div>
                <div className="viaje__title">{t.title}</div>
                <div className="viaje__sub">{t.sub}</div>
                <div className="viaje__foot">
                  <div className="viaje__price">
                    {t.priceOriginal && <span className="viaje__price-old">{t.priceOriginal}</span>}
                    <span className="viaje__price-new">{t.price}</span>
                  </div>
                  <span className="viaje__cta">VER VIAJE <span className="arrow">→</span></span>
                </div>
              </div>
            </a>
          ))}
        </div>
        <div className="viajes__more">
          <a className="btn btn--ghost" href="https://teedel1.com/" target="_blank" rel="noopener">
            VER TODOS LOS VIAJES EN TEEDEL1.COM →
          </a>
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────
// Final CTA
// ─────────────────────────────────────────────
function FinalCTA({ tweaks }) {
  return (
    <section className="finalcta">
      <div className="wrap">
        <div className="finalcta__inner">
          <h2>JUGÁ LA <span className="green">PRÓXIMA</span></h2>
          <p>Asegurá tu lugar en el siguiente torneo. Reservas en línea, pago digital, salida garantizada.</p>
          <a className="btn btn--primary" href="https://www.adondejugamos.com/ad/reservasconsulta.php?tab=770" target="_blank" rel="noopener" style={{padding:"16px 32px", fontSize:"var(--text-md)"}}>
            {tweaks.ctaCopy} <span className="arrow">→</span>
          </a>
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────
// Footer
// ─────────────────────────────────────────────
function Footer() {
  return (
    <footer className="foot">
      <div className="wrap">
        <div className="foot__top">
          <div className="foot__brand">
            <TGLogo height={36} />
            <p className="foot__tagline">El circuito amateur que mueve el golf del AMBA. Temporada 2026.</p>
          </div>
          <div className="foot__col">
            <h4>CIRCUITO</h4>
            <a href="#fixture">Fixture</a>
            <a href="#resultados">Resultados</a>
            <a href="#clubes">Clubes</a>
            <a href="https://www.adondejugamos.com/ad/reservasconsulta.php?tab=770" target="_blank" rel="noopener">Reservas ↗</a>
          </div>
          <div className="foot__col">
            <h4>TRENDINGOLF</h4>
            <a href="#que-es">Quiénes somos</a>
            <a href="#sponsors">Partners</a>
            <a href="mailto:hola@trendingolf.com">Contacto</a>
          </div>
          <div className="foot__col">
            <h4>SEGUINOS</h4>
            <a href="https://instagram.com/trendingolf" target="_blank" rel="noopener">Instagram ↗</a>
            <a href="#">WhatsApp ↗</a>
          </div>
        </div>
        <div className="foot__bottom">
          <span>© 2026 TRENDINGOLF · AMBA</span>
          <span>V1 · LANDING TEMPORAL</span>
        </div>
      </div>
    </footer>
  );
}

// ─────────────────────────────────────────────
// Header
// ─────────────────────────────────────────────
function Header({ tweaks }) {
  return (
    <header className="tg-header">
      <div className="wrap">
        <a href="#top" className="tg-header__logo"><TGLogo height={32} /></a>
        <nav className="tg-header__nav">
          <a href="#fixture">Fixture</a>
          <a href="#que-es">Circuito</a>
          <a href="#clubes">Clubes</a>
          <a href="#resultados">Resultados</a>
          <a href="#viajes">Viajes</a>
        </nav>
        <a className="btn btn--primary btn--sm" href="https://wa.me/5491161160028?text=Hola%20TRENDINGOLF" target="_blank" rel="noopener">
          <span style={{fontSize:"14px", marginRight:"4px"}}>✆</span> WHATSAPP <span className="arrow">→</span>
        </a>
      </div>
    </header>
  );
}

// ─────────────────────────────────────────────
// App
// ─────────────────────────────────────────────
function App() {
  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "heroVariant": "image",
    "heroImage": "slideshow",
    "fixtureLayout": "carousel",
    "ctaCopy": "RESERVAR"
  }/*EDITMODE-END*/;

  const [tweaks, setTweak] = window.useTweaks(TWEAK_DEFAULTS);

  return (
    <>
      <Header tweaks={tweaks} />
      <Hero tweaks={tweaks} />
      <Fixture tweaks={tweaks} />
      <About />
      <Clubs />
      <Results />
      <Viajes />
      <Sponsors />
      <FinalCTA tweaks={tweaks} />
      <Footer />

      <window.TweaksPanel title="Tweaks">
        <window.TweakSection title="Hero">
          <window.TweakRadio
            label="Variante"
            value={tweaks.heroVariant}
            options={[
              { value: "image", label: "Imagen" },
              { value: "split", label: "Estadio" },
              { value: "card", label: "Ficha" },
            ]}
            onChange={(v) => setTweak("heroVariant", v)}
          />
          <window.TweakRadio
            label="Foto"
            value={tweaks.heroImage}
            options={[
              { value: "slideshow", label: "Carrusel" },
              { value: "sunset", label: "Atardecer" },
              { value: "fairway", label: "Fairway" },
              { value: "original", label: "Original" },
            ]}
            onChange={(v) => setTweak("heroImage", v)}
          />
        </window.TweakSection>
        <window.TweakSection title="Fixture">
          <window.TweakRadio
            label="Layout"
            value={tweaks.fixtureLayout}
            options={[
              { value: "carousel", label: "Carrusel" },
              { value: "grid", label: "Grilla" },
              { value: "list", label: "Lista" },
            ]}
            onChange={(v) => setTweak("fixtureLayout", v)}
          />
        </window.TweakSection>
        <window.TweakSection title="CTA principal">
          <window.TweakSelect
            label="Texto del botón"
            value={tweaks.ctaCopy}
            options={[
              { value: "RESERVAR", label: "RESERVAR" },
              { value: "INSCRIBIRME", label: "INSCRIBIRME" },
              { value: "VER FIXTURE", label: "VER FIXTURE" },
              { value: "JUGAR", label: "JUGAR" },
            ]}
            onChange={(v) => setTweak("ctaCopy", v)}
          />
        </window.TweakSection>
      </window.TweaksPanel>
    </>
  );
}

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