/* global React, Button, BracketLabel, MonoMeta, GenerativeArt, Reveal, Counter, SectionHead */

const PROJECTS = [
  { id: "01", slug: "case-01", title: "Droplet", italic: "Droplet", sub: ["UX research", "iOS native", "Brand identity"], year: "2025", art: "droplet" },
  { id: "02", slug: "case-02", title: "Forage", italic: "Forage", sub: ["UX research", "iOS native", "Local discovery"], year: "2026", art: "lines" },
  { id: "03", slug: "case-03", title: "Ember & Oak", italic: "& Oak", sub: ["Freelance", "Identity"], year: "2025", art: "rings" },
];

window.PROJECTS = PROJECTS;

// ---------- Hero waves (canvas) ----------
// Previous hero-bg: SVG turbulence blobs. Preserved below if revert is needed.
// <div className="hero-bg" aria-hidden="true" style={{ position:"absolute",inset:0,zIndex:0,
//   pointerEvents:"none",opacity:0.42,mixBlendMode:"screen",filter:"contrast(1.05) saturate(0)",
//   animation:"heroDrift 40s cubic-bezier(0.65,0,0.35,1) infinite" }}>
//   <svg viewBox="0 0 1600 900" ...> ... </svg>
// </div>
function HeroWaves() {
  const canvasRef = React.useRef(null);
  const stateRef = React.useRef({ t: 0, birds: null });

  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    let rafId;

    stateRef.current.birds = [
      { xFrac: 0.28, yFrac: 0.24, dx: -0.000035, wingPhase: 0.0,            wingSpeed: 0.022, size: 9,  alpha: 0.30 },
      { xFrac: 0.62, yFrac: 0.30, dx: -0.000024, wingPhase: Math.PI * 0.65, wingSpeed: 0.016, size: 6,  alpha: 0.22 },
    ];

    const LAYERS = [
      { baseYFrac: 0.82, alpha: 0.085, waves: [{ A: 34, f: 0.0030, s: 0.00060, p: 0.00 }, { A: 18, f: 0.0072, s: 0.00040, p: 1.20 }, { A: 10, f: 0.0131, s: 0.00025, p: 2.50 }] },
      { baseYFrac: 0.70, alpha: 0.068, waves: [{ A: 27, f: 0.0035, s: 0.00050, p: 0.80 }, { A: 15, f: 0.0077, s: 0.00035, p: 2.10 }, { A: 8,  f: 0.0140, s: 0.00022, p: 4.00 }] },
      { baseYFrac: 0.58, alpha: 0.052, waves: [{ A: 21, f: 0.0040, s: 0.00040, p: 1.50 }, { A: 12, f: 0.0082, s: 0.00028, p: 0.50 }, { A: 6,  f: 0.0150, s: 0.00018, p: 3.20 }] },
      { baseYFrac: 0.46, alpha: 0.038, waves: [{ A: 14, f: 0.0045, s: 0.00030, p: 2.20 }, { A: 8,  f: 0.0090, s: 0.00022, p: 1.00 }, { A: 4,  f: 0.0160, s: 0.00014, p: 4.80 }] },
    ];

    function resize() {
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      canvas.width  = Math.round(canvas.offsetWidth  * dpr);
      canvas.height = Math.round(canvas.offsetHeight * dpr);
    }
    resize();

    let ro;
    try { ro = new ResizeObserver(resize); ro.observe(canvas); }
    catch (_) { window.addEventListener("resize", resize); }

    function frame() {
      const { t, birds } = stateRef.current;
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      const w = canvas.offsetWidth;
      const h = canvas.offsetHeight;

      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.save();
      ctx.scale(dpr, dpr);

      for (const layer of LAYERS) {
        ctx.save();
        ctx.globalAlpha = layer.alpha;
        ctx.fillStyle = "#fff";
        ctx.beginPath();
        ctx.moveTo(0, h);
        for (let x = 0; x <= w; x += 4) {
          let y = layer.baseYFrac * h;
          for (const wv of layer.waves) y += wv.A * Math.sin(wv.f * x + t * wv.s + wv.p);
          ctx.lineTo(x, y);
        }
        ctx.lineTo(w, h);
        ctx.closePath();
        ctx.fill();
        ctx.restore();
      }

      for (const bird of birds) {
        bird.xFrac += bird.dx;
        bird.wingPhase += bird.wingSpeed;
        if (bird.xFrac < -0.12) bird.xFrac = 1.12;
        const px = bird.xFrac * w;
        const py = bird.yFrac * h;
        const s  = bird.size;
        const wb = Math.sin(bird.wingPhase) * s * 0.58 + s * 0.14;
        ctx.save();
        ctx.globalAlpha = bird.alpha;
        ctx.strokeStyle = "#fff";
        ctx.lineWidth   = s > 7 ? 1.6 : 1.2;
        ctx.lineCap     = "round";
        ctx.lineJoin    = "round";
        ctx.beginPath();
        ctx.moveTo(px - s, py);
        ctx.quadraticCurveTo(px - s * 0.46, py - wb, px, py + s * 0.15);
        ctx.quadraticCurveTo(px + s * 0.46, py - wb, px + s, py);
        ctx.stroke();
        ctx.restore();
      }

      ctx.restore();
      stateRef.current.t++;
      rafId = requestAnimationFrame(frame);
    }

    frame();
    return () => {
      cancelAnimationFrame(rafId);
      if (ro) ro.disconnect(); else window.removeEventListener("resize", resize);
    };
  }, []);

  return (
    <canvas ref={canvasRef} aria-hidden="true" style={{
      position: "absolute", inset: 0, width: "100%", height: "100%",
      display: "block", zIndex: 0, pointerEvents: "none",
      mixBlendMode: "screen", opacity: 0.88,
      filter: "contrast(1.05) saturate(0)",
    }} />
  );
}

