// ILUSÃO promo site — atmospheric horror landing
const { useState, useEffect, useRef } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#c9a961",
  "fogIntensity": 0.55,
  "grain": true,
  "flicker": true,
  "treeDensity": 18
}/*EDITMODE-END*/;

// ---------- Translations ----------
const TRANSLATIONS = {
  pt: {
    lang: "pt",
    htmlLang: "pt-BR",
    pageTitle: "ILUSÃO — um jogo de terror psicológico",
    kicker: "UM JOGO DE TERROR PSICOLÓGICO",
    tagline: <>O caminho na floresta é mais longo do que ele lembra.<br/>A floresta é mais antiga do que qualquer mapa.</>,
    typewriterText: "Floresta de Louveira  ·  Outono de 1973",
    enterBtn: "entrar na floresta",
    langToggle: "EN",
    heroMark1: "ILS · 1973 · INT-FIC",
    heroMark2: "CASO Nº LP-1973-0411-MD",
    stamp: "CONFIDENCIAL",
    dept: "POLÍCIA CIVIL · LOUVEIRA",
    case: "LP-1973-0411-MD",
    detective: "MENDONÇA",
    status: "ESCALADO",
    metaDept: "DEPARTAMENTO",
    metaCase: "CASO",
    metaDet: "DETETIVE DESIG.",
    metaStatus: "STATUS",
    s1num: "§ 01",
    s1title: "o que aconteceu em Louveira.",
    p1: <><em>Você</em> joga como o <em>Detetive Mendonça</em>, designado para investigar uma série de desaparecimentos inexplicáveis na borda da cidade. Os moradores não falam. As evidências não fazem sentido. E a floresta no fim da estrada está ali há mais tempo do que qualquer um consegue lembrar.</>,
    p2: <>Quanto mais fundo você cava — entrevistando testemunhas, investigando o terreno, seguindo o rastro dos que sumiram — mais perto chega o momento em que <em>você</em> mesmo vai ter que entrar.</>,
    warn: <><span className="warn-bar" /><span>O que espera lá dentro <strong>não é</strong> o que você espera.</span></>,
    folkloreTag: "— do folclore brasileiro",
    folkloreP: "ILUSÃO bebe da rica tradição do folclore brasileiro, tecendo criaturas da lenda numa história sobre culpa, luto, e as coisas que carregamos conosco no escuro.",
    folkloreQ: <>\"A floresta não apenas leva as pessoas. Ela <u>aprende</u> elas.\"</>,
    s2num: "§ 02",
    s2title: "arquivos anexos.",
    links: [
      { label: "ASSISTIR O TRAILER", sub: "YouTube · release trailer", tag: "VÍDEO", href: "https://youtu.be/Cu6AQsZk3BQ", icon: "▶" },
      { label: "BAIXAR ILUSÃO.exe", sub: "Windows · grátis", tag: "JOGO", href: "ILUSAO_Setup_1.0.0.exe", icon: "↓", download: true },
      { label: "PÁGINA NO ITCH.IO", sub: "comentários, devlogs e atualizações", tag: "ITCH", href: "https://guihonorato.itch.io/ilusao", icon: "↗" },
      { label: "DIÁRIO DO DESENVOLVEDOR", sub: "guilherme honorato · portfólio", tag: "DEV", href: "https://people.rit.edu/gsh8194/portfolio/", icon: "↗" },
    ],
    sigRole: "escrita · direção · programação",
    rights: "ILUSÃO © 1973 / 2025",
    rightsQuote: "\"Isto é uma ilusão. Isto é real.\"",
  },
  en: {
    lang: "en",
    htmlLang: "en",
    pageTitle: "ILUSÃO — a psychological horror game",
    kicker: "A PSYCHOLOGICAL HORROR GAME",
    tagline: <>The path into the forest is longer than he remembers.<br/>The forest is older than any map.</>,
    typewriterText: "Louveira Forest  ·  Autumn of 1973",
    enterBtn: "enter the forest",
    langToggle: "PT",
    heroMark1: "ILS · 1973 · INT-FIC",
    heroMark2: "CASE No. LP-1973-0411-MD",
    stamp: "CONFIDENTIAL",
    dept: "CIVIL POLICE · LOUVEIRA",
    case: "LP-1973-0411-MD",
    detective: "MENDONÇA",
    status: "ESCALATED",
    metaDept: "DEPARTMENT",
    metaCase: "CASE",
    metaDet: "ASSIGNED DET.",
    metaStatus: "STATUS",
    s1num: "§ 01",
    s1title: "what happened in Louveira.",
    p1: <>You play as <em>Detective Mendonça</em>, assigned to investigate a series of unexplained disappearances on the edge of town. The locals won't talk. The evidence makes no sense. And the forest at the end of the road has been there longer than anyone can remember.</>,
    p2: <>The deeper you dig — interviewing witnesses, investigating the land, following the trail of the missing — the closer comes the moment when <em>you</em> have to go in yourself.</>,
    warn: <><span className="warn-bar" /><span>What waits inside is <strong>not</strong> what you expect.</span></>,
    folkloreTag: "— from Brazilian folklore",
    folkloreP: "ILUSÃO draws from the rich tradition of Brazilian folklore, weaving creatures from legend into a story about guilt, grief, and the things we carry with us into the dark.",
    folkloreQ: <>\"The forest doesn't just take people. It <u>learns</u> them.\"</>,
    s2num: "§ 02",
    s2title: "attached files.",
    links: [
      { label: "WATCH THE TRAILER", sub: "YouTube · release trailer", tag: "VIDEO", href: "https://youtu.be/Cu6AQsZk3BQ", icon: "▶" },
      { label: "DOWNLOAD ILUSÃO.exe", sub: "Windows · free", tag: "GAME", href: "ILUSAO_Setup_1.0.0.exe", icon: "↓", download: true },
      { label: "ITCH.IO PAGE", sub: "comments, devlogs and updates", tag: "ITCH", href: "https://guihonorato.itch.io/ilusao", icon: "↗" },
      { label: "DEVELOPER'S DIARY", sub: "guilherme honorato · portfolio", tag: "DEV", href: "https://people.rit.edu/gsh8194/portfolio/", icon: "↗" },
    ],
    sigRole: "writing · direction · programming",
    rights: "ILUSÃO © 1973 / 2025",
    rightsQuote: "\"This is an illusion. This is real.\"",
  }
};

