/* global React */
const { useState, useEffect, useRef, useMemo } = React;

// ---------- Hooks ----------
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal, .reveal-stagger');
    // 1) Immediately reveal anything already in viewport (covers SSR-like initial state and IO-deferred environments)
    const inView = (el) => {
      const r = el.getBoundingClientRect();
      return r.top < window.innerHeight && r.bottom > 0;
    };
    els.forEach((el) => { if (inView(el)) el.classList.add('in'); });

    // 2) IntersectionObserver for everything that scrolls in later
    let io = null;
    if (typeof IntersectionObserver !== 'undefined') {
      io = new IntersectionObserver((entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add('in');
            io.unobserve(e.target);
          }
        });
      }, { threshold: 0.1, rootMargin: '0px 0px -40px 0px' });
      els.forEach((el) => { if (!el.classList.contains('in')) io.observe(el); });
    }

    // 3) Scroll-based fallback if IO doesn't fire (sandboxed iframes etc.)
    let raf = 0;
    const check = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        els.forEach((el) => { if (!el.classList.contains('in') && inView(el)) el.classList.add('in'); });
      });
    };
    window.addEventListener('scroll', check, { passive: true });
    window.addEventListener('resize', check);

    // 4) Hard safety net: reveal everything after 2s no matter what
    const safety = setTimeout(() => {
      els.forEach((el) => el.classList.add('in'));
    }, 2000);

    return () => {
      if (io) io.disconnect();
      window.removeEventListener('scroll', check);
      window.removeEventListener('resize', check);
      cancelAnimationFrame(raf);
      clearTimeout(safety);
    };
  }, []);
}

// Generic parallax wrapper — translates element on Y based on its position vs viewport
function Parallax({ speed = 0.1, children, className = '', style = {} }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let raf = 0;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        const rect = el.getBoundingClientRect();
        const center = rect.top + rect.height / 2 - window.innerHeight / 2;
        const t = -center * speed;
        el.style.transform = `translate3d(0, ${t.toFixed(1)}px, 0)`;
      });
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => { window.removeEventListener('scroll', onScroll); window.removeEventListener('resize', onScroll); cancelAnimationFrame(raf); };
  }, [speed]);
  return <div ref={ref} className={className} style={{ willChange: 'transform', ...style }}>{children}</div>;
}
function useScrollProgressBar(ref) {
  useEffect(() => {
    let raf = 0;
    const on = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        const h = document.documentElement.scrollHeight - window.innerHeight;
        const p = h > 0 ? window.scrollY / h : 0;
        if (ref.current) ref.current.style.transform = `scaleX(${p})`;
      });
    };
    on();
    window.addEventListener('scroll', on, { passive: true });
    window.addEventListener('resize', on);
    return () => { window.removeEventListener('scroll', on); window.removeEventListener('resize', on); cancelAnimationFrame(raf); };
  }, [ref]);
}

function CountUp({ to, suffix = '', duration = 1600 }) {
  const [v, setV] = useState(0);
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let started = false;
    const start = () => {
      if (started) return; started = true;
      const t0 = performance.now();
      const step = (t) => {
        const p = Math.min(1, (t - t0) / duration);
        const eased = 1 - Math.pow(1 - p, 3);
        setV(Math.round(to * eased));
        if (p < 1) requestAnimationFrame(step);
      };
      requestAnimationFrame(step);
    };
    const inView = () => {
      const r = el.getBoundingClientRect();
      return r.top < window.innerHeight && r.bottom > 0;
    };
    if (inView()) start();
    let io = null;
    if (typeof IntersectionObserver !== 'undefined') {
      io = new IntersectionObserver(([e]) => { if (e.isIntersecting) { start(); io.disconnect(); } }, { threshold: 0.2 });
      io.observe(el);
    }
    const onScroll = () => { if (inView()) start(); };
    window.addEventListener('scroll', onScroll, { passive: true });
    const safety = setTimeout(start, 2000);
    return () => { if (io) io.disconnect(); window.removeEventListener('scroll', onScroll); clearTimeout(safety); };
  }, [to, duration]);
  return <span ref={ref}>{v}{suffix}</span>;
}

