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

/* ---------- Hover link with slide-up animation ---------- */
function HoverLink({ text }) {
  return (
    <div className="hover-link">
      <div className="hover-in">
        {text}
        <div className="hover-ghost">{text}</div>
      </div>
    </div>
  );
}

/* ---------- Navbar ---------- */
function Navbar({ name, linkedin }) {
  const initials = name.split(" ").map(w => w[0]).join("").slice(0, 2).toUpperCase();
  const handleNav = (e, hash) => {
    e.preventDefault();
    const el = document.querySelector(hash);
    if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
  };
  return (
    <>
      <div className="nav-fade"></div>
      <div className="header">
        <a href="#top" className="navbar-title" onClick={(e) => handleNav(e, "#top")}>{initials}</a>
        <a href={`https://${linkedin}`} className="navbar-connect" target="_blank" rel="noreferrer">
          {linkedin}
        </a>
        <ul>
          <li><a href="#about" onClick={(e) => handleNav(e, "#about")}><HoverLink text="ABOUT" /></a></li>
          <li><a href="#work"  onClick={(e) => handleNav(e, "#work")}><HoverLink text="WORK" /></a></li>
          <li><a href="#contact" onClick={(e) => handleNav(e, "#contact")}><HoverLink text="CONTACT" /></a></li>
        </ul>
      </div>
    </>
  );
}

/* ---------- Background glows ---------- */
function BgGlows() {
  return (
    <>
      <div className="bg-circle bg-circle-1"></div>
      <div className="bg-circle bg-circle-2"></div>
      <div className="bg-circle bg-circle-3"></div>
    </>
  );
}

/* ---------- Hero / Landing ---------- */
function Landing({ firstName, lastName, role, focus }) {
  return (
    <div className="landing-section" id="top">
      <div className="landing-container">
        <div className="landing-intro">
          <h2>Hello! I'm</h2>
          <h1>
            {firstName.toUpperCase()}
            <br />
            <span>{lastName}</span>
          </h1>
        </div>

        <div className="now-pill"><span className="pulse"></span>NOW · Building something new</div>

        <div className="character" id="character-3d" aria-hidden="true"></div>

        <div className="landing-info">
          <h3>{role} &amp;</h3>
          <h2 className="landing-info-h2">
            <span className="word-stack">{focus}</span>
          </h2>
        </div>

        <a href="#about" className="landing-cta" onClick={(e) => {
          e.preventDefault();
          document.querySelector("#about").scrollIntoView({ behavior: "smooth" });
        }}>
          <span>SCROLL</span>
          <div className="line"></div>
        </a>
      </div>
    </div>
  );
}

/* ---------- About ---------- */
function About({ about }) {
  return (
    <div className="about-section" id="about">
      <div className="about-photo-wrap">
        <div className="about-photo-glow"></div>
        <img
          src="me.jpg"
          alt="Arun Jalota"
          className="about-photo"
          loading="lazy"
          decoding="async"
        />
      </div>
      <div className="about-me">
        <h3>About Me</h3>
        <p>{about}</p>
      </div>
    </div>
  );
}

