// HelloReader site components — uses tokens from assets/tokens.css
// Phone frames fork the ReadMe UI kit (Cover, FolderTabs, SearchPill, HeroBanner, etc.)

const { useState, useEffect, useRef } = React;

// ----- Confetti squares motif (decorative, sparse) -----
function ConfettiSquares({ seed = 1, count = 14, style = {} }) {
  // Deterministic pseudo-random
  const rand = (n) => {
    const x = Math.sin(seed * 9301 + n * 49297) * 233280;
    return x - Math.floor(x);
  };
  const squares = Array.from({ length: count }, (_, i) => {
    const size = 8 + rand(i) * 18;
    const filled = rand(i + 100) > 0.45;
    const yellow = rand(i + 200) > 0.3;
    return {
      size,
      top: rand(i + 1) * 100,
      left: rand(i + 2) * 100,
      rot: rand(i + 3) * 45 - 22,
      filled,
      color: yellow ? "#FED605" : "#FFE96B",
    };
  });
  return (
    <div data-confetti="true" style={{ position: "absolute", inset: 0, pointerEvents: "none", overflow: "hidden", ...style }}>
      {squares.map((s, i) => (
        <div key={i} style={{
          position: "absolute",
          top: `${s.top}%`, left: `${s.left}%`,
          width: s.size, height: s.size,
          background: s.filled ? s.color : "transparent",
          border: s.filled ? "none" : `2px solid ${s.color}`,
          transform: `rotate(${s.rot}deg)`,
          borderRadius: 3,
          opacity: 0.85,
        }} />
      ))}
    </div>
  );
}

// ----- Logo -----
function Logo({ size = 28 }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
      <div style={{
        width: size, height: size, background: "#FED605", borderRadius: size * 0.28,
        display: "flex", alignItems: "center", justifyContent: "center",
      }}>
        <svg width={size * 0.55} height={size * 0.65} viewBox="0 0 20 24" fill="none">
          <rect x="0" y="0" width="20" height="24" rx="2" fill="#0A0A0A"/>
          <path d="M12 0 L16 0 L16 9 L14 7 L12 9 Z" fill="#fff"/>
        </svg>
      </div>
      <span style={{ fontWeight: 900, fontSize: 18, color: "#0A0A0A", letterSpacing: "-0.01em" }}>HelloReader</span>
    </div>
  );
}

