// NEKO — Anasayfa page component
// Requires site-core.jsx + site-shop.jsx

function DiscordButton({ theme, lg }) {
  return (
    <button type="button" className={"btn btn-discord" + (lg ? " btn-lg" : "")}
      onClick={() => nekoToast("Discord daveti: " + NEKO.discord)}>
      <DiscordGlyph theme={theme} />
      Discord'a Katıl
    </button>
  );
}

function HeroMeta() {
  return (
    <div className="hero-meta">
      <span className="status-dot" aria-hidden="true"></span>
      <span><strong>{NEKO.online}</strong> oyuncu çevrimiçi</span>
      <span className="sep" aria-hidden="true"></span>
      <span>Sürüm {NEKO.version}</span>
    </div>
  );
}

// Hero background video — silent, native forward loop.
//
// NOTE — PRE-BAKED PING-PONG ASSET REQUIRED:
// The yoyo (forward → backward → forward) effect must be baked into the video
// file itself; runtime reverse playback via currentTime seeking stutters.
// Before production, export `uploads/bgvideo.mp4` as forward + reversed
// concatenated into one file (and strip the audio track), e.g. with ffmpeg:
//   ffmpeg -i bgvideo.mp4 -filter_complex \
//     "[0:v]reverse[r];[0:v][r]concat=n=2:v=1:a=0[v]" \
//     -map "[v]" -an -c:v libx264 -crf 23 -pix_fmt yuv420p \
//     -movflags +faststart bgvideo.mp4
// The code below plays that combined file normally with the native `loop`
// attribute, so the browser only ever plays forward — smooth, no seeking.
//
// NekoSky stays underneath as the poster/fallback layer while loading or on error.
function HeroVideoBackdrop({ theme }) {
  const videoRef = React.useRef(null);
  const [failed, setFailed] = React.useState(false);
  const [ready, setReady] = React.useState(false);

  React.useEffect(() => {
    const video = videoRef.current;
    if (!video) return;
    video.muted = true; // belt-and-braces: never any audio
    const reduced = window.matchMedia("(prefers-reduced-motion: reduce)");

    const onCanPlay = () => {
      setReady(true);
      if (!reduced.matches && video.paused) {
        video.play().catch(() => {});
      }
    };
    const onError = () => setFailed(true);
    const onMotionChange = () => {
      if (reduced.matches) { video.pause(); }
      else { video.play().catch(() => {}); }
    };

    video.addEventListener("canplay", onCanPlay);
    video.addEventListener("error", onError);
    if (reduced.addEventListener) reduced.addEventListener("change", onMotionChange);
    if (reduced.matches) video.pause();

    return () => {
      video.removeEventListener("canplay", onCanPlay);
      video.removeEventListener("error", onError);
      if (reduced.removeEventListener) reduced.removeEventListener("change", onMotionChange);
    };
  }, []);

  if (failed) return <NekoSky theme={theme} />;
  return (
    <div className="hero-video-wrap" aria-hidden="true">
      <NekoSky theme={theme} />
      <video ref={videoRef} className="hero-video" src="uploads/bgvideo.mp4"
        autoPlay muted playsInline loop preload="auto" tabIndex={-1}
        disablePictureInPicture
        style={{ opacity: ready ? 1 : 0, transition: "opacity .9s ease" }}></video>
      <div className="hero-video-tint"></div>
      <div className="hero-video-fade"></div>
    </div>
  );
}

