/* global React, ReactDOM, useReveal, Nav, Footer, StatsStrip, TeamImage, IMAGES, JOBS, ArrowRight, ArrowUpRight, MAIL, ScrollSpinner, ApplicationModal, ContactModal, PageBackdrop, Parallax */
const { useEffect, useRef } = React;

function openApply(role = '') {
  window.dispatchEvent(new CustomEvent('open-apply', { detail: { role } }));
}

// Full-page canvas backdrop — covers entire document height, drawn ONCE.
// The same curve flows from top (hero) all the way to the bottom of the page.
// Stars/dune fill only the top viewport-height (hero area); below, just the continuing curve.
function HeroDark() {
  const canvasRef = useRef(null);
  const wrapRef = useRef(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    const wrap = wrapRef.current;
    if (!canvas || !wrap) return;

    function draw() {
      const heroH = window.innerHeight;
      const W = wrap.clientWidth;
      const H = Math.max(wrap.clientHeight, heroH);
      if (W <= 0 || H <= 0) return;
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      canvas.width = W * dpr;
      canvas.height = H * dpr;
      canvas.style.width = W + 'px';
      canvas.style.height = H + 'px';
      const ctx = canvas.getContext('2d');
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);

      // Pure black fills the whole document
      ctx.fillStyle = '#040404';
      ctx.fillRect(0, 0, W, H);

      let s = 987654321;
      const rand = () => { s = (s * 1103515245 + 12345) & 0x7fffffff; return s / 0x7fffffff; };

      // Continuous crest: t parametrised so t=0..1 covers the hero height,
      // and t > 1 continues the SAME curve down through the rest of the page.
      const samples = Math.max(800, Math.round(H / 3));
      const crest = [];
      for (let i = 0; i < samples; i++) {
        const y = (i / (samples - 1)) * H;
        const tGlobal = y / heroH;
        const x = W * 0.46
                + Math.sin(tGlobal * Math.PI * 0.95) * W * 0.10
                - Math.sin(tGlobal * Math.PI * 1.9 + 0.4) * W * 0.07;
        crest.push([x, y]);
      }

      // Sparse starfield — only inside the hero viewport, so below the fold stays clean
      const starCount = Math.round((W * heroH) / 1900);
      for (let i = 0; i < starCount; i++) {
        const x = rand() * W;
        const y = rand() * heroH;
        const idx = Math.min(samples - 1, Math.max(0, Math.round((y / H) * (samples - 1))));
        const crestX = crest[idx][0];
        if (x > crestX - 4) continue;
        const distToEdge = crestX - x;
        if (distToEdge < 40 && rand() > distToEdge / 40) continue;
        const r = rand() * 0.7 + 0.22;
        const op = rand() * 0.35 + 0.10;
        ctx.fillStyle = `rgba(255,255,255,${op.toFixed(3)})`;
        ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill();
      }

      // Solid dune silhouette — only in the hero portion (right side)
      ctx.save();
      ctx.beginPath();
      ctx.rect(0, 0, W, heroH);
      ctx.clip();
      ctx.fillStyle = '#040404';
      ctx.beginPath();
      ctx.moveTo(crest[0][0], crest[0][1]);
      for (let i = 1; i < crest.length && crest[i][1] <= heroH; i++) ctx.lineTo(crest[i][0], crest[i][1]);
      ctx.lineTo(W + 50, heroH); ctx.lineTo(W + 50, 0); ctx.closePath(); ctx.fill();
      ctx.restore();

      // Rim grain along the WHOLE crest — consistent density top to bottom
      const RIM_SPREAD = Math.min(180, W * 0.10);
      for (let i = 0; i < crest.length; i++) {
        const [cx, cy] = crest[i];
        const prev = crest[Math.max(0, i - 1)];
        const next = crest[Math.min(crest.length - 1, i + 1)];
        const tx = next[0] - prev[0], ty = next[1] - prev[1];
        const tlen = Math.hypot(tx, ty) || 1;
        const nx = -ty / tlen, ny = tx / tlen;
        const lefting = nx < 0 ? 1 : -1;
        const cluster = Math.floor(rand() * 6 + 8);
        for (let j = 0; j < cluster; j++) {
          const u = rand();
          const offset = Math.pow(u, 1.5) * RIM_SPREAD;
          const x = cx + nx * offset * lefting;
          const y = cy + ny * offset * lefting + (rand() - 0.5) * 4;
          const op = (1 - u) * (rand() * 0.5 + 0.45);
          if (op < 0.04) continue;
          const r = rand() * 0.55 + 0.22;
          ctx.fillStyle = `rgba(255,255,255,${op.toFixed(3)})`;
          ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill();
        }
      }

      // Full-length continuous line — soft halo + crisp highlight all the way down
      ctx.save();
      ctx.filter = 'blur(5px)';
      ctx.strokeStyle = 'rgba(255,255,255,0.30)';
      ctx.lineWidth = 2.4;
      ctx.beginPath();
      ctx.moveTo(crest[0][0], crest[0][1]);
      for (let i = 1; i < crest.length; i++) ctx.lineTo(crest[i][0], crest[i][1]);
      ctx.stroke();
      ctx.restore();

      ctx.strokeStyle = 'rgba(255,255,255,0.55)';
      ctx.lineWidth = 0.8;
      ctx.beginPath();
      ctx.moveTo(crest[0][0], crest[0][1]);
      for (let i = 1; i < crest.length; i++) ctx.lineTo(crest[i][0], crest[i][1]);
      ctx.stroke();
    }

    draw();
    const onResize = () => draw();
    window.addEventListener('resize', onResize);
    let ro;
    if (typeof ResizeObserver !== 'undefined') {
      ro = new ResizeObserver(() => draw());
      ro.observe(document.body);
    }
    const t1 = setTimeout(draw, 250);
    const t2 = setTimeout(draw, 900);

    // Scroll parallax — translate the wrap vertically so the line moves slower than content
    let raf;
    const tickScroll = () => {
      if (wrap) wrap.style.transform = `translate3d(0, ${window.scrollY * 0.18}px, 0)`;
      raf = requestAnimationFrame(tickScroll);
    };
    raf = requestAnimationFrame(tickScroll);

    return () => {
      window.removeEventListener('resize', onResize);
      if (ro) ro.disconnect();
      clearTimeout(t1); clearTimeout(t2);
      cancelAnimationFrame(raf);
    };
  }, []);

  return (
    <>
      <div ref={wrapRef} className="page-backdrop" aria-hidden="true">
        <canvas ref={canvasRef} className="page-backdrop-canvas"/>
      </div>
      <section className="hero-dark min-h-[100vh] flex">
        <div className="relative z-10 w-full max-w-[1280px] mx-auto px-6 md:px-10 flex items-center">
          <div className="w-full">
            <h1 className="reveal hero-headline text-white">
              Crafting the Future of<br/>
              Digital Habits and Wellbeing
            </h1>
            <p className="reveal mt-6 md:mt-8 text-[15px] md:text-[17px] max-w-[440px]" style={{ color: 'rgba(255,255,255,0.65)', fontWeight: 400 }}>
              We create world-class digital wellness, wellbeing, and AI tools for people everywhere
            </p>
            <div className="reveal mt-10">
              <button onClick={() => openApply('')} className="btn-pill">
                Join us
                <span className="icon-mark">
                  <svg width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 1.5v9M1.5 6h9"/></svg>
                </span>
              </button>
            </div>
          </div>
        </div>
      </section>
    </>
  );
}