// ----- Language switcher -----
function LangSwitcher({ lang, onChange }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);
  const langs = [
    { code: "en", short: "EN", label: "English" },
    { code: "zh", short: "中", label: "中文" },
    { code: "vi", short: "VN", label: "Tiếng Việt" },
    { code: "th", short: "TH", label: "ภาษาไทย" },
    { code: "id", short: "ID", label: "Indonesia" },
  ];
  const cur = langs.find(l => l.code === lang);
  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button onClick={() => setOpen(!open)} style={{
        background: "#fff", border: "1.5px solid #E5E5E5", borderRadius: 999,
        padding: "8px 14px 8px 10px", cursor: "pointer", display: "flex", alignItems: "center", gap: 8,
        fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 13, color: "#0A0A0A",
      }}>
        <span style={{
          width: 22, height: 22, borderRadius: "50%", background: "#FED605",
          display: "inline-flex", alignItems: "center", justifyContent: "center",
          fontSize: 10, fontWeight: 900,
        }}>{cur.short}</span>
        <span>{cur.label}</span>
        <svg width="10" height="10" viewBox="0 0 12 12" fill="none">
          <path d="M3 4.5 L6 7.5 L9 4.5" stroke="#0A0A0A" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </button>
      {open && (
        <div style={{
          position: "absolute", right: 0, top: "calc(100% + 6px)",
          background: "#fff", borderRadius: 14, boxShadow: "var(--shadow-elevated)",
          border: "1px solid #EFEFEF", minWidth: 180, padding: 6, zIndex: 100,
        }}>
          {langs.map(l => (
            <button key={l.code} onClick={() => { onChange(l.code); setOpen(false); }} style={{
              width: "100%", textAlign: "left", padding: "10px 12px",
              background: l.code === lang ? "#FFF7C2" : "transparent",
              border: "none", borderRadius: 10, cursor: "pointer",
              display: "flex", alignItems: "center", gap: 10,
              fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 13,
              color: "#0A0A0A",
            }}>
              <span style={{
                width: 22, height: 22, borderRadius: "50%",
                background: l.code === lang ? "#FED605" : "#F5F5F5",
                display: "inline-flex", alignItems: "center", justifyContent: "center",
                fontSize: 10, fontWeight: 900,
              }}>{l.short}</span>
              {l.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// ----- Top nav -----
function TopNav({ lang, setLang, t }) {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  useEffect(() => {
    const h = () => setScrolled(window.scrollY > 20);
    h(); window.addEventListener("scroll", h, { passive: true });
    return () => window.removeEventListener("scroll", h);
  }, []);
  useEffect(() => {
    // Prevent body scroll when mobile menu is open
    document.body.style.overflow = menuOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [menuOpen]);
  const links = [
    { href: "#about", label: t.nav.about },
    { href: "#product", label: t.nav.product },
    { href: "#content", label: t.nav.content },
    { href: "#partners", label: t.nav.partners },
    { href: "#contact", label: t.nav.contact },
  ];
  return (
    <nav className="topnav" style={{
      position: "sticky", top: 0, zIndex: 50,
      background: scrolled ? "rgba(255,255,255,0.92)" : "rgba(255,255,255,0.6)",
      backdropFilter: "saturate(180%) blur(16px)",
      WebkitBackdropFilter: "saturate(180%) blur(16px)",
      borderBottom: scrolled ? "1px solid #EFEFEF" : "1px solid transparent",
      transition: "all 200ms var(--ease-out)",
    }}>
      <div className="topnav-inner" style={{
        maxWidth: 1280, margin: "0 auto",
        padding: "14px 32px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 24,
      }}>
        <a href="#top" style={{ textDecoration: "none" }} onClick={() => setMenuOpen(false)}><Logo /></a>
        <div className="topnav-links" style={{ display: "flex", alignItems: "center", gap: 4 }}>
          {links.map(l => (
            <a key={l.href} href={l.href} style={{
              padding: "8px 14px", borderRadius: 999,
              fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 700,
              color: "#2E2E2E", textDecoration: "none",
              transition: "all 150ms var(--ease-out)",
            }}
            onMouseEnter={e => { e.currentTarget.style.background = "#F5F5F5"; e.currentTarget.style.color = "#0A0A0A"; }}
            onMouseLeave={e => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "#2E2E2E"; }}
            >{l.label}</a>
          ))}
        </div>
        <div className="topnav-right" style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <LangSwitcher lang={lang} onChange={setLang} />
          <a href="#partners" className="topnav-cta" style={{
            background: "#0A0A0A", color: "#FED605",
            padding: "10px 18px", borderRadius: 999,
            fontFamily: "var(--font-sans)", fontWeight: 800, fontSize: 13,
            textDecoration: "none", display: "inline-block",
          }}>{t.hero.ctaPrimary}</a>
          <button
            type="button"
            className="topnav-hamburger"
            aria-label={menuOpen ? "Close menu" : "Open menu"}
            aria-expanded={menuOpen}
            onClick={() => setMenuOpen(o => !o)}
            style={{
              display: "none", border: "none", background: "transparent",
              padding: 8, cursor: "pointer", color: "#0A0A0A",
            }}
          >
            {menuOpen ? (
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
            ) : (
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M4 7h16M4 12h16M4 17h16"/></svg>
            )}
          </button>
        </div>
      </div>

      {/* Mobile overlay menu */}
      <div className="topnav-overlay" data-open={menuOpen} style={{
        display: "none",
        position: "fixed", top: 0, left: 0, right: 0, bottom: 0,
        background: "#fff", zIndex: 49, paddingTop: 64, overflowY: "auto",
      }}>
        <div style={{ padding: "24px 24px 80px", display: "flex", flexDirection: "column", gap: 4 }}>
          {links.map(l => (
            <a key={l.href} href={l.href} onClick={() => setMenuOpen(false)} style={{
              padding: "16px 18px", borderRadius: 14, background: "#F7F7F7",
              fontFamily: "var(--font-sans)", fontSize: 17, fontWeight: 800,
              color: "#0A0A0A", textDecoration: "none",
            }}>{l.label}</a>
          ))}
          <a href="#partners" onClick={() => setMenuOpen(false)} style={{
            marginTop: 16, padding: "18px 18px", borderRadius: 14,
            background: "#0A0A0A", color: "#FED605", textAlign: "center",
            fontFamily: "var(--font-sans)", fontWeight: 900, fontSize: 15,
            textDecoration: "none",
          }}>{t.hero.ctaPrimary}</a>
        </div>
      </div>
    </nav>
  );
}

// ----- Animated counter -----
function Counter({ to, suffix = "", duration = 1800, prefix = "" }) {
  const [v, setV] = useState(0);
  const ref = useRef(null);
  const started = useRef(false);
  useEffect(() => {
    const run = () => {
      if (started.current) return;
      started.current = true;
      const start = performance.now();
      const tick = (now) => {
        const p = Math.min(1, (now - start) / duration);
        // easeOutQuart
        const eased = 1 - Math.pow(1 - p, 4);
        setV(to * eased);
        if (p < 1) requestAnimationFrame(tick);
        else setV(to); // guarantee exact final value
      };
      requestAnimationFrame(tick);
    };
    const obs = new IntersectionObserver(entries => {
      entries.forEach(e => { if (e.isIntersecting) run(); });
    }, { threshold: 0.15 });
    if (ref.current) obs.observe(ref.current);
    // Fallback: if the observer never fires (layout quirks, fast scroll,
    // language switch re-mount), still settle on the final value.
    const fallback = setTimeout(run, 2500);
    return () => { obs.disconnect(); clearTimeout(fallback); };
  }, [to, duration]);
  let display;
  if (to >= 1000000) display = (v / 1000000).toFixed(v === to ? 1 : 1) + "M";
  else if (to >= 1000) display = Math.round(v / 1000) + "K";
  else if (to % 1 !== 0) display = v.toFixed(1);
  else display = Math.round(v).toString();
  return <span ref={ref}>{prefix}{display}{suffix}</span>;
}

// ----- Hero stats -----
function StatBlock({ value, label }) {
  return (
    <div>
      <div style={{
        fontFamily: "var(--font-sans)", fontWeight: 900, fontSize: 36,
        color: "#0A0A0A", letterSpacing: "-0.02em", lineHeight: 1,
      }}>{value}</div>
      <div style={{
        fontFamily: "var(--font-sans)", fontSize: 12, fontWeight: 700,
        color: "#737373", marginTop: 8, textTransform: "uppercase", letterSpacing: "0.06em",
      }}>{label}</div>
    </div>
  );
}

// ----- Section wrapper -----
function Section({ id, children, style = {}, screenLabel }) {
  return (
    <section id={id} data-screen-label={screenLabel} style={{
      maxWidth: 1280, margin: "0 auto", padding: "120px 32px", ...style,
    }}>{children}</section>
  );
}

function Eyebrow({ children, color = "#FF7A1A" }) {
  return (
    <div style={{
      fontFamily: "var(--font-sans)", fontSize: 11, fontWeight: 800,
      color, letterSpacing: "0.12em", textTransform: "uppercase",
      display: "inline-flex", alignItems: "center", gap: 8,
    }}>
      <span style={{ width: 20, height: 2, background: color, borderRadius: 1 }} />
      {children}
    </div>
  );
}

// ----- Phone frame wrapping forked ReadMe screens -----
function PhoneFrame({ children, label, tilt = 0, scale = 1 }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 14 }}>
      <div style={{
        width: 280, height: 580, background: "#0A0A0A",
        borderRadius: 38, padding: 8,
        boxShadow: "0 30px 60px -20px rgba(20,20,20,0.35), 0 10px 24px rgba(20,20,20,0.18)",
        transform: `rotate(${tilt}deg) scale(${scale})`,
        transition: "transform 300ms var(--ease-out)",
      }}>
        <div style={{
          width: "100%", height: "100%", background: "#fff", borderRadius: 30,
          overflow: "hidden", position: "relative", display: "flex", flexDirection: "column",
        }}>
          {/* notch */}
          <div style={{
            position: "absolute", top: 6, left: "50%", transform: "translateX(-50%)",
            width: 90, height: 20, background: "#0A0A0A", borderRadius: 12, zIndex: 2,
          }} />
          <div style={{
            height: 28, background: "#FED605", display: "flex", alignItems: "center",
            justifyContent: "space-between", padding: "0 18px", fontSize: 10, fontWeight: 800,
            color: "#0A0A0A", flex: "none", paddingTop: 6,
          }}>
            <span>9:41</span>
            <span style={{ display: "flex", gap: 4, alignItems: "center" }}>
              <span style={{ width: 4, height: 4, background: "#0A0A0A", borderRadius: "50%" }} />
              <span style={{ width: 4, height: 4, background: "#0A0A0A", borderRadius: "50%" }} />
              <span style={{ width: 4, height: 4, background: "#0A0A0A", borderRadius: "50%" }} />
            </span>
          </div>
          <div style={{ flex: 1, overflow: "hidden", background: "#fff" }}>
            {children}
          </div>
        </div>
      </div>
      <div style={{
        fontFamily: "var(--font-sans)", fontWeight: 800, fontSize: 12,
        color: "#737373", letterSpacing: "0.06em", textTransform: "uppercase",
      }}>{label}</div>
    </div>
  );
}

// ----- Mini ReadMe screens for the phone frames -----
// We scale down the full screens to fit nicely
function MiniDiscover({ t }) {
  return (
    <div style={{ transform: "scale(0.74)", transformOrigin: "top left", width: "135%", height: "135%" }}>
      <FolderTabs tabs={[t.product.phoneLabel1, "Ranking", "Category"]} active={t.product.phoneLabel1} onChange={() => {}} />
      <SearchPill placeholder="Story name" />
      <HeroBanner title="CORNER" italic="With" badge="Serializing" subtitle="Baby" hue={30} />
      <SectionHeader title="New Releases" rightAction="See all ›" />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10, padding: "0 16px 20px" }}>
        <BookCell title="Love for Never Fails" chapter="Ch. 12" hue={340} />
        <BookCell title="Daisy's Husband" chapter="Ch. 88" hue={10} />
        <BookCell title="My Pretty Boss" chapter="Ch. 6" hue={300} />
      </div>
    </div>
  );
}

function MiniLibrary({ t }) {
  return (
    <div style={{ transform: "scale(0.74)", transformOrigin: "top left", width: "135%", height: "135%" }}>
      <div style={{ background: "#FED605", padding: "12px 16px 18px" }}>
        <div style={{ fontSize: 26, fontWeight: 900, color: "#0A0A0A" }}>{t.product.phoneLabel2}</div>
        <div style={{ display: "flex", gap: 10, marginTop: 10 }}>
          <div style={{ flex: 1, background: "#fff", borderRadius: 12, padding: "10px 12px" }}>
            <div style={{ fontSize: 11, color: "#737373", fontWeight: 700 }}>Reading</div>
            <div style={{ fontSize: 16, fontWeight: 900, color: "#0A0A0A" }}>47 <span style={{ fontSize: 11, color: "#737373" }}>mins today</span></div>
          </div>
          <div style={{ flex: 1.3, background: "#fff", borderRadius: 12, padding: "10px 12px" }}>
            <span style={{ background: "linear-gradient(90deg,#FED605,#FFB800)", color: "#0A0A0A", fontWeight: 900, fontSize: 9, padding: "2px 6px", borderRadius: 999 }}>OPEN SVIP</span>
            <div style={{ fontSize: 10, color: "#FF3E5F", fontWeight: 700, marginTop: 4 }}>Sign in daily for rewards</div>
          </div>
        </div>
      </div>
      <div style={{ padding: 16 }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }}>
          <BookCell title="Who Are You, My Husband" chapter="Ch. 213" hue={340} />
          <BookCell title="Remarriage meets Love" chapter="Ch. 90" hue={10} />
          <BookCell title="Cunning Baby" chapter="Ch. 21" hue={280} />
          <BookCell title="Mary's Husband" chapter="Ch. 216" hue={50} />
          <BookCell title="Kill Me, Heal Me" chapter="Ch. 120" hue={200} />
          <BookCell title="Bad Luck Bride" chapter="Ch. 44" hue={320} />
        </div>
      </div>
    </div>
  );
}