function HomeHero({ theme, variant }) {
  if (variant === "2") {
    const corner = (pos) => ({
      position: "absolute", width: 18, height: 18, background: "var(--c-accent)", zIndex: 2,
      ...(pos.includes("t") ? { top: -6 } : { bottom: -6 }),
      ...(pos.includes("l") ? { left: -6 } : { right: -6 }),
    });
    return (
      <header className="hero">
        <HeroVideoBackdrop theme={theme} />
        <div className="hero-split">
          <div>
            <h1 className="hero-title" style={{ fontSize: "clamp(56px, 7vw, 84px)" }}>NEKO</h1>
            <p className="hero-sub" style={{ margin: "16px 0 24px" }}>
              Keşif, görev ve topluluk odaklı hayatta kalma sunucusu. Sezon 4 şimdi açık.
            </p>
            <div className="hero-ctas" style={{ justifyContent: "flex-start", marginBottom: 22 }}>
              <a href="#katil" className="btn btn-primary">Sunucuya Katıl</a>
              <CopyIpButton ghost />
              <DiscordButton theme={theme} />
            </div>
          </div>
          <div className="px-shadow">
            <div style={{ position: "relative" }}>
              <div className="img-ph" style={{ aspectRatio: "16 / 10", fontSize: 13 }}>
                sunucu ekran görüntüsü — 16:10{"\n"}(sur / kale gün batımı çekimi)
              </div>
              <span aria-hidden="true" style={corner("tl")}></span>
              <span aria-hidden="true" style={corner("tr")}></span>
              <span aria-hidden="true" style={corner("bl")}></span>
              <span aria-hidden="true" style={corner("br")}></span>
            </div>
          </div>
        </div>
      </header>
    );
  }
  // Variant 1 — Sinematik Merkez
  return (
    <header className="hero">
      <HeroVideoBackdrop theme={theme} />
      <div className="hero-inner">
        <div className="hero-kicker">YAŞAYAN BİR MINECRAFT DÜNYASI</div>
        <h1 className="hero-title">NEKO</h1>
        <p className="hero-sub">Surların ardında görevler, dostluklar ve keşfedilmemiş topraklar seni bekliyor.</p>
        <div className="hero-ctas">
          <a href="#katil" className="btn btn-primary btn-lg">Sunucuya Katıl</a>
          <CopyIpButton />
          <DiscordButton theme={theme} lg />
        </div>
      </div>
      <div style={{ position: "relative", marginTop: 30 }}>
        <NekoTerrain theme={theme} />
      </div>
    </header>
  );
}

function ModeCard({ m, theme }) {
  const body = (
    <div className="px-shadow-sm card-hover" style={{ height: "100%" }}>
      <div className="frost-2" style={{ padding: 18, display: "flex", flexDirection: "column", gap: 10, height: "100%", "--px-step": "6px" }}>
        <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 10 }}>
          <ItemSlot label={"mod ikonu\n(piksel art)"} size={56} />
          {m.mascot ? <DiscordGlyph theme={theme} /> : null}
        </div>
        <div style={{ fontFamily: "var(--font-pixel)", fontSize: 19, fontWeight: 600, lineHeight: 1.25 }}>{m.name}</div>
        <p style={{ fontSize: 12.5, lineHeight: 1.6, color: "var(--c-text-2)", margin: 0, flex: 1 }}>{m.desc}</p>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
          <span className="badge" style={{ fontSize: 11 }}>{m.stat}</span>
          {m.href ? <span className="supporter-hint" aria-hidden="true">→</span> : null}
        </div>
      </div>
    </div>
  );
  if (m.href) {
    return <a className="mode-link" href={m.href} aria-label={m.name}>{body}</a>;
  }
  return body;
}

function NewsCard({ n }) {
  return (
    <article className="px-shadow-sm card-hover">
      <div className="frost-2" style={{ display: "flex", flexDirection: "column", height: "100%", "--px-step": "6px" }}>
        <div className="img-ph" style={{ aspectRatio: "16 / 9" }}>{n.ph}</div>
        <div style={{ padding: 16, display: "flex", flexDirection: "column", gap: 8, flex: 1 }}>
          <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
            <span className="badge badge-cosmetic" style={{ fontSize: 10.5 }}>{n.cat}</span>
            <span style={{ fontSize: 11.5, color: "var(--c-text-2)" }}>{n.date}</span>
          </div>
          <h3 style={{ fontFamily: "var(--font-pixel)", fontSize: 17, fontWeight: 600, margin: 0, lineHeight: 1.3 }}>{n.title}</h3>
        </div>
      </div>
    </article>
  );
}