// PageLine — no-op now; the hero canvas covers the whole document.
function PageLine() { return null; }

function ImageTextBlock({ titleRegular, titleBold, body, img, alt, reverse = false }) {
  return (
    <section className="max-w-[1280px] mx-auto px-6 md:px-10 py-14 md:py-20">
      <div className="reveal grid md:grid-cols-12 gap-10 md:gap-16 items-center">
        <div className={`md:col-span-6 ${reverse ? 'md:order-2' : ''}`}>
          <Parallax speed={0.04}>
            <TeamImage src={img} alt={alt} ratio="4/5" parallax={0.04}/>
          </Parallax>
        </div>
        <div className={`md:col-span-6 ${reverse ? 'md:order-1' : ''}`}>
          <Parallax speed={-0.04}>
            <h2 className="h-display text-[40px] sm:text-[56px] md:text-[80px] lg:text-[96px]" style={{ lineHeight: 0.96 }}>
              <span className="block" style={{ fontWeight: 500 }}>{titleRegular}</span>
              <span className="block" style={{ fontWeight: 700 }}>{titleBold}</span>
            </h2>
          </Parallax>
          <Parallax speed={-0.02}>
            <p className="mt-8 md:mt-10 text-[16px] md:text-[17px] leading-[1.6] max-w-[480px]" style={{ color: 'var(--ink-2)' }}>
              {body}
            </p>
          </Parallax>
        </div>
      </div>
    </section>
  );
}