// ---------- Fog layer ----------
function Fog({ intensity }) {
  return (
    <div className="fog-wrap" aria-hidden style={{ opacity: intensity }}>
      <svg className="fog" viewBox="0 0 1600 900" preserveAspectRatio="xMidYMid slice">
        <defs>
          <filter id="fogBlur" x="-20%" y="-20%" width="140%" height="140%">
            <feTurbulence type="fractalNoise" baseFrequency="0.012 0.018" numOctaves="2" seed="3" />
            <feDisplacementMap in="SourceGraphic" scale="60" />
            <feGaussianBlur stdDeviation="40" />
          </filter>
        </defs>
        <g filter="url(#fogBlur)" opacity="0.5">
          <ellipse className="fog-blob fog-a" cx="400" cy="650" rx="600" ry="160" fill="#3a5a3a" />
          <ellipse className="fog-blob fog-b" cx="1200" cy="720" rx="700" ry="180" fill="#2a4030" />
          <ellipse className="fog-blob fog-c" cx="800" cy="500" rx="900" ry="140" fill="#4a6a4a" />
        </g>
      </svg>
    </div>
  );
}

// ---------- Trees ----------
function Trees({ density }) {
  const trees = [];
  const seed = (i) => (Math.sin(i * 9301 + 49297) * 233280) % 1;
  for (let i = 0; i < density; i++) {
    const r = Math.abs(seed(i));
    const x = (i / density) * 100 + (r - 0.5) * 6;
    const h = 32 + r * 38;
    const w = 1.4 + r * 2.2;
    const z = i % 3;
    trees.push({ x, h, w, z, i });
  }
  return (
    <div className="trees" aria-hidden>
      {trees.map(t => (
        <div key={t.i} className={`tree tree-z${t.z}`} style={{ left: `${t.x}%`, height: `${t.h}vh`, width: `${t.w}px` }}>
          <div className="trunk" />
          <div className="branches">
            {[...Array(5 + t.z)].map((_, j) => {
              const top = 10 + j * 14 + (Math.abs(seed(t.i + j * 3)) * 6);
              const len = 12 + Math.abs(seed(t.i + j * 7)) * 26 - j * 1.5;
              const side = j % 2 === 0 ? 'L' : 'R';
              const angle = 18 + Math.abs(seed(t.i + j)) * 22;
              return (
                <span key={j} className={`branch branch-${side}`} style={{ top: `${top}%`, width: `${len}px`, transform: `rotate(${side === 'L' ? -angle : angle}deg)` }} />
              );
            })}
          </div>
        </div>
      ))}
    </div>
  );
}