/* ---------- What I Do ---------- */
function WhatIDo({ cards }) {
  const [active, setActive] = useState(null);
  return (
    <div className="whatIDO">
      <div className="what-box">
        <h2 className="what-title">
          W<span className="hat-h2">HAT</span>
          <div>I<span className="do-h2"> DO</span></div>
        </h2>
      </div>
      <div className="what-box">
        <div className="what-box-in">
          <div className="what-vline left"></div>
          <div className="what-vline right"></div>
          {cards.map((c, i) => {
            const cls = [
              "what-content",
              active === i ? "active" : "",
              active !== null && active !== i ? "sibling" : "",
            ].filter(Boolean).join(" ");
            return (
              <div key={i} className={cls}
                onMouseEnter={() => setActive(i)}
                onMouseLeave={() => setActive(null)}
                onClick={() => setActive(active === i ? null : i)}>
                <div className="what-corner"></div>
                {i === 0 && <div className="what-hline top"></div>}
                <div className="what-hline bottom"></div>
                <div className="what-content-inner">
                  <h3>{c.title}</h3>
                  <h4>{c.subtitle}</h4>
                  <p>{c.body}</p>
                  <h5>Skillset &amp; tools</h5>
                  <div className="what-tags-row">
                    {c.tags.map((t, j) => <div key={j} className="what-tag">{t}</div>)}
                  </div>
                  <div className="what-arrow"></div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

/* ---------- Career ---------- */
function Career({ roles }) {
  return (
    <div className="career-section section-container">
      <div className="career-container">
        <h2>My career <span>&amp;</span><br />experience</h2>
        <div className="career-info">
          <div className="career-timeline"><div className="career-dot"></div></div>
          {roles.map((r, i) => (
            <div className="career-info-box" key={i}>
              <div className="career-info-in">
                <div className="career-role">
                  <h4>{r.role}</h4>
                  <h5>{r.company}</h5>
                </div>
                <h3>{r.period}</h3>
              </div>
              <p>{r.body}</p>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ---------- Work carousel ---------- */
function Work({ projects }) {
  const [idx, setIdx] = useState(0);
  const total = projects.length;
  const go = (n) => setIdx((n + total) % total);
  return (
    <div className="work-section" id="work">
      <div className="work-container section-container">
        <h2>My <span>Work</span></h2>
        <div className="carousel-wrapper">
          <button className="carousel-arrow carousel-arrow-left" aria-label="Previous" onClick={() => go(idx - 1)}>‹</button>
          <button className="carousel-arrow carousel-arrow-right" aria-label="Next" onClick={() => go(idx + 1)}>›</button>
          <div className="carousel-track-container">
            <div className="carousel-track" style={{ transform: `translateX(-${idx * 100}%)` }}>
              {projects.map((p, i) => (
                <div className="carousel-slide" key={i}>
                  <div className="carousel-content">
                    <div className="carousel-info">
                      <div className="carousel-number"><h3>0{i + 1}</h3></div>
                      <div className="carousel-details">
                        <h4>{p.title}</h4>
                        <p className="carousel-category">{p.category}</p>
                        <div className="carousel-tools">
                          <span className="tools-label">Tools &amp; Features</span>
                          <p>{p.tools}</p>
                        </div>
                      </div>
                    </div>
                    <div className="carousel-image-wrapper">
                      {p.link ? (
                        <a href={p.link} target="_blank" rel="noreferrer" className="work-image-card" style={{ background: p.bg }}>
                          <div className="grid-overlay"></div>
                          <div className="gradient-overlay"></div>
                          <span className="label">{p.label || p.title}</span>
                          <span className="link-pill">↗</span>
                        </a>
                      ) : (
                        <div className="work-image-card" style={{ background: p.bg }}>
                          <div className="grid-overlay"></div>
                          <div className="gradient-overlay"></div>
                          <span className="label">{p.label || p.title}</span>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
          <div className="carousel-dots">
            {projects.map((_, i) => (
              <button key={i} className={`carousel-dot ${i === idx ? "active" : ""}`} onClick={() => setIdx(i)} aria-label={`Go to project ${i + 1}`} />
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- TechStack ---------- */
function TechStack({ stack }) {
  return (
    <div className="techstack section-container">
      <div className="section-eyebrow"><span className="num">06</span><span className="bar"></span>STACK</div>
      <h2>My <span>Techstack</span></h2>
      <div className="tech-grid">
        {stack.map((t, i) => (
          <div key={i} className="tech-pill tech-pill-rich">
            <div className="tech-name">{t.name}</div>
            <div className="tech-note">{t.note}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- Contact ---------- */
function Contact({ name, linkedin, email, github, education, year }) {
  return (
    <div className="contact-section section-container" id="contact">
      <div className="contact-container">
        <h3>Contact</h3>
        <div className="contact-flex">
          <div className="contact-box">
            <h4>Connect</h4>
            <p>
              <a href={`mailto:${email}`}>{email}</a><br />
              <a href={`https://${linkedin}`} target="_blank" rel="noreferrer">{linkedin}</a>
            </p>
            <h4>Education</h4>
            {education.map((e, i) => <p key={i}>{e}</p>)}
          </div>
          <div className="contact-box" style={{ minWidth: 260 }}>
            <h4>Social</h4>
            <a className="contact-social" href={`https://${linkedin}`} target="_blank" rel="noreferrer">
              <span>LinkedIn</span><span className="arrow">↗</span>
            </a>
            {github && (
              <a className="contact-social" href={`https://${github}`} target="_blank" rel="noreferrer">
                <span>GitHub</span><span className="arrow">↗</span>
              </a>
            )}
            <a className="contact-social" href={`mailto:${email}`}>
              <span>Email</span><span className="arrow">↗</span>
            </a>
          </div>
          <div className="contact-box">
            <h2>Designed &amp; built<br />by <span>{name}</span></h2>
            <h5>© {year}</h5>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- Side rail ---------- */
function SocialRail({ linkedin, github, email }) {
  return (
    <div className="icons-section">
      <div className="social-icons">
        {github && <a href={`https://${github}`} target="_blank" rel="noreferrer" aria-label="GitHub">
          <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor"><path d="M12 .5C5.65.5.5 5.65.5 12c0 5.1 3.29 9.41 7.86 10.94.58.11.79-.25.79-.55v-2.13c-3.2.69-3.87-1.36-3.87-1.36-.52-1.32-1.28-1.67-1.28-1.67-1.05-.72.08-.71.08-.71 1.16.08 1.77 1.19 1.77 1.19 1.03 1.77 2.7 1.26 3.36.96.1-.75.4-1.26.73-1.55-2.55-.29-5.24-1.28-5.24-5.7 0-1.26.45-2.29 1.19-3.1-.12-.29-.52-1.47.11-3.07 0 0 .97-.31 3.18 1.18a11 11 0 0 1 5.79 0c2.2-1.49 3.18-1.18 3.18-1.18.63 1.6.23 2.78.11 3.07.74.81 1.19 1.84 1.19 3.1 0 4.43-2.69 5.4-5.26 5.69.41.36.78 1.06.78 2.14v3.17c0 .31.21.67.8.55A11.51 11.51 0 0 0 23.5 12C23.5 5.65 18.35.5 12 .5z"/></svg>
        </a>}
        <a href={`https://${linkedin}`} target="_blank" rel="noreferrer" aria-label="LinkedIn">
          <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor"><path d="M20.45 20.45h-3.55v-5.57c0-1.33-.02-3.03-1.85-3.03-1.85 0-2.13 1.44-2.13 2.94v5.66H9.36V9h3.41v1.56h.05a3.74 3.74 0 0 1 3.37-1.85c3.6 0 4.27 2.37 4.27 5.46v6.28zM5.34 7.43A2.06 2.06 0 1 1 5.34 3.3a2.06 2.06 0 0 1 0 4.13zM7.12 20.45H3.56V9h3.56v11.45zM22.22 0H1.77C.79 0 0 .77 0 1.72v20.56C0 23.23.79 24 1.77 24h20.45c.98 0 1.78-.77 1.78-1.72V1.72C24 .77 23.2 0 22.22 0z"/></svg>
        </a>
        <a href={`mailto:${email}`} aria-label="Email">
          <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="m22 7-10 6L2 7"/></svg>
        </a>
      </div>
      <a className="resume-button builder-tag" href="#lab" onClick={(e) => {
        e.preventDefault();
        document.querySelector("#lab")?.scrollIntoView({ behavior: "smooth" });
      }}>
        <span className="dot"></span>
        BUILDER · NOT FOR HIRE
      </a>
    </div>
  );
}

function Cursor() {
  useEffect(() => {
    if (matchMedia("(hover: none)").matches) return;
    const dot = document.createElement("div"); dot.className = "cursor-dot";
    const ring = document.createElement("div"); ring.className = "cursor-ring";
    document.body.appendChild(dot); document.body.appendChild(ring);
    let dx = 0, dy = 0, rx = 0, ry = 0;
    const move = (e) => { dx = e.clientX; dy = e.clientY; };
    window.addEventListener("mousemove", move);
    const enter = () => document.body.classList.add("cursor-hover");
    const leave = () => document.body.classList.remove("cursor-hover");
    const hoverable = "a, button, .what-content, .carousel-dot, .tech-pill, [data-cursor]";
    document.querySelectorAll(hoverable).forEach(el => {
      el.addEventListener("mouseenter", enter);
      el.addEventListener("mouseleave", leave);
    });
    let raf;
    const tick = () => {
      rx += (dx - rx) * 0.18;
      ry += (dy - ry) * 0.18;
      dot.style.transform = `translate(${dx}px, ${dy}px) translate(-50%,-50%)`;
      ring.style.transform = `translate(${rx}px, ${ry}px) translate(-50%,-50%)`;
      raf = requestAnimationFrame(tick);
    };
    tick();
    return () => { cancelAnimationFrame(raf); window.removeEventListener("mousemove", move); dot.remove(); ring.remove(); };
  }, []);
  return null;
}

function Marquee({ items }) {
  const list = [...items, ...items];
  return (
    <div className="marquee" aria-hidden="true">
      <div className="marquee-track">
        {list.map((it, i) => (
          <React.Fragment key={i}>
            <span className={i % 3 === 1 ? "accent" : ""}>{it}</span>
            <span className="dot"></span>
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

function StackTilt() {
  useEffect(() => {
    const els = document.querySelectorAll(".tech-pill-rich");
    const onMove = (e) => {
      const r = e.currentTarget.getBoundingClientRect();
      e.currentTarget.style.setProperty("--mx", `${((e.clientX - r.left) / r.width) * 100}%`);
      e.currentTarget.style.setProperty("--my", `${((e.clientY - r.top) / r.height) * 100}%`);
    };
    els.forEach(el => el.addEventListener("mousemove", onMove));
    return () => els.forEach(el => el.removeEventListener("mousemove", onMove));
  });
  return null;
}

function PageProgress() {
  useEffect(() => {
    const bar = document.createElement("div"); bar.className = "page-progress";
    document.body.appendChild(bar);
    const update = () => {
      const h = document.documentElement;
      const pct = (h.scrollTop || document.body.scrollTop) / (h.scrollHeight - h.clientHeight) * 100;
      bar.style.width = pct + "%";
    };
    window.addEventListener("scroll", update, { passive: true });
    update();
    return () => { window.removeEventListener("scroll", update); bar.remove(); };
  }, []);
  return null;
}

function SectionRail() {
  const items = [
    { id: "top", label: "Home" },
    { id: "about", label: "About" },
    { id: "work", label: "Work" },
    { id: "contact", label: "Contact" },
  ];
  const [active, setActive] = useState("top");
  useEffect(() => {
    const onScroll = () => {
      let cur = "top";
      items.forEach(it => {
        const el = document.querySelector("#" + it.id);
        if (el && el.getBoundingClientRect().top < window.innerHeight / 2) cur = it.id;
      });
      setActive(cur);
    };
    window.addEventListener("scroll", onScroll, { passive: true }); onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <nav className="section-rail" aria-label="Section navigation">
      {items.map(it => (
        <a key={it.id} href={"#" + it.id} className={active === it.id ? "active" : ""}
           onClick={(e) => { e.preventDefault(); document.querySelector("#" + it.id)?.scrollIntoView({ behavior: "smooth" }); }}
           aria-label={it.label} />
      ))}
    </nav>
  );
}

function Spotlight() {
  useEffect(() => {
    const el = document.createElement("div"); el.className = "spotlight";
    document.body.appendChild(el);
    const move = (e) => {
      el.style.setProperty("--sx", e.clientX + "px");
      el.style.setProperty("--sy", e.clientY + "px");
    };
    window.addEventListener("mousemove", move);
    return () => { window.removeEventListener("mousemove", move); el.remove(); };
  }, []);
  return null;
}

function Constellation() {
  useEffect(() => {
    const c = document.createElement("canvas"); c.id = "constellation";
    document.body.appendChild(c);
    const ctx = c.getContext("2d");
    let W, H;
    const resize = () => { W = c.width = innerWidth; H = c.height = innerHeight; };
    resize(); window.addEventListener("resize", resize);
    const N = 70;
    const pts = Array.from({ length: N }, () => ({
      x: Math.random() * W, y: Math.random() * H,
      vx: (Math.random() - .5) * .15, vy: (Math.random() - .5) * .15,
    }));
    let raf;
    const draw = () => {
      ctx.clearRect(0, 0, W, H);
      pts.forEach(p => {
        p.x += p.vx; p.y += p.vy;
        if (p.x < 0 || p.x > W) p.vx *= -1;
        if (p.y < 0 || p.y > H) p.vy *= -1;
        ctx.beginPath(); ctx.arc(p.x, p.y, 1.2, 0, Math.PI * 2);
        ctx.fillStyle = "rgba(94,234,212,.55)"; ctx.fill();
      });
      for (let i = 0; i < N; i++) for (let j = i + 1; j < N; j++) {
        const dx = pts[i].x - pts[j].x, dy = pts[i].y - pts[j].y;
        const d = Math.hypot(dx, dy);
        if (d < 130) {
          ctx.strokeStyle = `rgba(94,234,212,${0.18 * (1 - d / 130)})`;
          ctx.beginPath(); ctx.moveTo(pts[i].x, pts[i].y); ctx.lineTo(pts[j].x, pts[j].y); ctx.stroke();
        }
      }
      raf = requestAnimationFrame(draw);
    };
    draw();
    return () => { cancelAnimationFrame(raf); window.removeEventListener("resize", resize); c.remove(); };
  }, []);
  return null;
}

function CommandPalette() {
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState("");
  const cmds = [
    { label: "Go to About",   meta: "Section", run: () => document.querySelector("#about")?.scrollIntoView({ behavior: "smooth" }) },
    { label: "Go to Work",    meta: "Section", run: () => document.querySelector("#work")?.scrollIntoView({ behavior: "smooth" }) },
    { label: "Go to Contact", meta: "Section", run: () => document.querySelector("#contact")?.scrollIntoView({ behavior: "smooth" }) },
    { label: "Visit VoltExam",     meta: "External", run: () => window.open("https://voltexam.com", "_blank") },
    { label: "Visit CapitalGains", meta: "External", run: () => window.open("https://www.capitalgains.app", "_blank") },
    { label: "Email Arun",         meta: "Action",   run: () => location.href = "mailto:arun@arunjalota.com" },
    { label: "Open GitHub",        meta: "External", run: () => window.open("https://github.com/arunjalota", "_blank") },
    { label: "Open LinkedIn",      meta: "External", run: () => window.open("https://linkedin.com/in/arunjalota", "_blank") },
    { label: "Toggle accent: Cyan",   meta: "Theme", run: () => document.documentElement.style.setProperty("--accentColor", "#22d3ee") },
    { label: "Toggle accent: Mint",   meta: "Theme", run: () => document.documentElement.style.setProperty("--accentColor", "#5eead4") },
    { label: "Toggle accent: Orange", meta: "Theme", run: () => document.documentElement.style.setProperty("--accentColor", "#f97316") },
  ];
  const filtered = cmds.filter(c => c.label.toLowerCase().includes(q.toLowerCase()));

  useEffect(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") { e.preventDefault(); setOpen(v => !v); }
      if (e.key === "Escape") setOpen(false);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  return (
    <>
      <div className="kbd-hint" onClick={() => setOpen(true)}>
        <kbd>⌘</kbd><kbd>K</kbd> Command menu
      </div>
      <div className={`palette-backdrop ${open ? "open" : ""}`} onClick={() => setOpen(false)}>
        <div className="palette" onClick={(e) => e.stopPropagation()}>
          <input autoFocus={open} placeholder="Type a command or section…" value={q} onChange={(e) => setQ(e.target.value)} />
          <ul>
            {filtered.map((c, i) => (
              <li key={i} onClick={() => { c.run(); setOpen(false); setQ(""); }}>
                <span>{c.label}</span><span className="meta">{c.meta}</span>
              </li>
            ))}
            {!filtered.length && <li><span style={{ opacity: .5 }}>No matches</span></li>}
          </ul>
        </div>
      </div>
    </>
  );
}

/* ---------- LAB · smart tools powered by Claude ---------- */
function AskArun() {
  const [q, setQ] = useState("");
  const [a, setA] = useState("");
  const [loading, setLoading] = useState(false);
  const seeded = [
    "What's the hardest engineering problem you've solved?",
    "How do you decide what to build next?",
    "Your take on AI in product work?",
    "Engineer → director, what changes?",
  ];
  const ask = async (text) => {
    const prompt = (text || q).trim();
    if (!prompt) return;
    setQ(prompt); setLoading(true); setA("");
    try {
      const SYS = `You are Arun Jalota answering visitors on his portfolio site. About him: 13+ years building software. Software Engineer 2012–19, Sr. Software Engineer 2019–21, Technical Director 2021–25, now (2025+) building independently — products include VoltExam (AI exam prep, voltexam.com) and CapitalGains (finance/tax companion, capitalgains.app). Stack he loves: TypeScript, Node, Python, React, Next.js, Unity/C#, Postgres, Redis, AWS, OpenAI, Three.js. Voice: builder, direct, no-fluff, lightly self-aware, never braggy, sometimes wry. He's a builder, not a job seeker — never pitch himself for hiring. Keep replies under 80 words. No greetings, no "Great question", no markdown. Plain prose.`;
      const text = await window.claude.complete({
        messages: [{ role: "user", content: `${SYS}\n\nVisitor asks: ${prompt}` }],
      });
      setA(text);
    } catch {
      setA("My AI twin is offline. Email me directly: arun@arunjalota.com");
    } finally { setLoading(false); }
  };
  return (
    <div className="lab-card">
      <div className="lab-card-head">
        <span className="lab-tag">AI</span>
        <h3>Ask Arun</h3>
      </div>
      <p className="lab-sub">A small AI that thinks like me. Ask about building, AI, or the messy bits in between.</p>
      <div className="lab-seeds">
        {seeded.map((s, i) => (
          <button key={i} type="button" className="lab-seed" onClick={() => ask(s)}>{s}</button>
        ))}
      </div>
      <div className="lab-input">
        <input value={q} onChange={(e) => setQ(e.target.value)}
               onKeyDown={(e) => e.key === "Enter" && ask()}
               placeholder="Ask me anything..." />
        <button type="button" onClick={() => ask()} disabled={loading}>
          {loading ? "…" : "→"}
        </button>
      </div>
      {(loading || a) && (
        <div className="lab-reply">
          {loading
            ? <span className="lab-dots"><i></i><i></i><i></i></span>
            : a}
        </div>
      )}
    </div>
  );
}

function BuildOMatic() {
  const [idea, setIdea] = useState("");
  const [loading, setLoading] = useState(false);
  const roll = async () => {
    setLoading(true);
    try {
      const text = await window.claude.complete(
        `Invent ONE surprising, oddly-specific product idea at the intersection of: AI, a real-world workflow, and a small human annoyance. Output EXACTLY in this format, no markdown, no extra lines:\n\n<3-word product name in Title Case>\n<one sentence pitch, max 20 words>\nStack: <three techs comma-separated>\nWhy it's weird: <one short line>\n\nPick stack from: TypeScript, Node, Python, React, Next.js, Unity, Three.js, Postgres, Redis, AWS, OpenAI, WebSockets, Swift. Be specific, slightly absurd, builder-flavoured.`
      );
      setIdea(text);
    } catch {
      setIdea("Idea generator ran out of coffee. Try again.");
    } finally { setLoading(false); }
  };
  return (
    <div className="lab-card">
      <div className="lab-card-head">
        <span className="lab-tag alt">∆</span>
        <h3>Build-O-Matic</h3>
      </div>
      <p className="lab-sub">Click for a startup idea nobody asked for. A small love letter to building weird things.</p>
      <button type="button" className="build-roll" onClick={roll} disabled={loading}>
        {loading ? "Inventing…" : (idea ? "Roll again" : "Roll the dice")}
      </button>
      {idea && <pre className="build-idea">{idea}</pre>}
    </div>
  );
}

function Lab() {
  return (
    <div className="lab section-container reveal" id="lab">
      <div className="section-eyebrow"><span className="num">05</span><span className="bar"></span>LAB · TRY IT</div>
      <h2 className="lab-title">
        Smart toys. Wired to the same APIs<br/>
        I ship in <span className="accent">production</span>.
      </h2>
      <div className="lab-grid">
        <AskArun />
        <BuildOMatic />
      </div>
    </div>
  );
}

function Philosophy() {
  return (
    <div className="philosophy reveal">
      <div className="section-eyebrow"><span className="num">04</span><span className="bar"></span>PHILOSOPHY</div>
      <p className="philosophy-quote">
        Software is just <span className="accent">a story</span> told to a machine.<br />
        The best ones are <span className="accent">honest</span>, the rest are clever.
      </p>
      <div className="philosophy-sig">— A note to self, on most days</div>
    </div>
  );
}

function Stats() {
  return (
    <div className="stats-strip section-container reveal">
      <div className="stat"><div className="num">13<span className="plus">+</span></div><div className="label">Years building</div></div>
      <div className="stat"><div className="num">4</div><div className="label">Roles, one craft</div></div>
      <div className="stat"><div className="num">∞</div><div className="label">Pull requests</div></div>
      <div className="stat"><div className="num">1</div><div className="label">Currently shipping</div></div>
    </div>
  );
}

/* ---------- Defaults / Tweaks ---------- */
const DATA_DEFAULTS = /*EDITMODE-BEGIN*/{
  "firstName": "Arun",
  "lastName": "Jalota",
  "role": "Engineer",
  "focus": "Builder",
  "accent": "#f97316",
  "linkedin": "linkedin.com/in/arunjalota",
  "github": "github.com/arunjalota",
  "email": "arun@arunjalota.com"
}/*EDITMODE-END*/;

const ACCENT_OPTIONS = ["#5eead4", "#22d3ee", "#f97316", "#a78bfa"];

function App() {
  const t = window.useTweaks ? window.useTweaks(DATA_DEFAULTS) : [DATA_DEFAULTS, () => {}];
  const [tweaks, setTweak] = t;

  // ── Loading sequence + 3D mount + scroll reveals + smooth scroll ──
  const [loaded, setLoaded] = useState(false);
  const [pct, setPct] = useState(0);
  useEffect(() => {
    document.body.classList.add("loading");
    let p = 0;
    const id = setInterval(() => {
      p += 2 + Math.random() * 6;
      if (p >= 100) { p = 100; clearInterval(id); }
      setPct(Math.floor(p));
    }, 70);
    return () => clearInterval(id);
  }, []);
  useEffect(() => {
    if (pct < 100) return;
    const t = setTimeout(() => {
      setLoaded(true);
      document.body.classList.remove("loading");
      document.body.classList.add("app-ready");
      // mount three.js after the hero is visible
      if (window.mountCharacter3D) window.mountCharacter3D();
      // smooth scroll
      if (window.Lenis) {
        const lenis = new window.Lenis({ duration: 1.4, smoothWheel: true, smoothTouch: false });
        function raf(time) { lenis.raf(time); requestAnimationFrame(raf); }
        requestAnimationFrame(raf);
      }
      // scroll reveals
      const io = new IntersectionObserver((entries) => {
        entries.forEach(e => {
          if (e.isIntersecting) {
            e.target.classList.add("visible");
            io.unobserve(e.target);
          }
        });
      }, { threshold: 0.15 });
      document.querySelectorAll(".reveal").forEach(el => io.observe(el));
    }, 500);
    return () => clearTimeout(t);
  }, [pct]);

  useEffect(() => {
    document.documentElement.style.setProperty("--accentColor", tweaks.accent);
    document.documentElement.style.setProperty("--accentGlow", tweaks.accent);
  }, [tweaks.accent]);

  const content = {
    about: (
      <>
        I'm a <span className="accent">technologist</span> who builds end-to-end —
        from product strategy to hands-on code. I've spent years shipping
        full-stack products and now I'm focused on the place where
        <span className="accent"> AI meets real-world workflows</span>.
        <span className="quiet"> Always shipping, rarely satisfied.</span>
      </>
    ),
    whatIDoCards: [
      {
        title: "AI & AUTOMATION",
        subtitle: "Workflow intelligence for organizations",
        body: "I help teams automate the boring parts of their business — internal ops, customer touch-points, knowledge retrieval — so people stay focused on the work that matters.",
        tags: ["LLMs & agents", "RAG & retrieval", "Workflow design", "Evals & guardrails", "Integrations", "Product strategy"],
      },
      {
        title: "BUILD & SCALE",
        subtitle: "Shipping software in production",
        body: "I build the systems behind the demo: APIs, data pipelines, full-stack products. Production-ready, instrumented, and built to scale — not slide-deck demos.",
        tags: ["TypeScript", "Node.js", "Python", "React", "Postgres", "AWS / GCP"],
      },
    ],
    career: [
      { role: "Building something new", company: "Independent", period: "NOW",
        body: "Heads-down on a new product at the edge of engineering and applied AI. Quietly shipping; happy to compare notes — drop a line." },
      { role: "Technical Director", company: "Product org", period: "2021–25",
        body: "Led engineering for a multi-product line. Owned architecture, hiring, and delivery — from zero-to-one launches to scaling existing systems. Set the technical bar and the team that cleared it." },
      { role: "Sr. Software Engineer", company: "Product team", period: "2019–21",
        body: "Built and operated production services end-to-end — APIs, data, real-time, and the UI on top. Picked up the work nobody else wanted and turned it into the bits the team relied on." },
      { role: "Software Engineer", company: "Engineering teams", period: "2012–19",
        body: "Seven years deep across enterprise codebases — design, development, delivery, code review at scale. Cut my teeth on the unglamorous parts: legacy systems, migrations, integrations, and on-call." },
    ],
    projects: [
      { title: "VoltExam",      category: "AI-powered exam prep platform",     tools: "Next.js · TypeScript · Postgres · OpenAI · Tailwind",
        bg: "linear-gradient(135deg, #0e2a2a, #14b8a6 120%)",   label: "VX", link: "https://voltexam.com" },
      { title: "CapitalGains",  category: "Personal finance & tax companion",  tools: "Swift · React · Node · Charts · Secure storage",
        bg: "linear-gradient(135deg, #1a2a3a, #22d3ee 130%)",   label: "CG", link: "https://www.capitalgains.app" },
      { title: "Realtime systems",  category: "Voice & event-driven services",    tools: "Node.js · WebSockets · Redis · Workers · Queues",
        bg: "linear-gradient(135deg, #2a1a3a, #5eead4 140%)",   label: "RT" },
      { title: "Interactive 3D",    category: "Unity · C# experiments & games",   tools: "Unity · C# · Shaders · Procedural generation",
        bg: "linear-gradient(135deg, #3a2a1a, #a5f3fc 140%)",   label: "3D" },
    ],
    stack: [
      { name: "TypeScript", note: "My default for anything non-trivial. Types as a thinking tool." },
      { name: "Python",     note: "Glue for AI, data, and the occasional script that runs production." },
      { name: "Node.js",    note: "Long-running services, real-time, and APIs I trust at 3am." },
      { name: "React",      note: "Composable interfaces. The grammar I think in for UI." },
      { name: "Next.js",    note: "Hybrid rendering when SEO and DX both matter." },
      { name: "Unity · C#", note: "Game loops, shaders, and the joy of moving things in 3D." },
      { name: "Postgres",   note: "Relational truth. JSONB when life gets messy." },
      { name: "MongoDB",    note: "Flexible documents for fast-iteration domains." },
      { name: "Redis",      note: "Caches, queues, pub/sub — the duct tape of fast systems." },
      { name: "AWS",        note: "Where production lives. Lambda, ECS, RDS, S3." },
      { name: "Docker",     note: "Reproducible everywhere. Container is the unit." },
      { name: "OpenAI",     note: "LLMs as a primitive. Prompts, tools, and evals." },
      { name: "Three.js",   note: "Stories told in 3D on the web. Lights, shaders, motion." },
      { name: "Tailwind",   note: "Design tokens at the speed of thought." },
    ],
    education: ["B.Tech, Information Technology — 2008–2012"],
  };

  const TP = window.TweaksPanel;
  const TS = window.TweakSection;
  const TText = window.TweakText;
  const TColor = window.TweakColor;
  const tweaksReady = TP && TS && TText && TColor;

  return (
    <>
      {!loaded && (
        <div className={`loading-screen ${pct >= 100 ? "fading" : ""}`}>
          <div className="loading-counter"><b>{String(pct).padStart(3, "0")}</b>/ LOADING</div>
          <div className="loading-name" aria-label={`${tweaks.firstName} ${tweaks.lastName}`}>
            {(tweaks.firstName + " " + tweaks.lastName).split("").map((ch, i) => (
              <span key={i} style={{ animationDelay: `${0.05 + i * 0.06}s` }}
                    className={i >= tweaks.firstName.length + 1 ? "italic" : ""}>
                {ch === " " ? "\u00a0" : ch}
              </span>
            ))}
          </div>
          <div className="loading-sub">{tweaks.role} &middot; {tweaks.focus}</div>
          <div className="loading-bar" style={{ width: `${pct}%` }}></div>
        </div>
      )}
      <Constellation />
      <BgGlows />
      <Spotlight />
      <Cursor />
      <PageProgress />
      <SectionRail />
      <CommandPalette />
      <div className="signature">// crafted with three.js, react & late-night espresso</div>
      <Navbar name={`${tweaks.firstName} ${tweaks.lastName}`} linkedin={tweaks.linkedin} />
      <SocialRail linkedin={tweaks.linkedin} github={tweaks.github} email={tweaks.email} />

      <Landing
        firstName={tweaks.firstName}
        lastName={tweaks.lastName}
        role={tweaks.role}
        focus={tweaks.focus}
      />
      <Stats />
      <div className="reveal"><About about={content.about} /></div>
      <Marquee items={["Engineering", "Applied AI", "Product", "Architecture", "Teams", "Shipping", "Craft"]} />
      <div className="reveal"><WhatIDo cards={content.whatIDoCards} /></div>
      <div className="reveal"><Career roles={content.career} /></div>
      <div className="reveal"><Work projects={content.projects} /></div>
      <Philosophy />
      <Lab />
      <div className="reveal"><TechStack stack={content.stack} /></div>
      <StackTilt />
      <Contact
        name={`${tweaks.firstName} ${tweaks.lastName}`}
        linkedin={tweaks.linkedin}
        github={tweaks.github}
        email={tweaks.email}
        education={content.education}
        year={2026}
      />

      {tweaksReady && (
        <TP title="Tweaks">
          <TS title="Identity">
            <TText label="First name" value={tweaks.firstName} onChange={(v) => setTweak("firstName", v)} />
            <TText label="Last name"  value={tweaks.lastName}  onChange={(v) => setTweak("lastName", v)} />
            <TText label="Role"       value={tweaks.role}      onChange={(v) => setTweak("role", v)} />
            <TText label="Focus word" value={tweaks.focus}     onChange={(v) => setTweak("focus", v)} />
          </TS>
          <TS title="Theme">
            <TColor label="Accent color" value={tweaks.accent} options={ACCENT_OPTIONS} onChange={(v) => setTweak("accent", v)} />
          </TS>
          <TS title="Contact">
            <TText label="LinkedIn" value={tweaks.linkedin} onChange={(v) => setTweak("linkedin", v)} />
            <TText label="GitHub"   value={tweaks.github}   onChange={(v) => setTweak("github", v)} />
            <TText label="Email"    value={tweaks.email}    onChange={(v) => setTweak("email", v)} />
          </TS>
        </TP>
      )}
    </>
  );
}

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