function CategoriesCard() {
  const items = [
    { label: 'Digital', icon: (
      <svg width="34" height="34" viewBox="0 0 32 32" fill="none" stroke="currentColor" strokeWidth="1.4">
        <rect x="4" y="6" width="24" height="16" rx="1.5"/>
        <path d="M4 19h24M12 26h8M14 22v4M18 22v4"/>
      </svg>
    )},
    { label: 'Wellness', icon: (
      <svg width="34" height="34" viewBox="0 0 32 32" fill="none" stroke="currentColor" strokeWidth="1.4">
        <path d="M16 26c-6-2-10-7-10-13a4 4 0 016-3.46A4 4 0 0118 9.54 4 4 0 0126 13c0 6-4 11-10 13z"/>
        <path d="M11 14c1.5 1 2.5 2 5 2s3.5-1 5-2"/>
      </svg>
    )},
    { label: 'Books', icon: (
      <svg width="34" height="34" viewBox="0 0 32 32" fill="none" stroke="currentColor" strokeWidth="1.4">
        <path d="M6 8c3 0 7 1 10 3v15c-3-2-7-3-10-3V8z"/>
        <path d="M26 8c-3 0-7 1-10 3v15c3-2 7-3 10-3V8z"/>
      </svg>
    )},
    { label: 'AI Tech', icon: (
      <svg width="34" height="34" viewBox="0 0 32 32" fill="none" stroke="currentColor" strokeWidth="1.4">
        <rect x="9" y="9" width="14" height="14" rx="2"/>
        <path d="M16 5v4M16 23v4M5 16h4M23 16h4M11 5v4M21 5v4M11 23v4M21 23v4M5 11h4M5 21h4M23 11h4M23 21h4"/>
        <circle cx="16" cy="16" r="2.5" fill="currentColor" stroke="none"/>
      </svg>
    )},
  ];
  return (
    <section className="section-lavender">
      <div className="max-w-[1280px] mx-auto px-6 md:px-10 py-12 md:py-16">
        <div className="reveal bg-white rounded-[28px] p-7 md:p-12 relative overflow-hidden">
          {/* 4 category badges */}
          <div className="reveal-stagger grid grid-cols-2 md:grid-cols-4 gap-2">
            {items.map((it, i) => (
              <div key={i} className="category-card relative">
                <div className="icon-badge mx-auto">{it.icon}</div>
                <div className="mt-6 text-[18px] md:text-[22px]" style={{ fontWeight: 600, letterSpacing: '-0.02em' }}>{it.label}</div>
              </div>
            ))}
          </div>

          {/* Divider + paragraph + button */}
          <div className="border-t mt-10 md:mt-14 pt-10 md:pt-14 grid md:grid-cols-12 gap-8 items-end" style={{ borderColor: 'var(--line)' }}>
            <p className="md:col-span-8 text-[17px] md:text-[22px] leading-[1.45]" style={{ color: 'var(--ink-2)', letterSpacing: '-0.005em' }}>
              We offer rare opportunities, drawing top talent to join our rapidly growing team and launching innovative brands in a fast-expanding digital wellness industry. If you're bold, ambitious, and ready to push your limits, let's talk.
            </p>
            <div className="md:col-span-4 md:flex md:justify-end">
              <button onClick={() => openApply('')} className="btn-pill btn-pill-dark">
                Join us
                <span className="icon-mark">
                  <svg width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 1.5v9M1.5 6h9"/></svg>
                </span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function JoinMissionCTA() {
  return (
    <section className="bg-white relative overflow-hidden">
      <div className="tech-grid"/>
      <div className="max-w-[1280px] mx-auto px-6 md:px-10 py-14 md:py-20 relative">
        <div className="reveal grid md:grid-cols-12 gap-10 items-end">
          <div className="md:col-span-7">
            <Parallax speed={-0.04}>
              <h2 className="h-display text-[48px] sm:text-[64px] md:text-[88px] lg:text-[104px]" style={{ lineHeight: 0.98, fontWeight: 700 }}>
                Join our mission!
              </h2>
            </Parallax>
            <p className="mt-6 text-[17px] md:text-[20px]" style={{ color: 'var(--ink-2)' }}>
              Shape the future of digital wellness &amp; wellbeing with us.
            </p>
          </div>
          <div className="md:col-span-5 md:flex md:justify-end">
            <a href="careers.html#positions" className="btn-pill btn-pill-dark" style={{ padding: '18px 28px' }}>
              See positions
              <span className="icon-mark" style={{ background: 'transparent', border: '1px solid rgba(255,255,255,0.3)' }}>
                <ArrowUpRight size={11}/>
              </span>
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}

function HomePage() {
  useReveal();
  useEffect(() => {
    document.body.classList.add('home-active');
    return () => document.body.classList.remove('home-active');
  }, []);
  return (
    <div className="home-page">
      <Nav activePage="home" openCount={JOBS.length} theme="dark" />
      <PageLine/>
      <main>
        <HeroDark />
        <StatsStrip />

        <section className="section-lavender">
          <ImageTextBlock
            titleRegular="From bold idea to"
            titleBold="Global frontrunners"
            body="From the very beginning, we were driven by a clear vision — to build transformative digital wellness and AI tools for the people who need them. Today, we're a globally recognized company delivering high-quality products that help people live happier, more balanced, and more productive lives."
            img={IMAGES.team1}
            alt="The Core Habits team."
          />
        </section>

        <CategoriesCard />

        <section className="section-lavender">
          <ImageTextBlock
            titleRegular="Powered by people,"
            titleBold="For people"
            body="We're a vibrant team where professionals come together, support each other, and grow side by side. At Core Habits, work isn't just a job — it's a lively experience. From unforgettable parties and game nights to shared hobbies and workations around the world. We're bold visionaries with wild ideas. Ready to join something extraordinary? Welcome aboard."
            img={IMAGES.team2}
            alt="Core Habits team enjoying time together."
            reverse
          />
        </section>

        <JoinMissionCTA />
      </main>
      <Footer />
      <ApplicationModal/>
      <ContactModal/>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<HomePage />);