// Scroll progress bar at top (DOM-only)
function ScrollProgress() {
  const ref = useRef(null);
  useScrollProgressBar(ref);
  return <div className="scroll-progress-bar"><div ref={ref} className="bar"/></div>;
}

// Page-wide atmosphere: floating gradient blobs that drift with scroll (DOM-only, no state churn)
function PageAtmosphere() {
  const b1 = useRef(null), b2 = useRef(null), b3 = useRef(null);
  useEffect(() => {
    let raf = 0;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        const y = window.scrollY;
        if (b1.current) b1.current.style.transform = `translate3d(${y * 0.04}px, ${y * 0.15}px, 0)`;
        if (b2.current) b2.current.style.transform = `translate3d(${y * -0.06}px, ${y * 0.30}px, 0)`;
        if (b3.current) b3.current.style.transform = `translate3d(${y * 0.08}px, ${y * 0.55}px, 0)`;
      });
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => { window.removeEventListener('scroll', onScroll); cancelAnimationFrame(raf); };
  }, []);
  return (
    <div className="page-atmos" aria-hidden="true">
      <div ref={b1} className="blob blob-1"/>
      <div ref={b2} className="blob blob-2"/>
      <div ref={b3} className="blob blob-3"/>
    </div>
  );
}

// ---------- Mail config ----------
const COMPANY_EMAIL = 'info@core-habits.com';
const FORMSUBMIT_AJAX = `https://formsubmit.co/ajax/${COMPANY_EMAIL}`;

// Helper: try to send through FormSubmit AJAX, otherwise fall back to mailto
async function sendForm({ subject, fields }) {
  // Try AJAX (no extra signup; the recipient confirms once via FormSubmit's email)
  try {
    const payload = {
      _subject: subject,
      _captcha: 'false',
      _template: 'table',
      ...fields,
    };
    const res = await fetch(FORMSUBMIT_AJAX, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
      body: JSON.stringify(payload),
    });
    if (res.ok) return { ok: true, via: 'ajax' };
  } catch (err) { /* fall through */ }
  // Fallback: open user's mail client with prefilled subject + body
  const lines = Object.entries(fields).map(([k, v]) => `${k}: ${v}`).join('\n');
  const href = `mailto:${COMPANY_EMAIL}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(lines)}`;
  window.location.href = href;
  return { ok: true, via: 'mailto' };
}

// Convenience mailto strings (for plain links)
const MAIL = {
  hello: `mailto:${COMPANY_EMAIL}?subject=${encodeURIComponent('Hello Core Habits')}`,
  apply: `mailto:${COMPANY_EMAIL}?subject=${encodeURIComponent('Application — Core Habits')}`,
  join:  `mailto:${COMPANY_EMAIL}?subject=${encodeURIComponent('Joining Core Habits')}`,
};

// ---------- Logomark: ring + accent dot ----------
function Logomark({ size = 26, color = 'currentColor', accent = 'var(--accent)' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none" aria-hidden="true">
      <circle cx="16" cy="16" r="14.5" stroke={color} strokeWidth="1.5" />
      <circle cx="16" cy="16" r="4.5" fill={accent} />
    </svg>
  );
}

function Wordmark({ inverted = false }) {
  return (
    <a href="index.html" className="flex items-center gap-2.5">
      <Logomark size={26} color={inverted ? '#fff' : 'var(--ink)'} />
      <span className="text-[20px] font-semibold tracking-tight leading-none" style={{ letterSpacing: '-0.02em' }}>
        Core <span style={{ fontWeight: 400 }}>Habits</span>
      </span>
    </a>
  );
}