// ---------- Hero ----------
function Hero({ tweaks }) {
  const layout = tweaks.heroLayout;
  return (
    <section className="hero" data-layout={layout} data-screen-label="01 Hero">
      <HeroWaves />
      <div className="hero-inner">
        <div className="hero-eye">
          <span>Portfolio</span>
          <span className="dot-sep">·</span>
          <span>Vol. 01</span>
          <span className="dot-sep">·</span>
          <span>Fort Worth, Texas</span>
        </div>
        {layout === "split" ? (
          <>
            <h1 className="hero-title">
              Jaeden Thai<br />is a <span className="serif-it">creator</span>
            </h1>
            <div>
              <p className="hero-sub" style={{ marginBottom: 32 }}>
                A junior designer with an emphasis on <em>brand identity</em>, about to start at Funsize in Austin. Freelancing and quietly building a practice out of Fort Worth.
              </p>
              <div className="hero-actions">
                <Button variant="primary" icon onClick={() => window.location.hash = "#case-01"}>Selected work</Button>
                <Button variant="outline" onClick={() => window.location.hash = "#about"}>About the desk</Button>
              </div>
            </div>
          </>
        ) : (
          <>
            <h1 className="hero-title">
              Jaeden Thai<br />is a <span className="serif-it">creator</span>
            </h1>
            <p className="hero-sub">
              A junior designer with an emphasis on <em>brand identity</em>, about to start at Funsize in Austin. Freelancing and quietly building a practice out of Fort Worth, Texas.
            </p>
            <div className="hero-actions">
              <Button variant="primary" icon onClick={() => window.location.hash = "#case-01"}>Selected work</Button>
              <Button variant="outline" onClick={() => window.location.hash = "#about"}>About the desk</Button>
            </div>
          </>
        )}
        <div className="hero-bottom">
          <span>↓ scroll on</span>
          <span>Three projects, selected</span>
        </div>
      </div>
      <div className="hero-marquee">
        <div className="marquee-track">
          {[...Array(2)].map((_, k) => (
            <React.Fragment key={k}>
              <span>Brand identity</span><span className="dot">●</span>
              <span className="serif-it">building in public</span><span className="dot">●</span>
              <span>AI + design</span><span className="dot">●</span>
              <span className="serif-it">done with care</span><span className="dot">●</span>
              <span>Systems thinking</span><span className="dot">●</span>
              <span className="serif-it">photography on the side</span><span className="dot">●</span>
              <span>Open for summer 2026</span><span className="dot">●</span>
            </React.Fragment>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- Status row ----------
function StatusRow() {
  return (
    <div className="status-row">
      <div className="status-cell">
        <span className="label">Status</span>
        <span className="value"><span className="available-dot" />Open · summer 2026</span>
      </div>
      <div className="status-cell">
        <span className="label">Currently</span>
        <span className="value">Joining Funsize, Austin</span>
      </div>
      <div className="status-cell">
        <span className="label">Learning</span>
        <span className="value">AI tools <em>&</em> design</span>
      </div>
      <div className="status-cell">
        <span className="label">Focus</span>
        <span className="value">Brand <em>&</em> product</span>
      </div>
    </div>
  );
}

// ---------- Project card ----------
function ProjectCard({ p, navigate }) {
  return (
    <a className="project-card" onClick={(e) => { e.preventDefault(); navigate(p.slug); }} href={"#" + p.slug}>
      <div className="card-bg"><GenerativeArt seed={parseInt(p.id) * 17} variant={p.art} /></div>
      <div className="grain-overlay" />
      <div className="pc-top">
        <span className="pc-num">{p.id}</span>
        <span className="pc-yr">{p.year}</span>
      </div>
      <div className="pc-bottom">
        <h3 className="pc-title">
          {(() => { const first = p.title.replace(p.italic, "").trim(); return <>{first}<em>{first ? " " : ""}{p.italic}</em></>; })()}
        </h3>
        <span className="pc-tags">
          {p.sub.map((s, i) => <span key={i}>{s}</span>)}
        </span>
      </div>
      <div className="pc-arrow">→</div>
    </a>
  );
}

// ---------- Works ----------
function Works({ tweaks, navigate }) {
  return (
    <section className="works" data-screen-label="02 Selected Works">
      <div className="section-head">
        <h2 className="section-title">Selected <em>work</em></h2>
        <span className="mono-meta">Three · early projects</span>
      </div>
      <Reveal as="div">
        <div className="works-grid" data-cols={tweaks.gridCols}>
          {PROJECTS.map(p => <ProjectCard key={p.id} p={p} navigate={navigate} />)}
        </div>
      </Reveal>
    </section>
  );
}

// ---------- Process (home) ----------
const STEPS = [
  { num: "01", step: "Listen", desc: "I read everything I can find. I ask the questions that probably sound obvious. I try to understand the problem before I fall in love with a solution.", deliver: "Notes · sketches · questions" },
  { num: "02", step: "Sketch", desc: "On paper, in Figma, sometimes both. The ideas I keep usually arrive on the third or fourth round, not the first.", deliver: "Wireframes · prototypes" },
  { num: "03", step: "Share", desc: "Critique, hand-off, revise. I want feedback on the messy parts, not just the polished ones. That's where the learning is.", deliver: "Crit · hand-off · iterate" },
];

function ProcessHome() {
  return (
    <section className="section" data-screen-label="03 Process" style={{ padding: "96px 0 0" }}>
      <div className="section-head">
        <h2 className="section-title">How I'm <em>learning to work</em></h2>
        <span className="mono-meta">Three movements</span>
      </div>
      <ol className="process-list">
        {STEPS.map((s) => (
          <li key={s.num}>
            <span className="p-num">{s.num}</span>
            <span className="p-step"><em>{s.step}</em></span>
            <span className="p-desc">{s.desc}</span>
            <span className="p-deliver">{s.deliver}</span>
          </li>
        ))}
      </ol>
    </section>
  );
}

// ---------- CTA ----------
function HomeCTA({ navigate }) {
  return (
    <section className="cta" data-screen-label="04 CTA">
      <div className="cta-grain" />
      <div className="cta-inner">
        <BracketLabel style={{ marginBottom: 24, display: "inline-flex" }}>An invitation</BracketLabel>
        <h2 className="cta-title">Let's make<br />something <em>together</em></h2>
        <p className="cta-sub">
          I'm open to internships, freelance briefs, mentorship conversations, or coffee. If something seems like a fit, I'd love to hear about it.
        </p>
        <div className="cta-actions">
          <Button variant="primary" icon onClick={() => window.location.href = "mailto:hello@jaedenthai.studio"}>Start a conversation</Button>
          <Button variant="outline" onClick={() => navigate("resume")}>Read the resume</Button>
        </div>
      </div>
    </section>
  );
}

function HomePage({ tweaks, navigate }) {
  return (
    <div className="page-enter">
      <Hero tweaks={tweaks} />
      <StatusRow />
      <Works tweaks={tweaks} navigate={navigate} />
      <ProcessHome />
      <HomeCTA navigate={navigate} />
    </div>
  );
}

window.HomePage = HomePage;
