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

/* ---------- magnetic custom cursor + sticker hover labels ---------- */
function Cursor() {
  const ref = useRef(null);
  const target = useRef({ x: -100, y: -100 });
  const pos = useRef({ x: -100, y: -100 });

  useEffect(() => {
    const el = ref.current;
    const onMove = (e) => { target.current.x = e.clientX; target.current.y = e.clientY; };

    const handleEnter = (e) => {
      const t = e.target.closest("[data-cursor]");
      if (!t) return;
      const mode = t.getAttribute("data-cursor");
      const label = t.getAttribute("data-label") || "";
      el.classList.remove("hot", "text");
      if (mode === "hot") el.classList.add("hot");
      if (mode === "text") el.classList.add("text");
      el.setAttribute("data-label", label);
    };
    const handleLeave = (e) => {
      const t = e.target.closest && e.target.closest("[data-cursor]");
      if (!t) return;
      el.classList.remove("hot", "text");
      el.setAttribute("data-label", "");
    };

    window.addEventListener("mousemove", onMove);
    document.addEventListener("mouseover", handleEnter);
    document.addEventListener("mouseout", handleLeave);

    let raf;
    const tick = () => {
      pos.current.x += (target.current.x - pos.current.x) * 0.22;
      pos.current.y += (target.current.y - pos.current.y) * 0.22;
      el.style.transform = `translate(${pos.current.x}px, ${pos.current.y}px) translate(-50%, -50%)`;
      raf = requestAnimationFrame(tick);
    };
    tick();
    return () => {
      window.removeEventListener("mousemove", onMove);
      document.removeEventListener("mouseover", handleEnter);
      document.removeEventListener("mouseout", handleLeave);
      cancelAnimationFrame(raf);
    };
  }, []);

  return <div id="vi-cursor" ref={ref}></div>;
}

/* ---------- NAV ---------- */
function Nav() {
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  const links = [
    { href: "#services", label: "Services" },
    { href: "#work",     label: "Work" },
    { href: "#process",  label: "Process" },
    { href: "#team",     label: "Team" },
    { href: "#faq",      label: "FAQ" },
  ];

  return (
    <>
      <nav className="nav">
        <a href="#top" className="nav__logo-mark" data-cursor="hot" data-label="TOP">
          <span className="nav__logo-viral">VIRAL</span>
          <span className="nav__logo-inbound">inbound.</span>
        </a>
        <span className="nav__status"><span className="dot"></span> Studio Open · Bengaluru</span>
        <div className="nav__links">
          {links.map((l) => (
            <a key={l.href} href={l.href} data-cursor="hot" data-label="LOOK">{l.label}</a>
          ))}
        </div>
        <a href="#contact" className="nav__cta" data-cursor="hot" data-label="GO">Start a Project →</a>
        <button
          className={`nav__burger ${open ? "is-open" : ""}`}
          onClick={() => setOpen(!open)}
          aria-label={open ? "Close menu" : "Open menu"}
          aria-expanded={open}
          data-cursor="hot"
          data-label="MENU"
        >
          <span></span>
          <span></span>
          <span></span>
        </button>
      </nav>

      <div className={`mobnav ${open ? "is-open" : ""}`} aria-hidden={!open}>
        <div className="mobnav__inner">
          <span className="mobnav__eyebrow">
            <span className="dot"></span> Menu · 05 sections
          </span>
          <ul className="mobnav__list">
            {links.map((l, i) => (
              <li key={l.href} style={{ "--i": i }}>
                <a href={l.href} onClick={() => setOpen(false)}>
                  <span className="mobnav__num">{String(i + 1).padStart(2, "0")}</span>
                  <span className="mobnav__label">{l.label}</span>
                  <span className="mobnav__arrow">↗</span>
                </a>
              </li>
            ))}
          </ul>

          <div className="mobnav__cta-row">
            <a href="#contact" className="cta cta--paper" onClick={() => setOpen(false)}>
              Start a Project <span className="cta__arrow">↗</span>
            </a>
          </div>

          <div className="mobnav__meta">
            <div>
              <span className="mobnav__meta-label">EMAIL</span>
              <a href="mailto:hello@viralinbound.in">hello@viralinbound.in</a>
            </div>
            <div>
              <span className="mobnav__meta-label">PHONE</span>
              <a href="tel:+918968430834">+91 89684 30834</a>
            </div>
            <div>
              <span className="mobnav__meta-label">STUDIO</span>
              <span>Koramangala, BLR</span>
            </div>
          </div>

          <div className="mobnav__sig">
            <span className="t-serif" style={{ fontSize: 22 }}>made loud,</span>
            <span className="t-mono" style={{ opacity: 0.6 }}>EST. MMXX</span>
          </div>
        </div>
      </div>
    </>
  );
}