// ---------- Grain ----------
function Grain() {
  return (
    <svg className="grain" aria-hidden>
      <filter id="grainFilter">
        <feTurbulence type="fractalNoise" baseFrequency="0.9" numOctaves="2" stitchTiles="stitch" />
        <feColorMatrix values="0 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 0.55 0" />
      </filter>
      <rect width="100%" height="100%" filter="url(#grainFilter)" />
    </svg>
  );
}

// ---------- Language Toggle ----------
function LangToggle({ lang, onToggle, accent }) {
  return (
    <button
      onClick={onToggle}
      className="lang-toggle"
      style={{ borderColor: accent, color: accent }}
      title={lang === 'pt' ? 'Switch to English' : 'Mudar para Português'}
    >
      {lang === 'pt' ? 'EN' : 'PT'}
    </button>
  );
}

// ---------- Hero ----------
function Hero({ t, tr, onLangToggle }) {
  const [typed, setTyped] = useState("");
  const full = tr.typewriterText;
  useEffect(() => {
    setTyped("");
    let i = 0;
    const id = setInterval(() => {
      i++;
      setTyped(full.slice(0, i));
      if (i >= full.length) clearInterval(id);
    }, 55);
    return () => clearInterval(id);
  }, [full]);

  return (
    <section className="hero" data-screen-label="01 Hero">
      <Fog intensity={t.fogIntensity} />
      <div className="vignette" aria-hidden />
      <LangToggle lang={tr.lang} onToggle={onLangToggle} accent={t.accent} />

      <div className="hero-inner">
        <div className="kicker">
          <span className="kicker-dot" />
          {tr.kicker}
          <span className="kicker-dot" />
        </div>

        <h1 className={`title ${t.flicker ? 'flicker' : ''}`} style={{ color: t.accent }}>
          ILUSÃO
        </h1>

        <div className="serif-rule" style={{ background: `linear-gradient(90deg, transparent, ${t.accent}66, transparent)` }} />

        <p className="tagline">{tr.tagline}</p>

        <p className="typewriter">{typed}<span className="caret">▍</span></p>

        <a href="#dossie" className="enter">
          <span>{tr.enterBtn}</span>
          <span className="enter-arrow">↓</span>
        </a>
      </div>

      <div className="hero-foot">
        <div className="mark">{tr.heroMark1}</div>
        <div className="mark">{tr.heroMark2}</div>
      </div>
    </section>
  );
}