// Spinning geometric mark — rotates with scroll velocity (DOM-only, no state churn)
function ScrollSpinner({ size = 56, className = '' }) {
  const wrapRef = useRef(null);
  useEffect(() => {
    let last = window.scrollY, lastT = performance.now();
    let target = 0, current = 0, angle = 0, raf;
    const onScroll = () => {
      const now = performance.now();
      const dt = Math.max(1, now - lastT);
      const dy = window.scrollY - last;
      target = (dy / dt) * 1000;
      last = window.scrollY;
      lastT = now;
    };
    const tick = () => {
      current = current + (target - current) * 0.12;
      target *= 0.92;
      angle = (angle + 0.3 + current * 0.04) % 360;
      if (wrapRef.current) wrapRef.current.style.transform = `rotate(${angle}deg)`;
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => { cancelAnimationFrame(raf); window.removeEventListener('scroll', onScroll); };
  }, []);
  return (
    <div ref={wrapRef} className={`scroll-spinner ${className}`} style={{ width: size, height: size }} aria-hidden="true">
      <svg viewBox="0 0 80 80" width={size} height={size} fill="none">
        <circle cx="40" cy="40" r="36" stroke="currentColor" strokeOpacity="0.18" strokeWidth="1" strokeDasharray="2 6"/>
        <circle cx="40" cy="40" r="26" stroke="currentColor" strokeOpacity="0.3" strokeWidth="1"/>
        <g transform="translate(40,40)" stroke="currentColor" strokeWidth="1">
          <line x1="-30" y1="0" x2="-22" y2="0"/>
          <line x1="30" y1="0" x2="22" y2="0"/>
          <line x1="0" y1="-30" x2="0" y2="-22"/>
          <line x1="0" y1="30" x2="0" y2="22"/>
        </g>
        <circle cx="40" cy="40" r="5" fill="var(--accent)"/>
      </svg>
    </div>
  );
}

// ---------- Nav ----------
function Nav({ activePage = 'home', openCount = 5, theme = 'light' }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 12);
    on();
    window.addEventListener('scroll', on, { passive: true });
    return () => window.removeEventListener('scroll', on);
  }, []);

  const inverted = theme === 'dark';

  return (
    <header className={`nav-wrap theme-${theme} ${scrolled ? 'scrolled' : ''}`}>
      <ScrollProgress/>
      <div className="max-w-[1280px] mx-auto px-6 md:px-10 h-[78px] flex items-center justify-between">
        <Wordmark inverted={inverted} />
        <nav className="hidden md:flex items-center gap-9">
          <a href="index.html" className={`nav-link ${activePage === 'home' ? 'active' : ''}`}>About</a>
          <a href="careers.html" className={`nav-link ${activePage === 'careers' ? 'active' : ''}`}>
            Careers
            <span className="badge-circle">{openCount}</span>
          </a>
          <button onClick={() => window.dispatchEvent(new CustomEvent('open-contact'))} className="nav-link">Contact</button>
        </nav>
        <button
          onClick={() => window.dispatchEvent(new CustomEvent('open-apply', { detail: { role: '' } }))}
          className={`btn-pill ${inverted ? '' : 'btn-pill-dark'}`}
        >
          Apply
          <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>
    </header>
  );
}