/* ---------- HERO ---------- */
function Hero() {
  const layerRef = useRef(null);

  useEffect(() => {
    const layer = layerRef.current;
    if (!layer) return;
    const onMove = (e) => {
      const rect = layer.getBoundingClientRect();
      const cx = rect.width / 2;
      const cy = rect.height / 2;
      const dx = (e.clientX - rect.left - cx) / cx;
      const dy = (e.clientY - rect.top - cy) / cy;
      layer.querySelectorAll("[data-depth]").forEach((node) => {
        const d = parseFloat(node.getAttribute("data-depth"));
        node.style.transform = `translate(${dx * d}px, ${dy * d}px) rotate(${node.dataset.r || 0}deg)`;
      });
    };
    window.addEventListener("mousemove", onMove);
    return () => window.removeEventListener("mousemove", onMove);
  }, []);

  // scramble effect on the headline word
  const [scrambled, setScrambled] = useState("LOUDER");
  useEffect(() => {
    const target = "LOUDER";
    const pool = "QWERTYUIOPASDFGHJKLZXCVBNM#@$%&!?";
    let i = 0;
    const id = setInterval(() => {
      const out = target.split("").map((ch, idx) => {
        if (idx < i) return ch;
        return pool[Math.floor(Math.random() * pool.length)];
      }).join("");
      setScrambled(out);
      i += 0.5;
      if (i >= target.length + 4) i = 0;
    }, 80);
    return () => clearInterval(id);
  }, []);

  return (
    <section className="hero noise dots" id="top">
      <window.HeroBackdrop />
      <div className="hero__floats" ref={layerRef}>
        <span className="hero__emoji floaty" style={{ bottom: "2%", left: "5%", "--r": "-8deg", color: "var(--lava)" }} data-depth="22" data-r="-8">★</span>
        <span className="hero__emoji floaty" style={{ top: "18%", right: "8%", "--r": "12deg", color: "var(--pink)" }} data-depth="-18" data-r="12">✺</span>
        <span className="hero__emoji floaty" style={{ top: "12%", left: "6%", "--r": "6deg", color: "var(--blue)" }} data-depth="14" data-r="6">✦</span>
        <span className="hero__emoji floaty" style={{ bottom: "16%", right: "12%", "--r": "-10deg", color: "var(--lava)" }} data-depth="-22" data-r="-10">❍</span>
        <span className="sticker sticker--pink" style={{ position: "absolute", top: "8%", right: "30%" }} data-depth="10">No agency BS, est. 2020</span>
        <span className="sticker sticker--blue" style={{ position: "absolute", bottom: "30%", right: "6%", transform: "rotate(6deg)" }} data-depth="-14">Made in 🇮🇳</span>
        <span className="sticker sticker--acid" style={{ position: "absolute", bottom: "10%", left: "32%", transform: "rotate(-3deg)" }} data-depth="8">★ ★ ★ ★ ★</span>
      </div>

      <div className="wrap hero__inner">
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 40, flexWrap: "wrap", gap: 14 }}>
          <span className="eyebrow">A design studio for the chronically online</span>
          <span className="t-mono" style={{ fontSize: 12, opacity: 0.6 }}>EST. MMXX · BENGALURU</span>
        </div>

        <h1 className="mega" style={{ position: "relative" }}>
          We make<br />
          <span className="t-serif hero-brands">brands</span>{" "}
          <span style={{ display: "inline-block", background: "var(--ink)", color: "var(--acid)", padding: "0 18px", borderRadius: 18, transform: "rotate(-2deg)" }}>{scrambled}.</span>
        </h1>

        <div className="hero__footer">
          <p className="hero__caption">
            We're a small studio building <em className="t-serif" style={{ fontSize: 21 }}>brands, products and websites</em> that
            people actually screenshot. No templated decks. No design-by-committee.
            Just sharp work, made loud.
          </p>
          <div style={{ display: "flex", gap: 14, flexWrap: "wrap" }}>
            <a href="#contact" className="cta" data-cursor="hot" data-label="LET'S GO">
              Book an intro call <span className="cta__arrow">↗</span>
            </a>
            <a href="#work" className="cta cta--paper" data-cursor="hot" data-label="SEE">
              See the work <span className="cta__arrow">→</span>
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- TICKER ---------- */
function Ticker({ items, variant = "" }) {
  const content = [...items, ...items, ...items];
  return (
    <div className={`ticker ${variant}`}>
      <div className="ticker__track">
        {content.map((it, i) => (
          <span key={i} style={{ display: "inline-flex", alignItems: "center", gap: 28 }}>
            {it} <span className="star">✦</span>
          </span>
        ))}
      </div>
    </div>
  );
}

