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

// === Helpers ===
function renderRich(parts) {
  if (typeof parts === "string") return parts;
  if (!Array.isArray(parts)) return null;
  return parts.map((p, i) => {
    if (typeof p === "string") return <React.Fragment key={i}>{p}</React.Fragment>;
    if (p.grad) return <span key={i} className="grad">{p.grad}</span>;
    if (p.alt) return <span key={i} className="alt">{p.alt}</span>;
    return null;
  });
}

function SectionTag({ data }) {
  return (
    <div className="section-tag">
      <span className="num">{data[0]}</span>
      <span className="bar"></span>
      <span className="label">{data[1]}</span>
    </div>
  );
}

function Placeholder({ label, corner = "EDU3D · IMG", tint = "" }) {
  return (
    <div className={`ph ${tint}`}>
      <span className="ph-corner">{corner}</span>
      <span className="ph-label">{label}</span>
    </div>
  );
}

function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12 }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

function useParallax() {
  useEffect(() => {
    const els = document.querySelectorAll("[data-parallax]");
    function onScroll() {
      const vh = window.innerHeight;
      els.forEach((el) => {
        const r = el.getBoundingClientRect();
        const center = r.top + r.height / 2 - vh / 2;
        const speed = parseFloat(el.dataset.parallax) || 0.1;
        const offset = -center * speed;
        el.style.transform = `translate3d(0, ${offset.toFixed(1)}px, 0)`;
      });
    }
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
}

// === Nav ===
function Nav({ lang, setLang, t }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <nav className={`nav ${scrolled ? "scrolled" : ""}`}>
      <a href="#top" className="nav-logo">
        <span className="dot"></span>
        EDU3D
      </a>
      <div className="nav-links">
        <a href="#manifesto">{t.nav.manifesto}</a>
        <a href="#work">{t.nav.work}</a>
        <a href="#cases">{t.nav.cases}</a>
        <a href="#workflow">{t.nav.workflow}</a>
        <a href="#contact">{t.nav.contact}</a>
        <span className="lang-toggle">
          <button className={lang === "pt" ? "active" : ""} onClick={() => setLang("pt")}>PT</button>
          <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
        </span>
      </div>
    </nav>
  );
}

// === Hero ===
function Hero({ t }) {
  return (
    <section className="hero" id="top">
      <div className="hero-bg" data-parallax="-0.05"></div>
      <div className="hero-grain"></div>
      <div className="hero-stamp" aria-hidden="true">
        <span className="stamp-num">{t.hero.stamp[0]}</span>
        <span>{t.hero.stamp[1]}</span>
        <span style={{ opacity: 0.7 }}>{t.hero.stamp[2]}</span>
      </div>
      <div className="hero-inner">
        <div className="hero-meta">
          <div className="hero-meta-left">
            <span className="mono-label" style={{ display: "block", marginBottom: 12 }}>{t.hero.kicker}</span>
          </div>
          <div className="hero-meta-right">
            {t.hero.meta.map((m, i) => <div key={i}>{m}</div>)}
          </div>
        </div>
        <h1 className="reveal">
          <span className="grad">{t.hero.heroLine1}</span><br />
          <span>{t.hero.heroLine2}</span>
        </h1>
        <p className="hero-sub reveal">{t.hero.sub}</p>
      </div>
      <div className="hero-marquee">
        <div className="hero-marquee-track">
          <span>
            {[...t.hero.marquee, ...t.hero.marquee].map((m, i) => (
              <React.Fragment key={i}>
                {m}
                <span className="star">✦</span>
              </React.Fragment>
            ))}
          </span>
        </div>
      </div>
    </section>
  );
}

// === Manifesto ===
function Manifesto({ t }) {
  return (
    <section className="manifesto" id="manifesto">
      <SectionTag data={t.manifesto.tag} />
      <div className="manifesto-grid">
        <div>
          <h2 className="manifesto-headline reveal">
            {t.manifesto.headline[0]}
            <span className="grad-warm">{t.manifesto.headline[1]}</span>
          </h2>
        </div>
        <div className="manifesto-body">
          <p className="lead reveal">{t.manifesto.lead}</p>
          {t.manifesto.paras.map((p, i) => (
            <p key={i} className="dim reveal">{p}</p>
          ))}
          <div className="manifesto-rule"></div>
          <p className="reveal">{t.manifesto.kicker}</p>
        </div>
      </div>
    </section>
  );
}

// === Transformation ===
function Transformation({ t }) {
  return (
    <section className="transformation" id="work">
      <SectionTag data={t.transformation.tag} />
      <h2 className="transformation-headline reveal">
        {renderRich(t.transformation.headline)}
      </h2>
      <p className="hero-sub reveal" style={{ marginBottom: 56, maxWidth: 600 }}>{t.transformation.sub}</p>
      <div className="tx-grid">
        {t.transformation.steps.map((s, i) => (
          <div key={i} className="tx-step reveal">
            <div className="tx-step-tag">
              <span className="num">{s.num}</span>
              <span>{s.tag}</span>
            </div>
            <div className="tx-step-visual" data-parallax={i === 1 ? "0.06" : "0.03"}>
              <Placeholder
                label={s.visual}
                corner={`STEP ${s.num}`}
                tint={["tinted-purple", "tinted-magenta", "tinted-orange"][i]}
              />
            </div>
            <div className="tx-step-caption">{s.caption}</div>
            {i < 2 && <span className="tx-arrow">→</span>}
          </div>
        ))}
      </div>
    </section>
  );
}

// === Values ===
function Values({ t }) {
  return (
    <section className="values">
      {t.values.items.map((v, i) => (
        <div key={i} className={`value-row v${i + 1}`}>
          <div className="value-bg"></div>
          <div className="value-inner">
            <div className="value-text reveal" style={{ order: i % 2 === 0 ? 0 : 1 }}>
              <span className="num">{v.num} · {t.values.tag[1]}</span>
              <h2>{v.title}</h2>
              <p>{v.body}</p>
            </div>
            <div className="value-visual reveal" data-parallax="0.04">
              <Placeholder
                label={v.visual}
                corner={`V.0${i + 1}`}
                tint={["tinted-purple", "tinted-magenta", "tinted-cyan"][i]}
              />
            </div>
          </div>
        </div>
      ))}
    </section>
  );
}

// === Scale ===
function Scale({ t }) {
  return (
    <section className="scale">
      <div className="scale-inner">
        <div className="scale-grid">
          <div className="reveal">
            <SectionTag data={t.scale.tag} />
            <h2>
              {t.scale.headline[0]}<br />
              {t.scale.headline[1]}<br />
              {t.scale.headline[2]}
              {renderRich([t.scale.headline[3]])}
            </h2>
            <p className="hero-sub" style={{ marginTop: 20 }}>{t.scale.body}</p>
            <div className="scale-stats">
              {t.scale.stats.map((s, i) => (
                <div key={i}>
                  <span className="big">{s.big}</span>
                  {s.label}
                </div>
              ))}
            </div>
          </div>
          <div className="scale-visual reveal" data-parallax="0.05">
            <Placeholder label={t.scale.visual} corner="04 · OOH" tint="tinted-orange" />
          </div>
        </div>
      </div>
    </section>
  );
}

// === AI Workflow ===
function AIWorkflow({ t }) {
  return (
    <section className="ai-workflow">
      <div style={{ padding: "0 var(--pad-x)" }}>
        <SectionTag data={t.ai.tag} />
      </div>
      <h2 className="ai-headline reveal" style={{ marginTop: -24 }}>
        {renderRich(t.ai.headline)}
      </h2>
      <p className="hero-sub reveal" style={{ padding: "0 var(--pad-x) 60px", maxWidth: 600 }}>{t.ai.sub}</p>
      <div className="ai-split">
        <div className="ai-side left reveal">
          <div>
            <span className="mono-label" style={{ display: "block", marginBottom: 16 }}>OLD WAY</span>
            <h3>{t.ai.left.title}</h3>
          </div>
          <ul>
            {t.ai.left.items.map((it, i) => <li key={i}>{it}</li>)}
          </ul>
          <div className="ai-visual">
            <Placeholder label={t.ai.left.visual} corner="3D · TRADITIONAL" tint="tinted-blue" />
          </div>
        </div>
        <div className="ai-side right reveal">
          <div>
            <span className="mono-label" style={{ display: "block", marginBottom: 16, color: "var(--magenta)" }}>NEW WAY</span>
            <h3>{t.ai.right.title}</h3>
          </div>
          <ul>
            {t.ai.right.items.map((it, i) => <li key={i}>{it}</li>)}
          </ul>
          <div className="ai-visual">
            <Placeholder label={t.ai.right.visual} corner="AI · CURATED" tint="tinted-magenta" />
          </div>
        </div>
      </div>
    </section>
  );
}

// === Possibilities ===
function Possibilities({ t }) {
  const tints = ["tinted-purple", "tinted-magenta", "tinted-orange", "tinted-blue", "tinted-cyan", "tinted-purple", "tinted-magenta", "tinted-orange"];
  return (
    <section className="possibilities">
      <SectionTag data={t.possibilities.tag} />
      <h2 className="poss-headline reveal">{renderRich(t.possibilities.headline)}</h2>
      <p className="poss-sub reveal">{t.possibilities.sub}</p>
      <div className="poss-grid">
        {t.possibilities.tiles.map((tile, i) => (
          <div key={i} className={`poss-tile t-${i + 1} reveal`} data-parallax={i % 2 ? "0.02" : "-0.02"}>
            <Placeholder label={tile} corner={`P.0${i + 1}`} tint={tints[i]} />
          </div>
        ))}
      </div>
    </section>
  );
}

// === Philosophy ===
function Philosophy({ t }) {
  return (
    <section className="philosophy">
      <h2 className="philosophy-quote reveal">
        {renderRich(t.philosophy.quote)}
      </h2>
      <div className="philosophy-attr reveal">
        <span className="bar"></span>
        {t.philosophy.attr}
        <span className="bar"></span>
      </div>
    </section>
  );
}

// === Cases ===
function Cases({ t }) {
  return (
    <section className="cases" id="cases">
      <div className="cases-head">
        <div>
          <SectionTag data={t.cases.tag} />
          <h2 className="reveal">{t.cases.headline[0]}<br />{t.cases.headline[1]}</h2>
        </div>
        <p className="hero-sub reveal" style={{ maxWidth: 380 }}>{t.cases.sub}</p>
      </div>
      <div className="case-list">
        {t.cases.items.map((c, i) => (
          <div key={i} className="case-item reveal">
            <span className="case-num">C.0{i + 1}</span>
            <span className="case-name">{c.name}</span>
            <span className="case-prob"><strong>Problema</strong>{c.prob}</span>
            <span className="case-sol"><strong>Solução</strong>{c.sol}</span>
            <span className="case-arrow">→</span>
          </div>
        ))}
      </div>
    </section>
  );
}

// === Workflow ===
function Workflow({ t }) {
  return (
    <section className="workflow" id="workflow">
      <div className="workflow-head">
        <SectionTag data={t.workflow.tag} />
        <h2 className="reveal">{renderRich(t.workflow.headline)}</h2>
        <p className="hero-sub reveal" style={{ maxWidth: 520, marginTop: 8 }}>{t.workflow.sub}</p>
      </div>
      <div className="workflow-flow">
        {t.workflow.flow.map((s, i) => (
          <div key={i} className={`flow-step reveal ${s.highlight ? "highlight" : ""}`}>
            <span className="flow-num">{s.num}</span>
            <div className="flow-name">{s.name}</div>
            <div className="flow-tag">{s.tag}</div>
          </div>
        ))}
      </div>
      <div className="services-grid">
        {t.workflow.services.map((s, i) => (
          <div key={i} className="service reveal">
            <span className="service-num">S.{String(i + 1).padStart(2, "0")}</span>
            <span className="service-name">{s}</span>
          </div>
        ))}
      </div>
    </section>
  );
}

// === Contact ===
function Contact({ t }) {
  return (
    <section className="contact" id="contact">
      <SectionTag data={t.contact.tag} />
      <h2 className="contact-headline reveal">
        {t.contact.headline[0]}<br />
        <span className="grad">{t.contact.headline[1]}</span>
      </h2>
      <p className="contact-sub reveal">{t.contact.sub}</p>
      <p className="hero-sub reveal" style={{ maxWidth: 540, margin: "0 auto 40px" }}>{t.contact.cta}</p>
      <div className="contact-cta reveal">
        <a className="btn btn-primary" href={`mailto:${t.contact.emails[0]}`}>
          {t.contact.ctaPrimary} <span className="arrow">→</span>
        </a>
        <a className="btn btn-ghost" href="#manifesto">
          {t.contact.ctaGhost}
        </a>
      </div>
      <div className="contact-emails reveal">
        {t.contact.emails.map((e, i) => (
          <a key={i} href={`mailto:${e}`}>{e}</a>
        ))}
      </div>
    </section>
  );
}

function Footer({ t }) {
  return (
    <footer className="footer">
      <div className="logo">EDU3D ✦</div>
      <div>{t.footer.left}</div>
      <div>{t.footer.right}</div>
    </footer>
  );
}

// === App ===
function App() {
  const [lang, setLang] = useState(() => {
    return localStorage.getItem("edu3d_lang") || "pt";
  });
  useEffect(() => {
    localStorage.setItem("edu3d_lang", lang);
    document.documentElement.lang = lang === "pt" ? "pt-BR" : "en";
  }, [lang]);

  const t = window.EDU3D_CONTENT[lang];
  useReveal();
  useParallax();

  // re-run reveal when lang changes (DOM swaps)
  useEffect(() => {
    const tm = setTimeout(() => {
      document.querySelectorAll(".reveal").forEach((el) => el.classList.add("in"));
    }, 50);
    return () => clearTimeout(tm);
  }, [lang]);

  return (
    <>
      <Nav lang={lang} setLang={setLang} t={t} />
      <Hero t={t} />
      <Manifesto t={t} />
      <Transformation t={t} />
      <Values t={t} />
      <Scale t={t} />
      <AIWorkflow t={t} />
      <Possibilities t={t} />
      <Philosophy t={t} />
      <Cases t={t} />
      <Workflow t={t} />
      <Contact t={t} />
      <Footer t={t} />
    </>
  );
}

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