function MiniReader({ t }) {
  return (
    <div style={{ background: "#F5EFE2", height: "100%", padding: "16px 18px 24px", overflow: "hidden" }}>
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 10, color: "#7A7268", fontWeight: 700 }}>
        <span>Chapter 12 · The Ballroom</span>
        <span>36%</span>
      </div>
      <div style={{ fontFamily: "'Source Serif 4',serif", color: "#2B2520", fontSize: 13, lineHeight: 1.7, marginTop: 12 }}>
        <p style={{ margin: "0 0 10px" }}>She turned the page. The ballroom lights caught on Lucien's cufflinks — gold, like everything else he owned.</p>
        <p style={{ margin: "0 0 10px" }}>"You came," he said, and there was no trace of surprise in his voice.</p>
        <p style={{ margin: "0 0 10px" }}>Jenny smoothed the hem of her borrowed gown. The silk felt cold against her palms.</p>
        <p style={{ margin: "0 0 10px" }}>"I didn't come for you."</p>
        <p style={{ margin: "0 0 10px" }}>"No?" He stepped closer, and the chandelier caught fire in his eyes.</p>
      </div>
      <div style={{ marginTop: 14, padding: "10px 12px", background: "#fff", borderRadius: 12, display: "flex", alignItems: "center", gap: 8, boxShadow: "0 1px 2px rgba(60,40,20,.06), 0 6px 14px rgba(60,40,20,.08)" }}>
        <div style={{ width: 22, height: 22, borderRadius: "50%", background: "radial-gradient(circle at 30% 30%,#FFEE80,#FED605 55%,#C99C00)", display: "flex", alignItems: "center", justifyContent: "center", color: "#4B3508", fontWeight: 900, fontSize: 11 }}>¥</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, fontWeight: 800, color: "#0A0A0A" }}>Next chapter locked</div>
          <div style={{ fontSize: 9, color: "#737373" }}>Borrow for free today!</div>
        </div>
        <button style={{ background: "#FED605", color: "#0A0A0A", border: "none", fontWeight: 900, padding: "6px 12px", borderRadius: 999, fontSize: 10 }}>Borrow</button>
      </div>
    </div>
  );
}

// Real Play Store marketing shot — already includes phone framing + brand chrome.
function RealShot({ src, label, tilt = 0 }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 14 }}>
      <div style={{
        width: 300, borderRadius: 28, overflow: "hidden",
        transform: `rotate(${tilt}deg)`,
        boxShadow: "0 30px 60px -20px rgba(0,0,0,0.45), 0 10px 24px rgba(0,0,0,0.22)",
        background: "#fff",
        transition: "transform 300ms var(--ease-out)",
      }}>
        <img src={src} alt={label} style={{ display: "block", width: "100%", height: "auto" }} />
      </div>
      <div style={{
        fontFamily: "var(--font-sans)", fontWeight: 800, fontSize: 12,
        color: "#C9C3B8", letterSpacing: "0.08em", textTransform: "uppercase",
      }}>{label}</div>
    </div>
  );
}

Object.assign(window, {
  ConfettiSquares, Logo, LangSwitcher, TopNav, Counter, StatBlock,
  Section, Eyebrow, PhoneFrame, RealShot, MiniDiscover, MiniLibrary, MiniReader,
});