/* ---------- SERVICES ---------- */
function Services() {
  const services = [
    {
      cls: "svc--brand", num: "01",
      title: <>Brand <em>identity.</em></>,
      body: "Logos, wordmarks, motion ID and the entire visual religion around them. We don't do moodboards we don't believe in.",
      list: ["Naming", "Logo & wordmark", "Type & color system", "Brand guidelines", "Packaging & merch"],
      emoji: "✺",
    },
    {
      cls: "svc--ux", num: "02",
      title: <>UI & UX <em>that fits.</em></>,
      body: "App flows, dashboards, design systems, prototypes. We treat your product like our own — because for 4 months, it is.",
      list: ["Research & flows", "Wireframes", "Hi-fi design", "Design systems", "Figma → reality"],
      emoji: "◐",
    },
    {
      cls: "svc--web", num: "03",
      title: <>Websites that <em>convert.</em></>,
      body: "Design + development. Marketing sites, e-com, landing pages. Built in Framer, Webflow, Next.js — whatever fits the job.",
      list: ["Strategy & copy", "Design", "Development", "CMS & headless", "SEO foundations"],
      emoji: "✦",
    },
  ];

  return (
    <section className="services noise rules" id="services">
      <Furniture num="02" label="WHAT WE DO" ghost="services." position="right" />
      <div className="wrap">
        <div className="services__head">
          <div>
            <span className="eyebrow">What we do · 03 services</span>
            <h2 className="mega" style={{ marginTop: 16 }}>
              Three things.<br />
              <span className="t-serif">Done loudly.</span>
            </h2>
          </div>
          <p>We don't do everything. We do three things, and we do them like our names are on the door — because they are.</p>
        </div>

        <div className="svc-grid">
          {services.map((s, i) => (
            <article key={i} className={`svc ${s.cls} noise`} data-cursor="hot" data-label="VIEW">
              <div className="svc__num">
                <span>{s.num} / 03</span>
                <span>↗</span>
              </div>
              <h3 className="svc__title">{s.title}</h3>
              <p className="svc__body">{s.body}</p>
              <div className="svc__list">
                {s.list.map((l, j) => <span key={j}>{l}</span>)}
              </div>
              <span className="svc__bigemoji">{s.emoji}</span>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- WORK ---------- */
function Work() {
  const cases = [
    { cls: "case--6", viz: "viz--mango", name: "Mango Mango", cat: "Brand identity · 2025",
      title: "Loud ice cream from Goa.", tag: "+312% DTC sales", visual: <BigStamp text="MANGO" sub="MANGO" /> },
    { cls: "case--6", viz: "viz--fold", name: "Fold", cat: "Product UX · 2024",
      title: "A neobank for freelancers.", tag: "1.2M onboarded", visual: <FoldViz /> },
    { cls: "case--4", viz: "viz--halo", name: "Halo", cat: "Brand + app · 2024",
      title: "Meditation, minus the woo.", tag: "App Store editor's pick", visual: <HaloViz /> },
    { cls: "case--4", viz: "viz--bolt", name: "Bolt Coffee", cat: "Web + identity · 2025",
      title: "Specialty coffee. With teeth.", tag: "Awwwards SOTD", visual: <BoltViz /> },
    { cls: "case--4", viz: "viz--pilot", name: "Pilot Studios", cat: "Brand system · 2023",
      title: "Indie game studio rebrand.", tag: "Featured · It's Nice That", visual: <PilotViz /> },
  ];
  return (
    <section className="work noise rules" id="work">
      <Furniture num="03" label="SELECTED WORK" ghost="archive." position="left" />
      <div className="wrap">
        <div className="work__head">
          <div>
            <span className="eyebrow">Selected work · 2023 — 2026</span>
            <h2 className="mega" style={{ marginTop: 16 }}>
              We made <span className="t-serif" style={{ color: "var(--pink)" }}>these</span><br />a little famous.
            </h2>
          </div>
          <p style={{ maxWidth: 320 }}>A few projects we're proud of. Click any of them to ask us how we'd do yours.</p>
        </div>

        <div className="work-grid">
          {cases.map((c, i) => (
            <article key={i} className={`case ${c.cls}`} data-cursor="hot" data-label="OPEN">
              <div className={`case__visual viz ${c.viz}`}>{c.visual}</div>
              <div className="case__meta">
                <div>
                  <div className="case__cat">{c.cat}</div>
                  <div className="case__name">{c.name} <span style={{ fontFamily: "var(--f-serif)", fontStyle: "italic", fontWeight: 400, opacity: 0.7 }}>— {c.title}</span></div>
                </div>
                <span className="case__tag">{c.tag}</span>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function BigStamp({ text, sub }) {
  return (
    <div style={{ textAlign: "center", lineHeight: 0.82 }}>
      <div style={{ fontSize: "clamp(60px, 9vw, 150px)", textShadow: "5px 5px 0 var(--ink)" }}>{text}</div>
      <div style={{ fontFamily: "var(--f-serif)", fontStyle: "italic", fontWeight: 400, fontSize: "clamp(50px, 8vw, 140px)", color: "var(--ink)", letterSpacing: "-0.02em" }}>{sub}.</div>
      <div style={{ position: "absolute", top: 18, right: 18, fontFamily: "var(--f-mono)", color: "var(--ink)", fontSize: 11, padding: "4px 10px", background: "var(--acid)", borderRadius: 999, transform: "rotate(8deg)" }}>SCOOPED FRESH</div>
    </div>
  );
}
function FoldViz() {
  return (
    <div style={{ width: "82%", maxWidth: 420, background: "var(--paper)", color: "var(--ink)", borderRadius: 18, padding: 18, boxShadow: "10px 10px 0 var(--ink)", border: "2px solid var(--ink)" }}>
      <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "var(--f-mono)", fontSize: 11, opacity: 0.6 }}>
        <span>FOLD · BALANCE</span><span>NOV 24</span>
      </div>
      <div style={{ fontFamily: "var(--f-display)", fontWeight: 900, fontSize: 56, lineHeight: 1, marginTop: 8, letterSpacing: "-0.04em" }}>
        ₹4,29,810
      </div>
      <div style={{ display: "flex", gap: 6, marginTop: 14 }}>
        {[34, 56, 22, 78, 44, 90, 60].map((h, i) => (
          <div key={i} style={{ flex: 1, height: h, background: i === 5 ? "var(--mint)" : "var(--ink)", borderRadius: 4 }}></div>
        ))}
      </div>
      <div style={{ marginTop: 12, display: "flex", justifyContent: "space-between", fontFamily: "var(--f-mono)", fontSize: 11 }}>
        <span>+12.4% this month</span><span style={{ background: "var(--mint)", padding: "2px 8px", borderRadius: 999 }}>▲ UP</span>
      </div>
    </div>
  );
}
function HaloViz() {
  return (
    <div style={{ textAlign: "center" }}>
      <div className="spin" style={{ fontSize: 200, lineHeight: 1, color: "var(--blue)" }}>◯</div>
      <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", flexDirection: "column", pointerEvents: "none" }}>
        <span style={{ fontFamily: "var(--f-serif)", fontStyle: "italic", fontSize: 48, letterSpacing: "-0.02em" }}>halo.</span>
        <span style={{ fontFamily: "var(--f-mono)", fontSize: 11, opacity: 0.6, letterSpacing: "0.1em" }}>BREATHE IN</span>
      </div>
    </div>
  );
}
function BoltViz() {
  return (
    <div style={{ textAlign: "center" }}>
      <div style={{ fontSize: "clamp(70px, 10vw, 130px)", lineHeight: 0.85, textShadow: "4px 4px 0 var(--ink)" }}>⚡</div>
      <div style={{ fontFamily: "var(--f-display)", fontWeight: 900, fontSize: 38, marginTop: -8, letterSpacing: "-0.03em" }}>BOLT</div>
      <div style={{ fontFamily: "var(--f-serif)", fontStyle: "italic", fontSize: 22, marginTop: -2 }}>specialty coffee.</div>
    </div>
  );
}
function PilotViz() {
  return (
    <div style={{ width: "82%", textAlign: "center" }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 6, marginBottom: 16 }}>
        {["P","I","L","O","T","S"].map((l, i) => (
          <div key={i} style={{ background: ["var(--pink)","var(--acid)","var(--mint)","var(--lava)","var(--lilac)","var(--blue)"][i], color: i === 1 ? "var(--ink)" : "var(--paper)", padding: "14px 0", fontFamily: "var(--f-display)", fontWeight: 900, fontSize: 32, border: "2px solid var(--paper)", borderRadius: 8 }}>{l}</div>
        ))}
      </div>
      <div style={{ fontFamily: "var(--f-mono)", fontSize: 11, opacity: 0.6 }}>PILOT · INDIE GAME STUDIOS · BRAND SYSTEM</div>
    </div>
  );
}

/* ---------- PROCESS ---------- */
function Process() {
  const steps = [
    { n: "01", title: <>Interr<em>ogate.</em></>, body: "We get nosy. Two weeks of questions, audits and uncomfortable truths. We arrive with opinions; we leave with a brief.", hand: "🔍", rot: "-2deg" },
    { n: "02", title: <>Pro<em>voke.</em></>, body: "We sketch the safe option and the unsafe one. We pitch the unsafe one harder. You decide.", hand: "✺", rot: "1.5deg" },
    { n: "03", title: <>Sh<em>ip.</em></>, body: "We design, build and launch with teeth. Every handoff is dev-ready, every milestone has a date — and it sticks.", hand: "🚀", rot: "-1deg" },
    { n: "04", title: <>St<em>ay.</em></>, body: "We don't ghost after launch. 60-day support, optimization sprints, and a Slack channel we actually answer in.", hand: "♥", rot: "2deg" },
  ];
  return (
    <section className="process noise grid-paper" id="process">
      <Furniture num="05" label="HOW IT WORKS" ghost="process." position="right" />
      <div className="wrap">
        <div className="process__head">
          <span className="eyebrow">How it works · 04 phases</span>
          <h2 className="mega" style={{ marginTop: 16 }}>
            A process that<br /><span className="t-serif">refuses to be</span> generic.
          </h2>
        </div>
        <div className="process-grid">
          {steps.map((s, i) => (
            <div key={i} className="step noise" style={{ "--rot": s.rot }}>
              <div>
                <div className="step__num">PHASE {s.n} / 04</div>
                <h3 className="step__title">{s.title}</h3>
                <p className="step__body">{s.body}</p>
              </div>
              <div className="step__hand">{s.hand}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Cursor, Nav, Hero, Ticker, Services, Work, Process, Furniture });

function Furniture({ num, label, ghost = "", position = "right", stars = true }) {
  // Editorial decoration for plain sections: ghost section number, spine label,
  // corner crop/registration marks, and a few scattered serif glyphs.
  return (
    <div className={`furniture furniture--${position}`} aria-hidden="true">
      <span className="furniture__num">{num}</span>
      {ghost && <span className="furniture__ghost">{ghost}</span>}
      <span className="furniture__spine">
        <span>SECTION {num}</span>
        <span className="dash"></span>
        <span>{label}</span>
        <span className="dash"></span>
        <span>VIRAL inbound.</span>
      </span>
      <span className="furniture__cross furniture__cross--tl"></span>
      <span className="furniture__cross furniture__cross--tr"></span>
      <span className="furniture__cross furniture__cross--bl"></span>
      <span className="furniture__cross furniture__cross--br"></span>
      {stars && (
        <>
          <span className="furniture__star" style={{ top: "20%", left: "8%", transform: "rotate(-12deg)" }}>✦</span>
          <span className="furniture__star" style={{ top: "70%", left: "12%", transform: "rotate(8deg)" }}>★</span>
          <span className="furniture__star" style={{ top: "30%", right: "9%", transform: "rotate(15deg)" }}>✺</span>
          <span className="furniture__star" style={{ top: "82%", right: "14%", transform: "rotate(-6deg)" }}>◯</span>
        </>
      )}
    </div>
  );
}
