/* zt-home.jsx — Landing page, wired to CMS content (window.JAKOB_CONTENT / JAKOB_PROJECTS) */
const { useState: useStateH, useEffect: useEffectH } = React;

const HERO_IMG = "assets/images/no background_v2.png"; // same portrait as the previous site
const isVideoSrc = (s) => typeof s === "string" && /\.(mp4|mov|webm)(\?|$)/i.test(s);
const catLabel = (c) => (c ? c.charAt(0).toUpperCase() + c.slice(1) : "");

function CoverMedia({ src }) {
  const style = { position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", display: "block" };
  if (!src) return null;
  return isVideoSrc(src)
    ? <video src={src} autoPlay muted loop playsInline preload="metadata" style={style} />
    : <img src={src} alt="" style={style} />;
}

function HomeRoles() {
  const L = (window.JAKOB_CONTENT && window.JAKOB_CONTENT.landing) || {};
  const phrases = (L.introPhrases && L.introPhrases.length) ? L.introPhrases
    : [{ text: "a designer," }, { text: "creative developer," }, { text: "and everything else" }];

  const [inView, setInView] = useStateH(false);
  const [charCount, setCharCount] = useStateH(0);
  const ref = React.useRef(null);

  useEffectH(() => {
    const el = ref.current;
    if (!el || typeof IntersectionObserver === "undefined") { setInView(true); return; }
    const obs = new IntersectionObserver(
      ([e]) => { if (e.isIntersecting) { setInView(true); obs.disconnect(); } },
      { threshold: 0.25 }
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, []);

  const firstText = phrases[0] ? phrases[0].text : "";
  useEffectH(() => {
    if (!inView || charCount >= firstText.length) return;
    const id = setTimeout(() => setCharCount((c) => c + 1), 38);
    return () => clearTimeout(id);
  }, [inView, charCount, firstText]);

  return (
    <section className="home-roles" ref={ref}>
      <div className="rolewrap">
        <div>
          {firstText.slice(0, charCount)}
          {inView && charCount < firstText.length && <span className="roles-cursor" />}
        </div>
        <div style={inView
          ? { animation: "roles-slide-up 0.8s cubic-bezier(.16,1,.3,1) 1.4s both" }
          : { opacity: 0 }}>
          {phrases[1] ? phrases[1].text : ""}
        </div>
        <div style={{ color: "var(--decor)", ...(inView
          ? { animation: "roles-slam-in 0.75s cubic-bezier(.2,.8,.2,1) 2.8s both" }
          : { opacity: 0 }) }}>
          {phrases[2] ? phrases[2].text : ""}
        </div>
      </div>
    </section>
  );
}

function HomeHero() {
  const L = (window.JAKOB_CONTENT && window.JAKOB_CONTENT.landing) || {};
  const heroLines = L.heroLines && L.heroLines.length ? L.heroLines : ["A Jakob of", "all trades."];
  const heroSub = L.heroSub || "Better than a master of one.";
  return (
    <React.Fragment>
      <section className="home-hero">
        <div className="home-portrait">
          <div className="ph" />
          <img src={HERO_IMG} alt="Jakob Visic" draggable={false} />
        </div>
        <div className="home-hero-copy">
          <h1 className="display">
            {heroLines.map((line, idx) => (
              <React.Fragment key={idx}>{idx > 0 && <br />}{line}</React.Fragment>
            ))}
          </h1>
          <div className="sub">{heroSub}</div>
        </div>
        <div className="scrollcue anim-nudge-y" style={{ fontFamily: '"IBM Plex Mono", monospace', fontSize: 10, fontWeight: 600, letterSpacing: ".22em", textTransform: "uppercase" }}>↓ Scroll</div>
      </section>
      <HomeRoles />
    </React.Fragment>
  );
}

function WhatIMake() {
  const L = (window.JAKOB_CONTENT && window.JAKOB_CONTENT.landing) || {};
  const heading = L.featuredHeading || "What I make";
  const projects = (window.JAKOB_PROJECTS || []).filter((p) => !p.hidden).slice(0, 4);
  return (
    <section className="wrap section">
      <div className="featured-head">
        <div className="reveal">
          <div className="eyebrow" style={{ marginBottom: 14 }}><Chevron size={11} sw={3} style={{ transform: "rotate(90deg)" }} /> SELECTED / 01</div>
          <h2 className="display">{heading}</h2>
        </div>
        <a className="featured-link reveal" href="portfolio.html">All projects <ArrowUR size={13} /></a>
      </div>
      <div className="featured-grid">
        {projects.map((p, idx) => {
          const thumb = p.thumb || {};
          return (
            <a className="work-card reveal" key={p.key || idx} href={`project.html?key=${encodeURIComponent(p.key)}`} style={{ animationDelay: (idx * 0.05) + "s" }}>
              <div className="thumb" style={{ background: thumb.bg || "var(--bg)" }}>
                <Brackets />
                <span className="open-tag"><ArrowUR size={14} /></span>
                {p.cover
                  ? <CoverMedia src={p.cover} />
                  : <span className="ph" style={thumb.dark ? { color: "rgba(255,255,255,.7)" } : null}>[ {thumb.label || p.title} ]<br/>DROP IMAGE</span>}
              </div>
              <div className="wmeta">
                <div className="wtitle">{p.title}</div>
                <div className="wcat">{(p.categories || []).map(catLabel).join(" · ")}</div>
              </div>
            </a>
          );
        })}
      </div>
    </section>
  );
}

function Logos() {
  const L = (window.JAKOB_CONTENT && window.JAKOB_CONTENT.landing) || {};
  const logos = (L.clientLogos || []).filter((l) => l && l.src);
  if (!logos.length) return null;
  const loop = [...logos, ...logos]; // duplicate for a seamless loop
  const duration = Math.max(24, logos.length * 6);
  const edgeFade = "linear-gradient(to right, transparent 0, #000 6%, #000 94%, transparent 100%)";
  return (
    <section className="wrap">
      <div className="logos" style={{ display: "block" }}>
        <span className="logos-lbl">↳ Worked with</span>
        <div className="logo-marquee" style={{ overflow: "hidden", marginTop: 18, maskImage: edgeFade, WebkitMaskImage: edgeFade }}>
          <style>{`
            @keyframes logo-marquee-rtl { from { transform: translateX(0); } to { transform: translateX(-50%); } }
            .logo-marquee-track { animation: logo-marquee-rtl ${duration}s linear infinite; }
            .logo-marquee:has(.logo-marquee-item:hover) .logo-marquee-track { animation-play-state: paused; }
          `}</style>
          <div className="logo-marquee-track" style={{ display: "flex", alignItems: "center", width: "max-content", gap: "clamp(80px, 14vw, 192px)", paddingLeft: "clamp(80px, 14vw, 192px)" }}>
            {loop.map((l, i) => (
              <a className="logo-marquee-item" key={i} href={l.url || undefined} target={l.url ? "_blank" : undefined} rel="noopener noreferrer" title={l.name || ""} style={{ display: "flex", alignItems: "center" }}>
                <img src={l.src} alt={l.name || ""} draggable={false}
                     style={{ height: "clamp(52px, 6.4vw, 88px)", width: "auto", maxWidth: 340, objectFit: "contain", display: "block", filter: "grayscale(1)", opacity: 0.55, transition: "filter .25s, opacity .25s" }}
                     onMouseEnter={(e) => { e.currentTarget.style.filter = "grayscale(0)"; e.currentTarget.style.opacity = "1"; }}
                     onMouseLeave={(e) => { e.currentTarget.style.filter = "grayscale(1)"; e.currentTarget.style.opacity = "0.55"; }} />
              </a>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function Recommendations() {
  const L = (window.JAKOB_CONTENT && window.JAKOB_CONTENT.landing) || {};
  const heading = L.testimonialsHeading || "Recommendations";
  const recs = L.testimonials || [];
  return (
    <section className="wrap section">
      <div className="tk-head" style={{ marginBottom: "clamp(24px,3vw,40px)" }}>
        <div className="reveal">
          <div className="eyebrow" style={{ marginBottom: 14 }}><Chevron size={11} sw={3} style={{ transform: "rotate(90deg)" }} /> SIGNAL / 02</div>
          <h2 className="display">{heading}</h2>
        </div>
        <div className="tk-desc reveal">From the people I've worked with.</div>
      </div>
      <div className="rec-grid">
        {recs.map((r, idx) => (
          <div className="rec-card reveal" key={idx}>
            <div className="qmark">{'"'}</div>
            <p className="qt">{r.quote}</p>
            <div className="qmark qmark-close">{'"'}</div>
            {r.byUrl
              ? <a className="who" href={r.byUrl} target="_blank" rel="noopener noreferrer" style={{ textDecoration: "none", color: "inherit" }}>{r.by}<ArrowUR size={11} style={{ display: "inline-block", marginLeft: 4, verticalAlign: "middle", color: "var(--accent)" }} /></a>
              : <div className="who">{r.by}</div>}
            {r.companyUrl
              ? <a className="role" href={r.companyUrl} target="_blank" rel="noopener noreferrer" style={{ textDecoration: "none", color: "inherit" }}>{r.role}<ArrowUR size={10} style={{ display: "inline-block", marginLeft: 4, verticalAlign: "middle", color: "var(--accent)", opacity: .7 }} /></a>
              : <div className="role">{r.role}</div>}
          </div>
        ))}
      </div>
    </section>
  );
}

function HomeCTA({ halftone, wild }) {
  const L = (window.JAKOB_CONTENT && window.JAKOB_CONTENT.landing) || {};
  const btnLabel = L.ctaButtonLabel || "Let's work together";
  const email = L.ctaEmail || "jakob.visic@gmail.com";
  return (
    <section className="cta">
      {halftone && <div className="cta-halftone" />}
      <div className="cta-chev"><ChevStack n={4} size={120} /></div>
      <div className="wrap section">
        <div className="cta-sub"><Reg /> NEW GAME · INSERT IDEA</div>
        <h2 className="display">Got a <span className="wild" data-wild={wild}>wild</span><br/>idea?</h2>
        <div className="cta-sub" style={{ marginTop: 26, marginBottom: 30 }}><span className="blink">▸</span> PRESS START</div>
        <a className="cta-btn" href={`mailto:${email}`}>
          <span style={{ width: 6, height: 6, borderRadius: 9, background: "currentColor" }} />
          {btnLabel}
          <ArrowUR size={15} />
        </a>
      </div>
    </section>
  );
}

function HomePage() {
  return (
    <Shell active="home" doc="DOC // INDEX.0x00">
      {({ t }) => (
        <React.Fragment>
          <HomeHero />
          <WhatIMake />
          <Logos />
          <Recommendations />
          <HomeCTA halftone={t.halftone} wild={t.wildAnim} />
        </React.Fragment>
      )}
    </Shell>
  );
}

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