/* OneMoreDay landing — hero + testimonial scroll reveal + Tweaks */

const { useRef, useEffect, useState, useMemo } = React;

/* ---- TWEAKS (persist with EDITMODE markers) ---- */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "avatarState": "alive",
  "accentHue": 145,
  "showGrid": true,
  "avatarName": "Kai",
  "heroTitleA": "Don't break the streak.",
  "heroTitleB": "Give your avatar one more day."
} /*EDITMODE-END*/;

function useTweaks() {
  const [t, setT] = useState(TWEAK_DEFAULTS);
  const set = (patch) => {
    const next = { ...t, ...patch };
    setT(next);
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: patch }, "*");
  };
  return [t, set];
}

/* ---- Hero ---- */
function Hero({ tweaks }) {
  const sectionRef = useRef(null);
  const heroTextRef = useRef(null);
  const dashRef = useRef(null);

  // Parallax via scroll listener (avoiding framer-motion dependency)
  useEffect(() => {
    const onScroll = () => {
      const sec = sectionRef.current;if (!sec) return;
      const rect = sec.getBoundingClientRect();
      const vh = window.innerHeight;
      // progress: 0 at start-start (top of sec at top of viewport) -> 1 at end-start (bottom of sec at top of viewport)
      const total = sec.offsetHeight;
      const scrolled = Math.min(Math.max(-rect.top, 0), total);
      const p = total === 0 ? 0 : scrolled / total;

      if (heroTextRef.current) {
        heroTextRef.current.style.transform = `translateY(${-200 * p}px)`;
        heroTextRef.current.style.opacity = String(Math.max(0, 1 - p * 2));
      }
      if (dashRef.current) {
        dashRef.current.style.transform = `translateY(${-250 * p}px)`;
      }
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const dying = tweaks.avatarState === "dying";

  return (
    <section
      ref={sectionRef}
      data-screen-label="01 Hero"
      style={{
        position: "relative",
        minHeight: "100vh",
        overflow: "hidden",
        paddingBottom: 80
      }}>
      
      {tweaks.showGrid && (
        <div style={{
          position: "absolute", inset: 0, pointerEvents: "none", zIndex: 0, overflow: "hidden",
          maskImage: "radial-gradient(ellipse at 50% 35%, #000 40%, transparent 85%)",
          WebkitMaskImage: "radial-gradient(ellipse at 50% 35%, #000 40%, transparent 85%)",
        }}>
          <video
            autoPlay muted loop playsInline preload="auto"
            style={{
              width: "100%", height: "100%", objectFit: "cover",
              opacity: 0.85, display: "block",
            }}>
            <source src="assets/hero-bg.mp4" type="video/mp4" />
          </video>
          <div style={{
            position: "absolute", inset: 0, pointerEvents: "none",
            background: "radial-gradient(ellipse at center, rgba(0,0,0,0.1) 0%, rgba(0,0,0,0.55) 60%, rgba(0,0,0,0.85) 100%)",
          }}/>
        </div>
      )}

      {/* Navbar */}
      <nav style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "18px clamp(20px, 6vw, 112px)",
        position: "relative", zIndex: 10
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: "clamp(28px, 6vw, 80px)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <LogoMark />
            <span style={{ fontSize: 18, fontWeight: 700, letterSpacing: "-0.02em" }}>OneMoreDay</span>
          </div>
          <div className="navlinks" style={{ display: "flex", gap: 4 }}>
            {["Habits", "Avatar ▾", "Quests", "Pricing"].map((l) =>
            <a key={l} href="#" style={{
              color: "var(--muted)", textDecoration: "none", fontSize: 14, fontWeight: 500,
              padding: "6px 12px", borderRadius: 8
            }}>{l}</a>
            )}
          </div>
        </div>
        <button className="btn-ghost">Sign In</button>
      </nav>

      {/* Hero content */}
      <div
        ref={heroTextRef}
        style={{
          position: "relative", zIndex: 5,
          display: "flex", flexDirection: "column", alignItems: "center",
          textAlign: "center",
          padding: "0 16px", marginTop: 64,
          willChange: "transform, opacity"
        }}>
        
        {/* liquid glass pill */}
        <div className="liquid-glass anim-in delay-0" style={{
          borderRadius: 10, padding: "8px 12px",
          display: "inline-flex", alignItems: "center", gap: 10, marginBottom: 22
        }}>
          <span style={{
            background: "#fff", color: "#000", borderRadius: 6,
            padding: "2px 8px", fontSize: 12, fontWeight: 600, letterSpacing: ".02em"
          }}>New</span>
          <span style={{ fontSize: 13, fontWeight: 500, color: "var(--muted)" }}>
            Avatar v2 · revive tokens & co-op streaks
          </span>
        </div>

        {/* Title */}
        <h1 className="anim-in delay-1" style={{
          fontSize: "clamp(40px, 6.2vw, 88px)",
          fontWeight: 900,
          letterSpacing: "-0.03em",
          lineHeight: 1.02,
          margin: "0 0 14px",
          maxWidth: 1000,
          textWrap: "balance"
        }}>
          {tweaks.heroTitleA} Give your avatar <span className="font-serif" style={{ fontWeight: 400 }}>one more day.</span>
        </h1>

        {/* Subtitle */}
        <p className="anim-in delay-2" style={{
          fontSize: 18, fontWeight: 400, lineHeight: 1.5, opacity: 0.9,
          color: "var(--hero-subtitle)",
          margin: "0 0 28px", maxWidth: 640
        }}>
          OneMoreDay turns your habits into a living voxel companion. Keep<br />
          your streaks, keep them alive. Miss a day, watch them fade.
        </p>

        {/* CTA */}
        <div className="anim-in delay-3" style={{ display: "flex", gap: 12, alignItems: "center" }}>
          <button className="btn-primary">Adopt your avatar</button>
          <a href="#how" style={{
            color: "var(--muted)", textDecoration: "none", fontSize: 14, fontWeight: 500,
            padding: "12px 18px", borderRadius: 999, border: "1px solid var(--border)"
          }}>How it works →</a>
        </div>

        <div style={{
          marginTop: 18, display: "flex", gap: 22, alignItems: "center",
          fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--muted)",
          flexWrap: "wrap", justifyContent: "center"
        }}>
          <span style={{ whiteSpace: "nowrap" }}>◆ 42,318 avatars alive rigtht now</span>
          <span style={{ opacity: 0.5 }}>|</span>
          <span style={{ whiteSpace: "nowrap" }}>◆ Longest streak: 1,204 days</span>
        </div>
      </div>

      {/* Phones cluster (matches real app screens) */}
      <div
        className="anim-in delay-4"
        ref={dashRef}
        style={{
          position: "relative",
          width: "100vw",
          marginLeft: "calc(-50vw + 50%)",
          marginTop: 80,
          paddingBottom: 60,
          willChange: "transform"
        }}>
        
        {/* Amber glow matching Home screen signature */}
        <div className="amber-glow" style={{
          position: "absolute", inset: "-10% 0 0 0", pointerEvents: "none"
        }} />

        <div style={{ position: "relative", zIndex: 2 }}>
          <DashboardMock dying={dying} />
        </div>

        {/* Bottom fade */}
        <div style={{
          position: "absolute", left: 0, right: 0, bottom: 0, height: 120,
          background: "linear-gradient(to top, var(--bg), transparent)",
          zIndex: 3, pointerEvents: "none"
        }} />
      </div>
    </section>);

}

/* ---- Feature strip between hero and testimonial ---- */
function HowItWorks() {
  const items = [
  { n: "01", t: "Adopt a voxel avatar", d: "Pick a chibi companion. Name it. It starts with 100 HP and no memory of a life before you." },
  { n: "02", t: "Feed it with habits", d: "Each habit you complete restores your avatar's life. Each habit you skip drains it." },
  { n: "03", t: "Keep it alive", d: "Break a streak and your avatar dies — voxel by voxel. Hit a streak and it levels up." }];

  return (
    <section id="how" style={{ padding: "120px clamp(20px, 6vw, 112px) 40px", position: "relative" }}>
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "baseline",
        marginBottom: 48, flexWrap: "wrap", gap: 20
      }}>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: ".2em", color: "var(--muted)", textTransform: "uppercase" }}>
          [ how it works ]
        </div>
        <h2 style={{ margin: 0, fontSize: "clamp(28px, 3.5vw, 44px)", fontWeight: 600, letterSpacing: "-0.02em", maxWidth: 640 }}>
          A habit tracker with <span className="font-serif">consequences.</span>
        </h2>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, minmax(0, 1fr))", gap: 1, background: "var(--border)", border: "1px solid var(--border)", borderRadius: 18, overflow: "hidden" }}>
        {items.map((it) =>
        <div key={it.n} style={{ background: "var(--bg)", padding: "32px 28px 40px", minHeight: 260 }}>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--muted)", letterSpacing: ".15em" }}>{it.n}</div>
            <div style={{ marginTop: 20, fontSize: 22, fontWeight: 500, letterSpacing: "-0.01em" }}>{it.t}</div>
            <div style={{ marginTop: 10, color: "var(--muted)", fontSize: 15, lineHeight: 1.55 }}>{it.d}</div>
          </div>
        )}
      </div>
    </section>);

}