// ---------- Footer with full company info ----------
function Footer() {
  return (
    <footer id="contact" className="section-lavender relative">
      <div className="geo-corner top-left"></div>
      <div className="max-w-[1280px] mx-auto px-6 md:px-10 py-20 relative">
        <div className="grid md:grid-cols-12 gap-12">
          <div className="md:col-span-6">
            <div className="flex items-center gap-3">
              <Logomark size={32} />
              <span className="text-[26px] font-semibold leading-none" style={{ letterSpacing: '-0.02em' }}>
                Core <span style={{ fontWeight: 400 }}>Habits</span>
              </span>
            </div>
            <p className="text-[18px] leading-[1.45] mt-8 max-w-[440px]" style={{ color: 'var(--ink-2)' }}>
              Building world-leading digital health, wellness, and AI tools. Transforming lives globally.
            </p>
            <div className="mt-10">
              <button onClick={() => window.dispatchEvent(new CustomEvent('open-contact'))} className="btn-pill btn-pill-dark">
                Get in touch
                <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 className="md:col-span-3">
            <div className="eyebrow mb-4">Company</div>
            <dl className="text-[14px] space-y-3" style={{ color: 'var(--ink-2)' }}>
              <div><dt className="text-[11px] uppercase tracking-wide opacity-60">Name</dt><dd className="mt-1">Mb Core Habits</dd></div>
              <div><dt className="text-[11px] uppercase tracking-wide opacity-60">Email</dt><dd className="mt-1"><a href={`mailto:${COMPANY_EMAIL}`} className="foot-link underline decoration-1 underline-offset-4">{COMPANY_EMAIL}</a></dd></div>
            </dl>
          </div>

          <div className="md:col-span-3">
            <div className="eyebrow mb-4">Address</div>
            <address className="text-[14px] not-italic leading-[1.6]" style={{ color: 'var(--ink-2)' }}>
              Vilniaus r. sav.,<br/>
              Avižieniai, Laurų g. 13,<br/>
              LT‑14184, Lithuania
            </address>
            <ul className="mt-6 space-y-2 text-[14px]">
              <li><a href="index.html" className="foot-link">About us</a></li>
              <li><a href="careers.html" className="foot-link">Careers</a></li>
              <li><button onClick={() => window.dispatchEvent(new CustomEvent('open-contact'))} className="foot-link" style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer' }}>Contact us</button></li>
            </ul>
          </div>
        </div>

        <div className="mt-16 pt-8 border-t flex flex-col md:flex-row md:items-center md:justify-between gap-3 text-[13px]" style={{ borderColor: 'rgba(0,0,0,0.08)', color: 'var(--muted)' }}>
          <div>© 2026 Mb Core Habits. All rights reserved</div>
          <div className="flex items-center gap-6">
            <a href="privacy-policy.html" className="foot-link">Privacy policy</a>
            <a href="privacy-notice.html" className="foot-link">Privacy notice</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ---------- Stats (3, updated) ----------
const STATS = [
  { to: 5,   suffix: '+',  label: 'Brands' },
  { to: 200, suffix: 'K+', label: 'Customers worldwide' },
  { to: 2,   suffix: '+',  label: 'Years running' },
];

function StatsStrip({ background = 'white' }) {
  return (
    <section className={background === 'white' ? 'bg-white relative' : 'relative'}>
      <div className="max-w-[1280px] mx-auto px-6 md:px-10 py-10 md:py-14">
        <div className="reveal-stagger stats-row">
          {STATS.map((s, i) => (
            <div key={i} className="stat-cell">
              <div className="stat-num"><CountUp to={s.to} suffix={s.suffix}/></div>
              <div className="stat-label">{s.label}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- B&W image with parallax option ----------
function TeamImage({ src, alt, ratio = '4/5', parallax = 0 }) {
  const ref = useRef(null);
  useEffect(() => {
    if (!parallax) return;
    const el = ref.current;
    if (!el) return;
    let raf = 0;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        const rect = el.getBoundingClientRect();
        const center = rect.top + rect.height / 2 - window.innerHeight / 2;
        const t = -center * parallax;
        const img = el.querySelector('img');
        if (img) img.style.transform = `translateY(${t.toFixed(1)}px) scale(1.08)`;
      });
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => { window.removeEventListener('scroll', onScroll); cancelAnimationFrame(raf); };
  }, [parallax]);
  return (
    <div ref={ref} className="img-frame" style={{ aspectRatio: ratio }}>
      <img src={src} alt={alt} loading="lazy" />
    </div>
  );
}

const IMAGES = {
  team1: 'https://images.unsplash.com/photo-1522071820081-009f0129c71c?w=1400&auto=format&fit=crop&q=80',
  team2: 'https://images.unsplash.com/photo-1543269865-cbf427effbad?w=1400&auto=format&fit=crop&q=80',
  team3: 'https://images.unsplash.com/photo-1542744173-8e7e53415bb0?w=1400&auto=format&fit=crop&q=80',
  team4: 'https://images.unsplash.com/photo-1556761175-5973dc0f32e7?w=1400&auto=format&fit=crop&q=80',
  team5: 'https://images.unsplash.com/photo-1529156069898-49953e39b3ac?w=1400&auto=format&fit=crop&q=80',
  team6: 'https://images.unsplash.com/photo-1517245386807-bb43f82c33c4?w=1400&auto=format&fit=crop&q=80',
};

// ---------- Jobs ----------
const JOBS = [
  { title: 'Senior UI/UX Designer', team: 'Design' },
  { title: 'Dart Developer', team: 'Engineering' },
  { title: 'AI Automation Engineer', team: 'AI & Automation' },
  { title: 'Talent Acquisition Specialist', team: 'People' },
  { title: 'Data Engineer', team: 'Data' },
];

const LOCATION = 'Vilnius · Hybrid (4 days in office, 1 day from home)';

// ---------- Arrow icons ----------
function ArrowUpRight({ size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
      <path d="M4 12L12 4M5 4h7v7"/>
    </svg>
  );
}
function ArrowRight({ size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
      <path d="M3 8h10M9 4l4 4-4 4"/>
    </svg>
  );
}

// Page backdrop — fixed canvas covering full viewport, dark dune visual stays behind all content
function PageBackdrop() {
  const canvasRef = useRef(null);

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

    function draw() {
      const W = canvas.clientWidth;
      const H = canvas.clientHeight;
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      canvas.width = W * dpr;
      canvas.height = H * dpr;
      const ctx = canvas.getContext('2d');
      ctx.scale(dpr, dpr);

      ctx.fillStyle = '#040404';
      ctx.fillRect(0, 0, W, H);

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

      const crest = [];
      const samples = 400;
      for (let i = 0; i < samples; i++) {
        const t = i / (samples - 1);
        const y = t * H;
        const x =
          W * 0.46
          + Math.sin(t * Math.PI * 0.95) * W * 0.10
          - Math.sin(t * Math.PI * 1.9 + 0.4) * W * 0.07;
        crest.push([x, y]);
      }

      const starCount = Math.round((W * H) / 1900);
      for (let i = 0; i < starCount; i++) {
        const x = rand() * W;
        const y = rand() * H;
        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();
      }

      ctx.fillStyle = '#040404';
      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.lineTo(W + 50, H);
      ctx.lineTo(W + 50, 0);
      ctx.closePath();
      ctx.fill();

      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];
        const ty = next[1] - prev[1];
        const tlen = Math.hypot(tx, ty) || 1;
        const nx = -ty / tlen;
        const 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();
        }
      }

      ctx.save();
      ctx.filter = 'blur(5px)';
      ctx.strokeStyle = 'rgba(255,255,255,0.20)';
      ctx.lineWidth = 2;
      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.30)';
      ctx.lineWidth = 0.5;
      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);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  return (
    <div className="page-backdrop" aria-hidden="true">
      <canvas ref={canvasRef} className="page-backdrop-canvas"/>
    </div>
  );
}

Object.assign(window, {
  useReveal,
  Nav, Footer, Logomark, Wordmark, StatsStrip, TeamImage, ScrollSpinner, Parallax,
  IMAGES, JOBS, LOCATION, STATS, ArrowUpRight, ArrowRight, MAIL,
  CountUp, ScrollProgress, PageAtmosphere, PageBackdrop, sendForm, COMPANY_EMAIL,
});