function HomePage() {
  const [theme, setTheme] = useNekoTheme();
  const [tw, setTw] = useNekoTweaks();
  const cart = useCart();
  const [cartOpen, setCartOpen] = React.useState(false);

  return (
    <React.Fragment>
      <a className="skip-link" href="#icerik">İçeriğe geç</a>
      <SiteNavbar active="home" theme={theme} setTheme={setTheme} variant={tw.navVariant}
        cartCount={cart.count} onCartOpen={() => setCartOpen(true)} />
      <HomeHero theme={theme} variant={tw.heroVariant} />

      <main id="icerik">
        {/* Server modes */}
        <section className="section" aria-labelledby="modlar">
          <SectionHead title="Neko'yı Keşfet" sub="Tek dünyada birbirine bağlı modlar — hepsi aynı haritada, aynı toplulukta." />
          <div className="grid-modes">
            {NEKO_MODES.map((m) => <ModeCard key={m.name} m={m} theme={theme} />)}
          </div>
        </section>

        <PixelDivider />

        {/* Living world split */}
        <section className="section" aria-labelledby="dunya">
          <div style={{ display: "grid", gridTemplateColumns: "1.05fr 1fr", gap: "clamp(24px, 5vw, 56px)", alignItems: "center" }} className="split-2">
            <div className="px-shadow">
              <div className="img-ph" style={{ aspectRatio: "4 / 3", fontSize: 13 }}>
                dünya görseli — 4:3{"\n"}(zindan girişi / sur manzarası)
              </div>
            </div>
            <div>
              <h2 className="section-title" style={{ fontFamily: "var(--font-hero)", fontSize: "clamp(30px, 4vw, 44px)" }}>Bilinmeyene Cesaret Et</h2>
              <p style={{ fontSize: 14.5, lineHeight: 1.75, color: "var(--c-text-2)", maxWidth: "48ch" }}>
                Haftalık görev zincirleri, oyuncuların kurduğu kasabalar, zindan rotaları ve cuma akşamları
                hep birlikte savunduğumuz surlar. Neko'da dünya senin izini taşır.
              </p>
              <a href="#katil" className="btn btn-secondary" style={{ marginTop: 10 }}>Sunucuya Katıl</a>
            </div>
          </div>
        </section>

        {/* Store preview */}
        <div className="band">
          <section className="section" aria-labelledby="magaza-on">
            <SectionHead title="Mağazadan Seçmeler"
              sub="Tamamı kozmetik ve destekçi odaklı — oyun gücü satılmaz."
              cta={<a href="Magaza.html" className="btn btn-outline">Mağazayı Gör</a>} />
            <div className="hscroll">
              {["rank-gezgin", "koz-sapka", "pet-tilki", "diyar-bayrak", "paket-sezon", "tag-kasif", "fx-ender"]
                .map((id) => NEKO_PRODUCTS.find((p) => p.id === id))
                .filter(Boolean)
                .map((p) => (
                  <ProductCard key={p.id} p={p} variant={tw.cardVariant} onAdd={cart.add} />
                ))}
            </div>
          </section>
        </div>

        {/* Credits preview */}
        <section className="section" aria-labelledby="kredi-on">
          <SectionHead title="Krediler"
            sub="Kredi, Neko'nın site bakiyesi. Yükle, mağazada kozmetiklerde harca."
            cta={<a href="Krediler.html" className="btn btn-outline">Kredi Yükle</a>} />
          <div className="grid-packs">
            {NEKO_PACKS.slice(0, 3).map((k) => (
              <div key={k.id} className="px-shadow card-hover">
                <div className={k.popular ? "glass-1" : "block-3"} style={{ padding: 22, textAlign: "center", height: "100%", display: "flex", flexDirection: "column", gap: 8 }}>
                  {k.popular && <span className="badge badge-supporter" style={{ alignSelf: "center" }}>En popüler</span>}
                  <div style={{ fontFamily: "var(--font-hero)", fontSize: 40, lineHeight: 1 }}>{k.amount}</div>
                  <div style={{ fontSize: 12, color: "var(--c-text-2)" }}>Kredi {k.bonus ? "· " + k.bonus : ""}</div>
                  <a href="Krediler.html" className="btn btn-secondary btn-sm" style={{ marginTop: "auto" }}>Seç</a>
                </div>
              </div>
            ))}
          </div>
        </section>

        {/* Discord CTA — community gathering card */}
        <section className="section" id="topluluk" aria-labelledby="discord">
          <div className="glass-1 community-card">
            <PxCorners size={12} />
            <div>
              <h2 className="section-title" style={{ marginBottom: 8 }}>Topluluğa Katıl</h2>
              <p style={{ fontSize: 13.5, lineHeight: 1.7, color: "var(--c-text-2)", margin: "0 0 20px", maxWidth: "52ch" }}>
                Duyurular, etkinlik takvimi ve yardım kanalı Discord'da. {NEKO.discord}
              </p>
              <DiscordButton theme={theme} />
            </div>
            <CommunityScene theme={theme} />
          </div>
        </section>

        {/* News */}
        <div className="band">
          <section className="section" aria-labelledby="haberler">
            <SectionHead title="Haberler & Güncellemeler"
              cta={<a href="Duyurular.html" className="btn btn-outline">Tüm Duyurular</a>} />
            <div className="grid-news">
              {NEKO_NEWS.map((n) => <NewsCard key={n.title} n={n} />)}
            </div>
          </section>
        </div>

        {/* Recent supporters — hover/focus expands to a profile preview */}
        <section className="section" aria-labelledby="aktivite" style={{ paddingBottom: "clamp(72px, 9vw, 120px)" }}>
          <SectionHead title="Son Destekçiler" sub="Örnek veriler — üzerine gel ya da odaklan: oyuncu önizlemesi açılır, tıklayınca profile gider." />
          <div className="supporter-grid">
            {NEKO_SUPPORTERS.map((a) => {
              const ini = (s) => (s.replace(/[“”"']/g, "").trim().charAt(0) || "▪");
              return (
                <div key={a.user} className="supporter-wrap">
                  <a className="supporter-link card-hover" href={"Profil.html?oyuncu=" + encodeURIComponent(a.user)}
                    aria-label={a.user + " — profili görüntüle"}>
                    <div className="px-shadow-sm">
                      <div className="block-3 supporter-card" style={{ "--px-step": "5px" }}>
                        <PixelAvatar seed={a.seed} />
                        <div className="who">
                          <strong>{a.user}</strong>
                          <span>{a.item}</span>
                        </div>
                        <span className="badge badge-supporter" style={{ fontSize: 10.5 }}>Destekçi</span>
                      </div>
                    </div>
                    <div className="supporter-extra px-shadow-sm">
                      <div className="block-3 supporter-extra-inner" style={{ "--px-step": "5px" }}>
                        <span className="supporter-stat">Oynama süresi:&nbsp;<strong>{a.hours} saat</strong></span>
                        {a.showCosmetics && a.cosmetics.length > 0 ? (
                          <div className="cosmetic-row" aria-label="Satın alınan kozmetikler">
                            {a.cosmetics.slice(0, 5).map((c) => (
                              <span key={c} className="cosmetic-mini" title={c}>{ini(c)}</span>
                            ))}
                          </div>
                        ) : (
                          <span className="supporter-stat">Kozmetikler gizli</span>
                        )}
                        <span className="supporter-hint">Profili görüntüle →</span>
                      </div>
                    </div>
                  </a>
                </div>
              );
            })}
          </div>
        </section>

        {/* Final join CTA */}
        <section className="section" id="katil" aria-labelledby="son-cta">
          <div className="px-shadow">
            <div className="block-3" style={{ padding: "clamp(28px, 5vw, 48px)", textAlign: "center" }}>
              <h2 style={{ fontFamily: "var(--font-hero)", fontSize: "clamp(30px, 4.6vw, 48px)", margin: "0 0 10px" }}>Surlar Seni Bekliyor</h2>
              <p style={{ fontSize: 13.5, color: "var(--c-text-2)", margin: "0 0 22px" }}>
                {NEKO.ip} · Sürüm {NEKO.version} · {NEKO.discord}
              </p>
              <div className="hero-ctas">
                <CopyIpButton />
                <a href="Magaza.html" className="btn btn-ghost">Mağazayı Gör</a>
                <a href="Giris Yap.html" className="btn btn-primary">Giriş Yap</a>
              </div>
            </div>
          </div>
        </section>
      </main>

      <SiteFooter />
      <CartDrawer cart={cart} open={cartOpen} onClose={() => setCartOpen(false)} />
      <ToastHost />
      <NekoTweaks theme={theme} setTheme={setTheme} tw={tw} setTw={setTw} page="home" />
    </React.Fragment>
  );
}

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