/* ---- Testimonial w/ scroll word reveal ---- */
function Testimonial() {
  const containerRef = useRef(null);
  const [progress, setProgress] = useState(0);

  const text = "OneMoreDay is the only tracker that ever scared me into consistency. On day 47 my little voxel guy was on 3 HP and I ran 5k in the rain. I haven't missed a morning since. I'm 203 days in.";
  const words = useMemo(() => text.split(" "), []);

  useEffect(() => {
    const onScroll = () => {
      const el = containerRef.current;if (!el) return;
      const rect = el.getBoundingClientRect();
      const vh = window.innerHeight;
      // "start end" -> "end center"
      const start = vh; // rect.top when section's top hits viewport bottom
      const end = -rect.height + vh / 2; // rect.top when section's bottom hits viewport center
      const p = 1 - (rect.top - end) / (start - end);
      setProgress(Math.min(1, Math.max(0, p)));
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const total = words.length;
  const activeCount = Math.floor(progress * total);

  return (
    <section
      ref={containerRef}
      data-screen-label="03 Testimonial"
      style={{
        minHeight: "100vh",
        padding: "140px clamp(20px, 6vw, 112px)",
        display: "flex", alignItems: "center"
      }}>
      
      <div style={{ maxWidth: 900, margin: "0 auto", display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 40 }}>
        {/* Quote mark — CSS, not an image */}
        <div style={{
          width: 56, height: 40,
          fontFamily: "var(--font-serif)",
          fontSize: 120, lineHeight: 0.7,
          color: "#fff"
        }}>“</div>

        <div style={{
          fontSize: "clamp(28px, 4vw, 52px)",
          fontWeight: 500,
          lineHeight: 1.2,
          letterSpacing: "-0.01em",
          display: "flex", flexWrap: "wrap"
        }}>
          {words.map((w, i) =>
          <span key={i} style={{ marginRight: "0.3em" }}
          className={"reveal-word " + (i < activeCount ? "on" : "")}>
              {w}
            </span>
          )}
          <span style={{ color: "var(--muted)", marginLeft: 8 }}>”</span>
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
          {/* Avatar slot — real OMD voxel avatar */}
          <div style={{
            width: 56, height: 56, borderRadius: 999,
            border: "3px solid #fff",
            background: "radial-gradient(circle at 50% 40%, rgba(255,107,53,0.3), #0c0c0c)",
            display: "grid", placeItems: "center",
            overflow: "hidden"
          }}>
            <img src="assets/avatar.png" alt=""
            style={{ height: 78, width: "auto", objectFit: "contain", transform: "translateY(8px)" }} />
          </div>
          <div>
            <div style={{ fontSize: 16, fontWeight: 600, lineHeight: 1.4 }}>Maya Okafor</div>
            <div style={{ fontSize: 14, fontWeight: 400, lineHeight: 1.4, color: "var(--muted)" }}>
              Day 203 · avatar "Tonic" · LV 19
            </div>
          </div>
        </div>
      </div>
    </section>);

}

/* ---- Footer ---- */
function Footer() {
  return (
    <footer style={{
      borderTop: "1px solid var(--border)",
      padding: "40px clamp(20px, 6vw, 112px)",
      display: "flex", justifyContent: "space-between",
      alignItems: "center", flexWrap: "wrap", gap: 16,
      color: "var(--muted)", fontSize: 13
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <LogoMark />
        <span style={{ color: "#fff", fontWeight: 600, letterSpacing: "-0.02em" }}>OneMoreDay</span>
        <span style={{ marginLeft: 12, fontFamily: "var(--font-mono)", fontSize: 11 }}>onemoreday.fit</span>
      </div>
      <div style={{ display: "flex", gap: 20 }}>
        <a href="#" style={{ color: "var(--muted)", textDecoration: "none" }}>Changelog</a>
        <a href="#" style={{ color: "var(--muted)", textDecoration: "none" }}>Privacy</a>
        <a href="#" style={{ color: "var(--muted)", textDecoration: "none" }}>Download</a>
      </div>
    </footer>);

}

/* ---- Logo mark (tiny voxel icon, CSS only) ---- */
function LogoMark() {
  return (
    <div style={{
      width: 26, height: 26, position: "relative", transformStyle: "preserve-3d",
      display: "inline-block"
    }}>
      <div style={{
        position: "absolute", inset: 0,
        display: "grid",
        gridTemplateColumns: "repeat(3, 1fr)",
        gridTemplateRows: "repeat(3, 1fr)",
        gap: 2
      }}>
        {[1, 1, 0, 1, 1, 1, 0, 1, 0].map((v, i) =>
        <div key={i} style={{
          background: v ? "#fff" : "transparent",
          borderRadius: 2
        }} />
        )}
      </div>
    </div>);

}

/* ---- Tweaks panel ---- */
function Tweaks({ tweaks, set }) {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const handler = (e) => {
      if (e.data?.type === "__activate_edit_mode") setVisible(true);
      if (e.data?.type === "__deactivate_edit_mode") setVisible(false);
    };
    window.addEventListener("message", handler);
    // announce AFTER listener is registered
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", handler);
  }, []);

  if (!visible) return null;
  return (
    <div className="tweaks">
      <h4>Tweaks</h4>
      <label>
        <span>Avatar state</span>
        <select value={tweaks.avatarState} onChange={(e) => set({ avatarState: e.target.value })}>
          <option value="alive">alive</option>
          <option value="dying">dying</option>
        </select>
      </label>
      <label>
        <span>Avatar name</span>
        <input type="text" value={tweaks.avatarName} onChange={(e) => set({ avatarName: e.target.value })} style={{ width: 110 }} />
      </label>
      <label style={{ flexDirection: "column", alignItems: "flex-start" }}>
        <span style={{ color: "var(--muted)", fontSize: 10, letterSpacing: ".1em", textTransform: "uppercase" }}>Hero title line 1</span>
        <input type="text" value={tweaks.heroTitleA} onChange={(e) => set({ heroTitleA: e.target.value })} style={{ width: "100%", marginTop: 4 }} />
      </label>
      <label>
        <span>Grid background</span>
        <input type="checkbox" checked={tweaks.showGrid} onChange={(e) => set({ showGrid: e.target.checked })} />
      </label>
      <button className="row" onClick={() => set({ avatarState: tweaks.avatarState === "alive" ? "dying" : "alive" })}>
        → Toggle avatar state
      </button>
    </div>);

}

/* ---- App ---- */
function App() {
  const [tweaks, set] = useTweaks();
  return (
    <div style={{ background: "var(--bg)" }}>
      <Hero tweaks={tweaks} />
      <HowItWorks />
      <Testimonial />
      <Footer />
      <Tweaks tweaks={tweaks} set={set} />
    </div>);

}

/* Entrance animations via CSS */
const style = document.createElement("style");
style.textContent = `
  .anim-in { opacity: 0; transform: translateY(20px); animation: ain .6s ease forwards; }
  .anim-in.delay-0 { animation-delay: 0s; transform: translateY(10px); animation-duration: .5s; }
  .anim-in.delay-1 { animation-delay: .1s; }
  .anim-in.delay-2 { animation-delay: .2s; }
  .anim-in.delay-3 { animation-delay: .3s; }
  .anim-in.delay-4 { animation-delay: .4s; transform: translateY(40px); animation-duration: .8s; }
  @keyframes ain { to { opacity: 1; transform: translateY(0); } }
  @media (max-width: 720px) {
    .navlinks { display: none !important; }
  }
`;
document.head.appendChild(style);

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