// ---------- Dossier ----------
function Dossier({ t, tr }) {
  return (
    <section className="dossier" id="dossie" data-screen-label="02 Dossier">
      <div className="paper-bg" aria-hidden />

      <div className="dossier-inner">
        <header className="dossier-head">
          <div className="stamp"><span>{tr.stamp}</span></div>
          <div className="case-meta">
            <div><span className="meta-k">{tr.metaDept}</span><span className="meta-v">{tr.dept}</span></div>
            <div><span className="meta-k">{tr.metaCase}</span><span className="meta-v">{tr.case}</span></div>
            <div><span className="meta-k">{tr.metaDet}</span><span className="meta-v">{tr.detective}</span></div>
            <div><span className="meta-k">{tr.metaStatus}</span><span className="meta-v status-esc">{tr.status}</span></div>
          </div>
        </header>

        <div className="brief">
          <h2 className="brief-title" style={{ color: t.accent }}>
            <span className="brief-num">{tr.s1num}</span>
            {tr.s1title}
          </h2>
          <div className="brief-body">
            <p>{tr.p1}</p>
            <p>{tr.p2}</p>
            <p className="warn">{tr.warn}</p>
          </div>

          <aside className="folklore">
            <div className="folklore-tag">{tr.folkloreTag}</div>
            <p>{tr.folkloreP}</p>
            <p className="folklore-quote" style={{ color: t.accent }}>{tr.folkloreQ}</p>
          </aside>
        </div>

        <div className="evidence">
          <h2 className="brief-title" style={{ color: t.accent }}>
            <span className="brief-num">{tr.s2num}</span>
            {tr.s2title}
          </h2>

          <div className="link-grid">
            {tr.links.map((l, i) => (
              <a
                key={i}
                href={l.href}
                className="link-card"
                style={{ '--accent': t.accent }}
                {...(l.download ? { download: true } : { target: "_blank", rel: "noopener noreferrer" })}
              >
                <div className="lc-tag">{l.tag}</div>
                <div className="lc-icon" style={{ color: t.accent }}>{l.icon}</div>
                <div className="lc-body">
                  <div className="lc-label">{l.label}</div>
                  <div className="lc-sub">{l.sub}</div>
                </div>
                <div className="lc-corner" style={{ borderColor: t.accent }} />
              </a>
            ))}
          </div>
        </div>

        <footer className="dossier-foot">
          <div className="sig">
            <div className="sig-line" style={{ background: t.accent }} />
            <div className="sig-name">guilherme honorato</div>
            <div className="sig-role">{tr.sigRole}</div>
          </div>
          <div className="rights">
            <div>{tr.rights}</div>
            <div className="rights-sub">{tr.rightsQuote}</div>
          </div>
        </footer>
      </div>
    </section>
  );
}

// ---------- Panel ----------
function Panel({ t, setTweak, tr }) {
  return (
    <TweaksPanel>
      <TweakSection title={tr.lang === 'pt' ? "Atmosfera" : "Atmosphere"}>
        <TweakColor
          label={tr.lang === 'pt' ? "Cor de acento" : "Accent colour"}
          value={t.accent}
          onChange={(v) => setTweak('accent', v)}
          options={['#c9a961', '#a8895a', '#d4b35a', '#8b9d6a', '#9b3d2a', '#e8c878']}
        />
        <TweakSlider
          label={tr.lang === 'pt' ? "Densidade da névoa" : "Fog density"}
          value={t.fogIntensity}
          onChange={(v) => setTweak('fogIntensity', v)}
          min={0} max={1} step={0.05}
        />
        <TweakToggle
          label={tr.lang === 'pt' ? "Grão de película" : "Film grain"}
          value={t.grain}
          onChange={(v) => setTweak('grain', v)}
        />
        <TweakToggle
          label={tr.lang === 'pt' ? "Flicker no título" : "Title flicker"}
          value={t.flicker}
          onChange={(v) => setTweak('flicker', v)}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

// ---------- App ----------
function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [lang, setLang] = useState('pt');
  const tr = TRANSLATIONS[lang];

  const toggleLang = () => setLang(l => l === 'pt' ? 'en' : 'pt');

  useEffect(() => {
    document.title = tr.pageTitle;
    document.documentElement.lang = tr.htmlLang;
  }, [tr]);

  return (
    <>
      <Hero t={t} tr={tr} onLangToggle={toggleLang} />
      <Dossier t={t} tr={tr} />
      {t.grain && <Grain />}
      <Panel t={t} setTweak={setTweak} tr={tr} />
    </>
  );
}

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