const { useState, useEffect, useMemo, useRef } = React;

/* ==================================================== */
/*  TWEAKS                                              */
/* ==================================================== */
function TweaksPanel({ tweaks, setTweaks, visible }) {
  if (!visible) return null;
  const update = (k, v) => {
    const next = { ...tweaks, [k]: v };
    setTweaks(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [k]: v } }, '*');
  };
  const reset = () => {
    setTweaks({ ...window.__TWEAK_DEFAULTS_SNAPSHOT__ });
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { ...window.__TWEAK_DEFAULTS_SNAPSHOT__ } }, '*');
  };
  const fields = [
  { k: 'heroPretitle', label: 'Pré-título', tag: 'input' },
  { k: 'heroTitleA', label: 'Título · linha 1', tag: 'input' },
  { k: 'heroTitleStrike', label: 'Título · palavra riscada', tag: 'input' },
  { k: 'heroTitleB', label: 'Título · linha 2', tag: 'input' },
  { k: 'heroTitleAccent', label: 'Título · palavra em destaque', tag: 'input' },
  { k: 'heroLede', label: 'Descrição', tag: 'textarea' },
  { k: 'heroCtaPrimary', label: 'Botão primário', tag: 'input' },
  { k: 'heroCtaSecondary', label: 'Botão secundário', tag: 'input' }];

  return (
    <div className="tweaks-panel">
      <div className="t-head">
        <span className="t-title">Tweaks · Hero copy</span>
        <button className="reset" onClick={reset}>Reset</button>
      </div>
      <div style={{ maxHeight: '60vh', overflowY: 'auto', paddingRight: 4 }}>
        {fields.map((f) =>
        <div className="t-group" key={f.k}>
            <label>{f.label}</label>
            {f.tag === 'textarea' ?
          <textarea rows={3} value={tweaks[f.k] || ''} onChange={(e) => update(f.k, e.target.value)} /> :
          <input type="text" value={tweaks[f.k] || ''} onChange={(e) => update(f.k, e.target.value)} />}
          </div>
        )}
      </div>
    </div>);

}

/* ==================================================== */
/*  NAV                                                 */
/* ==================================================== */
function Nav() {
  return (
    <nav className="top">
      <div className="row">
        <div className="brand"><span className="dot" />liberta</div>
        <div className="nav-links">
          <a href="#maleficios">Malefícios</a>
          <a href="#pulmao">Seu pulmão</a>
          <a href="#economia">Economia</a>
          <a href="#faq">FAQ</a>
        </div>
        <a href="#entrar" className="btn btn-primary" style={{ padding: '10px 18px', fontSize: 13 }}>
          Entrar <span className="arrow">→</span>
        </a>
      </div>
    </nav>);

}

/* ==================================================== */
/*  VAPE ILLUSTRATION — redesenho completo              */
/* ==================================================== */
function VapeFloat() {
  return (
    <div className="vape-hero" style={{
      position: 'absolute', right: 0, top: 0, bottom: 0,
      width: '52%', pointerEvents: 'none', zIndex: 1,
      display: 'flex', alignItems: 'center', justifyContent: 'flex-end'
    }}>
      <svg viewBox="0 0 480 700" fill="none" xmlns="http://www.w3.org/2000/svg"
      style={{ width: '100%', height: '100%', maxWidth: 560, filter: 'drop-shadow(0 60px 120px rgba(0,0,0,.8))' }}>
        <defs>
          {/* body gradient - premium gloss */}
          <linearGradient id="bodyGrad" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0" stopColor="#0f0c0a" />
            <stop offset="0.3" stopColor="#1e1915" />
            <stop offset="0.55" stopColor="#2e2820" />
            <stop offset="0.75" stopColor="#1a1612" />
            <stop offset="1" stopColor="#0a0806" />
          </linearGradient>
          <linearGradient id="bodyGradV" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor="#24201a" />
            <stop offset="0.5" stopColor="#161210" />
            <stop offset="1" stopColor="#0a0806" />
          </linearGradient>
          {/* edge highlight */}
          <linearGradient id="edgeLeft" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0" stopColor="#4a4038" stopOpacity=".8" />
            <stop offset="1" stopColor="#4a4038" stopOpacity="0" />
          </linearGradient>
          <linearGradient id="edgeRight" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0" stopColor="#3a3028" stopOpacity="0" />
            <stop offset="1" stopColor="#504540" stopOpacity=".6" />
          </linearGradient>
          {/* glow */}
          <radialGradient id="redGlow" cx=".5" cy=".5" r=".5">
            <stop offset="0" stopColor="oklch(58% 0.19 25)" stopOpacity=".9" />
            <stop offset="0.5" stopColor="oklch(48% 0.15 25)" stopOpacity=".4" />
            <stop offset="1" stopColor="oklch(38% 0.1 25)" stopOpacity="0" />
          </radialGradient>
          <radialGradient id="ambientGlow" cx=".5" cy="1" r=".7">
            <stop offset="0" stopColor="oklch(58% 0.19 25)" stopOpacity=".35" />
            <stop offset="1" stopColor="oklch(38% 0.1 25)" stopOpacity="0" />
          </radialGradient>
          {/* screen gradient */}
          <linearGradient id="screenGrad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor="#0a1520" />
            <stop offset="1" stopColor="#05080f" />
          </linearGradient>
          {/* smoke gradient */}
          <radialGradient id="smokeGrad" cx=".5" cy=".5" r=".5">
            <stop offset="0" stopColor="#3a3530" stopOpacity=".5" />
            <stop offset="1" stopColor="#3a3530" stopOpacity="0" />
          </radialGradient>
          <filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
            <feGaussianBlur stdDeviation="8" result="blur" />
            <feMerge><feMergeNode in="blur" /><feMergeNode in="SourceGraphic" /></feMerge>
          </filter>
          <filter id="softGlow" x="-100%" y="-100%" width="300%" height="300%">
            <feGaussianBlur stdDeviation="20" />
          </filter>
          <filter id="smokeBlur">
            <feGaussianBlur stdDeviation="12" />
          </filter>
        </defs>

        {/* ── ambient floor glow ── */}
        <ellipse cx="240" cy="680" rx="160" ry="40" fill="url(#ambientGlow)" filter="url(#softGlow)" />

        {/* ── SMOKE ── */}
        <g opacity=".55">
          <ellipse cx="220" cy="80" rx="55" ry="28" fill="url(#smokeGrad)" filter="url(#smokeBlur)">
            <animate attributeName="cy" values="80;60;80" dur="4s" repeatCount="indefinite" />
            <animate attributeName="opacity" values=".55;.2;.55" dur="4s" repeatCount="indefinite" />
          </ellipse>
          <ellipse cx="270" cy="50" rx="40" ry="22" fill="url(#smokeGrad)" filter="url(#smokeBlur)">
            <animate attributeName="cy" values="50;28;50" dur="5s" repeatCount="indefinite" />
            <animate attributeName="opacity" values=".4;.1;.4" dur="5s" repeatCount="indefinite" />
          </ellipse>
          <ellipse cx="200" cy="40" rx="30" ry="16" fill="url(#smokeGrad)" filter="url(#smokeBlur)">
            <animate attributeName="cy" values="40;15;40" dur="6s" repeatCount="indefinite" />
            <animate attributeName="opacity" values=".3;.05;.3" dur="6s" repeatCount="indefinite" />
          </ellipse>
        </g>

        {/* ── MOUTHPIECE ── */}
        <rect x="188" y="105" width="104" height="56" rx="14" fill="#181410" stroke="#2e2820" strokeWidth="1.5" />
        {/* mouthpiece top lip */}
        <rect x="196" y="108" width="88" height="10" rx="5" fill="#24201a" opacity=".8" />
        {/* mouthpiece inner channel */}
        <rect x="210" y="116" width="60" height="36" rx="6" fill="#0d0a08" stroke="#1a1612" strokeWidth="1" />

        {/* ── BODY MAIN ── */}
        <rect x="168" y="158" width="144" height="420" rx="22" fill="url(#bodyGradV)" stroke="#2a2420" strokeWidth="1.5" />

        {/* left edge highlight */}
        <rect x="168" y="158" width="18" height="420" rx="12" fill="url(#edgeLeft)" opacity=".6" />
        {/* right edge highlight */}
        <rect x="294" y="158" width="18" height="420" rx="12" fill="url(#edgeRight)" opacity=".6" />
        {/* top surface catch light */}
        <ellipse cx="240" cy="162" rx="56" ry="6" fill="#3a3530" opacity=".35" />

        {/* ── BRAND ENGRAVING LINE ── */}
        <text x="240" y="242" textAnchor="middle"
        fontFamily="'JetBrains Mono', monospace" fontSize="9" letterSpacing="6"
        fill="#3a3530" opacity=".7">LIBERTA</text>
        <line x1="185" y1="250" x2="295" y2="250" stroke="#2e2820" strokeWidth=".5" opacity=".8" />

        {/* ── LED BUTTON ── */}
        <rect x="214" y="262" width="52" height="52" rx="10" fill="#0d0a08" stroke="#2a2420" strokeWidth="1.5" />
        {/* button texture */}
        <rect x="218" y="266" width="44" height="44" rx="8" fill="#101010" opacity=".8" />
        {/* power icon */}
        <circle cx="240" cy="288" r="10" stroke="oklch(58% 0.19 25)" strokeWidth="1.5" fill="none" opacity=".8" />
        <line x1="240" y1="278" x2="240" y2="285" stroke="oklch(58% 0.19 25)" strokeWidth="2" strokeLinecap="round" />
        {/* button glow */}
        <ellipse cx="240" cy="288" rx="24" ry="24" fill="url(#redGlow)" filter="url(#softGlow)" opacity=".6">
          <animate attributeName="opacity" values=".6;.2;.6" dur="2.5s" repeatCount="indefinite" />
        </ellipse>

        {/* ── SCREEN ── */}
        <rect x="196" y="330" width="88" height="130" rx="6" fill="url(#screenGrad)" stroke="#1a2030" strokeWidth="1" />
        {/* screen scanlines */}
        <rect x="196" y="330" width="88" height="130" rx="6" fill="none"
        style={{ backgroundImage: 'repeating-linear-gradient(0deg,rgba(255,255,255,.03) 0 1px,transparent 1px 3px)' }} />
        {/* battery bar */}
        <text x="240" y="352" textAnchor="middle"
        fontFamily="'JetBrains Mono',monospace" fontSize="7" fill="#2a4060" letterSpacing="2">BATT</text>
        <rect x="206" y="358" width="68" height="7" rx="2" fill="#0a1520" />
        <rect x="206" y="358" width="45" height="7" rx="2" fill="oklch(58% 0.19 25)" opacity=".7" />
        {/* puff counter */}
        <text x="240" y="388" textAnchor="middle"
        fontFamily="'Instrument Serif',serif" fontSize="36" fill="#f1ece4" opacity=".9" letterSpacing="-1">847</text>
        <text x="240" y="402" textAnchor="middle"
        fontFamily="'JetBrains Mono',monospace" fontSize="6" fill="#2a4060" letterSpacing="3">PUFFS</text>
        {/* nic level */}
        <text x="240" y="424" textAnchor="middle"
        fontFamily="'JetBrains Mono',monospace" fontSize="7" fill="oklch(58% 0.19 25)" letterSpacing="2" opacity=".8">50mg/ml</text>
        {/* bottom divider */}
        <line x1="206" y1="435" x2="274" y2="435" stroke="#1a2030" strokeWidth=".5" />
        <text x="240" y="447" textAnchor="middle"
        fontFamily="'JetBrains Mono',monospace" fontSize="6" fill="#1a2030" letterSpacing="2">DESCARTÁVEL</text>

        {/* ── AIR INLET SLOTS ── */}
        {[0, 1, 2].map((i) =>
        <rect key={i} x="210" y={476 + i * 12} width="60" height="4" rx="2" fill="#0d0a08" stroke="#1a1612" strokeWidth=".5" />
        )}

        {/* ── BASE ── */}
        <rect x="178" y="572" width="124" height="14" rx="4" fill="#0f0c0a" stroke="#2a2420" strokeWidth="1" />
        <rect x="185" y="580" width="110" height="6" rx="2" fill="#1a1612" />

        {/* ── USB-C PORT ── */}
        <rect x="222" y="582" width="36" height="10" rx="3" fill="#0a0806" stroke="#2a2420" strokeWidth=".8" />
        <rect x="228" y="585" width="24" height="4" rx="1.5" fill="#161210" />

        {/* ── CONDENSATION DROPS ── */}
        {[{ x: 178, y: 300, r: 2.5 }, { x: 312, y: 380, r: 1.8 }, { x: 174, y: 450, r: 1.4 }, { x: 310, y: 280, r: 2 }].map((d, i) =>
        <circle key={i} cx={d.x} cy={d.y} r={d.r} fill="#2a2520" stroke="#3a3530" strokeWidth=".5" opacity=".7" />
        )}

        {/* ── SIDE LED STRIP ── */}
        <rect x="168" y="390" width="4" height="60" rx="2" fill="oklch(58% 0.19 25)" opacity=".5">
          <animate attributeName="opacity" values=".5;.15;.5" dur="2s" repeatCount="indefinite" />
        </rect>
        <rect x="168" y="390" width="4" height="60" rx="2" fill="oklch(58% 0.19 25)" filter="url(#softGlow)" opacity=".8">
          <animate attributeName="opacity" values=".8;.2;.8" dur="2s" repeatCount="indefinite" />
        </rect>

        {/* ── REFLECTION SHEEN ── */}
        <path d="M 190 168 Q 200 165 200 580 L 188 580 Q 186 168 190 168 Z"
        fill="white" opacity=".025" />
      </svg>
    </div>);

}

/* ==================================================== */
/*  HERO                                                */
/* ==================================================== */
function Hero({ tweaks }) {
  return (
    <section className="hero">
      <div className="grid-bg" />
      <VapeFloat />
      <div className="container" style={{ position: 'relative', zIndex: 2 }}>
        <div style={{ maxWidth: '75%', minWidth: 320 }}>
        <span className="eyebrow"><span className="pulse" />{tweaks.heroPretitle}</span>
        <h1 className="display">
          {tweaks.heroTitleA} <span className="strike">{tweaks.heroTitleStrike}</span>.<br />
          {tweaks.heroTitleB} <em>{tweaks.heroTitleAccent}</em>.
        </h1>
        <p className="hero-lede">{tweaks.heroLede}</p>
        <div className="hero-cta">
          <a href="#entrar" className="btn btn-primary">{tweaks.heroCtaPrimary} <span className="arrow">→</span></a>
          <a href="#pulmao" className="btn btn-ghost">{tweaks.heroCtaSecondary}</a>
        </div>
        </div>
        <div className="hero-meta">
          <div className="cell"><div className="k">Duração</div><div className="v">30 <em>dias</em></div></div>
          <div className="cell"><div className="k">Formato</div><div className="v">100% online</div></div>
          <div className="cell"><div className="k">Custo</div><div className="v">grátis</div></div>
          <div className="cell"><div className="k">Vagas</div><div className="v"><em>disponíveis</em></div></div>
        </div>
      </div>
    </section>);

}

/* ==================================================== */
/*  MALEFÍCIOS — 8 cards iguais (4×2)                  */
/* ==================================================== */
function Harms() {
  const items = [
  { tag: 'Nicotina', stat: '50', unit: 'mg/ml', title: 'Um pod = maços de cigarro', body: 'Um descartável comum carrega nicotina equivalente a vários maços. O vício é bioquímico — não falta de força de vontade.' },
  { tag: 'Metais', stat: '10+', unit: 'tipos', title: 'Chumbo, níquel, cromo no vapor', body: 'O aerossol que você inala carrega partículas metálicas liberadas pela resistência aquecida a cada puff.' },
  { tag: 'Químicos', stat: '2k+', unit: '', title: 'Compostos ainda não catalogados', body: 'A maioria dos efeitos de longo prazo segue desconhecida. Você é um experimento sem grupo de controle.' },
  { tag: 'EVALI', stat: '68', unit: 'mortes', title: 'Lesão pulmonar associada ao vape', body: 'Casos documentados pelo CDC em surto recente. A síndrome é aguda, de evolução rápida e pode ser fatal.' },
  { tag: 'Cérebro', stat: '25', unit: 'anos', title: 'Seu cérebro ainda se desenvolve', body: 'Até os 25 anos, a nicotina altera circuitos de atenção, memória e controle de impulsos de forma duradoura.' },
  { tag: 'Dependência', stat: '88%', unit: '', title: 'Continuam fumando após 1 ano', body: 'Entre usuários que tentam parar sem método. Ter suporte estruturado multiplica as chances de sucesso.' },
  { tag: 'Pulmão', stat: '↓40%', unit: '', title: 'Queda na capacidade respiratória', body: 'Uso intenso reduz significativamente o volume expiratório. Atletas relatam piora em semanas de uso.' },
  { tag: 'Cardiovascular', stat: '2×', unit: 'risco', title: 'Dobra o risco de infarto jovem', body: 'Nicotina aumenta pressão, acelera frequência cardíaca e favorece formação de coágulos — em qualquer idade.' }];

  return (
    <section id="maleficios">
      <div className="container">
        <div className="section-head">
          <div>
            <div className="num">01 — O QUE VOCÊ ESTÁ INALANDO</div>
            <h2>não é <em>só</em> vapor de água.</h2>
          </div>
          <div className="right">A indústria vendeu o pod como alternativa "limpa". Os dados contam outra história — e ela ainda está sendo escrita.</div>
        </div>
        <div className="harm-grid">
          {items.map((it, i) =>
          <div key={i} className="harm">
              <div className="tag">{it.tag}</div>
              <div className="stat" style={{ marginTop: 14 }}>{it.stat}<span className="unit">{it.unit}</span></div>
              <div className="title">{it.title}</div>
              <div className="body">{it.body}</div>
            </div>
          )}
        </div>
        <div className="disclaimer">
          [!] Os números acima são de referências de domínio público e podem variar por estudo. Este projeto extensionista recomenda verificar com fontes oficiais (CDC, OMS, Inca, Anvisa) antes de citar em trabalhos acadêmicos.
        </div>
      </div>
    </section>);

}

/* ==================================================== */
/*  SIMULADOR DE PULMÃO — manchas clipadas nos pulmões  */
/* ==================================================== */
function LungSvg({ damage }) {
  const tissue = `oklch(${82 - damage * 22}% ${0.02 + damage * 0.09} ${20})`;

  // Spots positions: coordenadas LOCAIS dentro de cada pulmão
  // Pulmão esquerdo: cx 14–44, cy 22–82
  // Pulmão direito: cx 56–86, cy 22–82
  const leftSpots = useMemo(() => {
    const rand = (s) => {let x = Math.sin(s * 17.3 + 1) * 43758.5;return x - Math.floor(x);};
    return Array.from({ length: 9 }, (_, i) => ({
      cx: 17 + rand(i * 3 + 1) * 22,
      cy: 30 + rand(i * 5 + 2) * 44,
      r: 1.2 + rand(i * 7 + 3) * 3.5
    }));
  }, []);

  const rightSpots = useMemo(() => {
    const rand = (s) => {let x = Math.sin(s * 13.7 + 5) * 31415.9;return x - Math.floor(x);};
    return Array.from({ length: 9 }, (_, i) => ({
      cx: 59 + rand(i * 4 + 2) * 22,
      cy: 30 + rand(i * 6 + 3) * 44,
      r: 1.2 + rand(i * 8 + 4) * 3.5
    }));
  }, []);

  const spots = Math.round(damage * 9);
  const pct = Math.round(damage * 100);

  return (
    <svg className="lung-svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <radialGradient id="lungGrad" cx=".5" cy=".35" r=".75">
          <stop offset="0" stopColor={tissue} stopOpacity=".92" />
          <stop offset="0.7" stopColor={tissue} stopOpacity=".55" />
          <stop offset="1" stopColor={tissue} stopOpacity=".15" />
        </radialGradient>

        {/* Clip paths — contornos exatos dos pulmões */}
        <clipPath id="clipLeft">
          <path d="M 42 22 Q 20 24 14 42 Q 10 60 18 78 Q 26 86 38 82 Q 44 78 44 68 L 44 28 Q 44 22 42 22 Z" />
        </clipPath>
        <clipPath id="clipRight">
          <path d="M 58 22 Q 80 24 86 42 Q 90 60 82 78 Q 74 86 62 82 Q 56 78 56 68 L 56 28 Q 56 22 58 22 Z" />
        </clipPath>

        <filter id="spotBlur"><feGaussianBlur stdDeviation=".8" /></filter>
        <filter id="heatBlur"><feGaussianBlur stdDeviation="2.5" /></filter>
        <filter id="ambientBlur"><feGaussianBlur stdDeviation="1.5" /></filter>
      </defs>

      {/* ── ribcage ── */}
      <g opacity=".12" stroke="oklch(80% 0.12 180)" strokeWidth=".3" fill="none">
        {[0, 1, 2, 3, 4, 5].map((i) =>
        <path key={i} d={`M 8 ${22 + i * 10} Q 50 ${17 + i * 10} 92 ${22 + i * 10}`} />
        )}
      </g>
      <rect x="48.5" y="18" width="3" height="66" fill="oklch(80% 0.12 180)" opacity=".1" />
      <path d="M 15 22 Q 50 14 85 22" stroke="oklch(80% 0.12 180)" strokeWidth=".5" fill="none" opacity=".2" />

      {/* ── LEFT LUNG ── */}
      <path d="M 42 22 Q 20 24 14 42 Q 10 60 18 78 Q 26 86 38 82 Q 44 78 44 68 L 44 28 Q 44 22 42 22 Z"
      fill="url(#lungGrad)" stroke={tissue} strokeWidth=".4" />
      {/* left damage spots — clipped inside left lung */}
      <g clipPath="url(#clipLeft)">
        <g filter="url(#spotBlur)">
          {leftSpots.slice(0, spots).map((s, i) =>
          <circle key={i} cx={s.cx} cy={s.cy} r={s.r}
          fill={`oklch(${15 + damage * 8}% 0.03 25)`}
          opacity={0.35 + damage * 0.55} />
          )}
        </g>
        {/* heat overlay clipped */}
        {damage > 0.25 &&
        <ellipse cx="28" cy="64" rx="13" ry="9"
        fill="oklch(58% 0.19 25)"
        filter="url(#heatBlur)"
        opacity={damage * 0.38} />
        }
        {/* ambient damage tint */}
        {damage > 0.5 &&
        <rect x="0" y="0" width="100" height="100"
        fill={`oklch(${20}% 0.06 25)`}
        opacity={damage * 0.25} />
        }
      </g>

      {/* ── RIGHT LUNG ── */}
      <path d="M 58 22 Q 80 24 86 42 Q 90 60 82 78 Q 74 86 62 82 Q 56 78 56 68 L 56 28 Q 56 22 58 22 Z"
      fill="url(#lungGrad)" stroke={tissue} strokeWidth=".4" />
      {/* right damage spots — clipped inside right lung */}
      <g clipPath="url(#clipRight)">
        <g filter="url(#spotBlur)">
          {rightSpots.slice(0, spots).map((s, i) =>
          <circle key={i} cx={s.cx} cy={s.cy} r={s.r}
          fill={`oklch(${15 + damage * 8}% 0.03 25)`}
          opacity={0.35 + damage * 0.55} />
          )}
        </g>
        {damage > 0.25 &&
        <ellipse cx="72" cy="60" rx="11" ry="8"
        fill="oklch(58% 0.19 25)"
        filter="url(#heatBlur)"
        opacity={damage * 0.35} />
        }
        {damage > 0.5 &&
        <rect x="0" y="0" width="100" height="100"
        fill={`oklch(${20}% 0.06 25)`}
        opacity={damage * 0.22} />
        }
      </g>

      {/* ── trachea + bronchi ── */}
      <path d="M 50 16 L 50 30 M 50 30 L 40 40 M 50 30 L 60 40"
      stroke={tissue} strokeWidth=".9" fill="none" opacity=".75" />
      <g stroke={tissue} strokeWidth=".3" fill="none" opacity=".5">
        <path d="M 40 40 L 32 50 M 40 40 L 36 55 M 40 40 L 28 46" />
        <path d="M 60 40 L 68 50 M 60 40 L 64 55 M 60 40 L 72 46" />
      </g>
    </svg>);

}

function LungSimulator() {
  const [years, setYears] = useState(2);
  const [puffs, setPuffs] = useState(200);
  const [nicotine, setNicotine] = useState(35);
  const [startAge, setStartAge] = useState(17);

  const damage = useMemo(() => {
    const tFactor = Math.min(years / 8, 1);
    const pFactor = Math.min(puffs / 600, 1);
    const nFactor = Math.min(nicotine / 60, 1);
    const aFactor = Math.max(0, (22 - startAge) / 10);
    return Math.min(1, tFactor * 0.35 + pFactor * 0.35 + nFactor * 0.2 + aFactor * 0.1);
  }, [years, puffs, nicotine, startAge]);

  const verdict = useMemo(() => {
    if (damage < 0.2) return {
      level: 'Baixa exposição', color: 'var(--ink-dim)',
      title: 'Janela de reversão aberta',
      body: 'Parar agora permite que seus pulmões restaurem a função ciliar em semanas. Os cílios que varrem impurezas das vias aéreas se recuperam rapidamente após a cessação — o corpo é generoso quando você para a tempo.',
      detail: 'Capacidade respiratória ainda preservada. Risco de dependência já presente.'
    };
    if (damage < 0.45) return {
      level: 'Exposição moderada', color: 'var(--warn)',
      title: 'Inflamação silenciosa em curso',
      body: 'Irritação crônica das vias aéreas, redução discreta do fôlego em esforço físico. Tosse matinal frequente é sinal de alerta. Ainda reversível — mas cada semana adiciona carga inflamatória cumulativa.',
      detail: 'Muco excessivo, broncoespasmo leve e início de remodelamento tecidual possíveis.'
    };
    if (damage < 0.7) return {
      level: 'Exposição elevada', color: 'oklch(65% 0.16 45)',
      title: 'Dano estrutural começando',
      body: 'Inflamação persistente com possível formação de tecido cicatricial nos alvéolos. Capacidade vital reduzida de forma mensurável. Parar agora ainda faz diferença real — mas a reversão será parcial.',
      detail: 'Risco de bronquiolite obliterante, sibilância crônica e infecções respiratórias recorrentes.'
    };
    return {
      level: 'Exposição crítica', color: 'oklch(58% 0.19 25)',
      title: 'Risco real de lesão permanente',
      body: 'Quadro compatível com EVALI e bronquiolite obliterante em casos documentados. Tecido pulmonar pode não se recuperar completamente. Parar hoje não reverte tudo — mas impede o próximo estágio.',
      detail: 'Consulta pneumológica urgente recomendada. Cada puff adiciona dano irreversível.'
    };
  }, [damage]);

  const pct = Math.round(damage * 100);
  const capacity = Math.round(100 - damage * 42);

  return (
    <section id="pulmao">
      <div className="container">
        <div className="section-head">
          <div>
            <div className="num">02 — RAIO-X INTERATIVO</div>
            <h2>veja seu <em>pulmão</em> agora.</h2>
          </div>
          <div className="right">Ajuste os parâmetros e visualize o impacto estimado. Heurística educativa — não substitui avaliação médica.</div>
        </div>

        <div className="sim">
          {/* XRAY PANEL */}
          <div className="xray-frame">
            <div className="xray-corner tl" /><div className="xray-corner tr" />
            <div className="xray-corner bl" /><div className="xray-corner br" />
            <div className="xray-hud">
              <div className="row"><span>PT-BR · LIBERTA</span><span>{new Date().toISOString().slice(0, 10)}</span></div>
              <div className="row" style={{ alignItems: 'flex-end' }}>
                <span>SCAN · CHEST-AP</span>
                <span style={{ color: damage > 0.5 ? 'oklch(70% 0.18 25)' : undefined }}>
                  DMG {pct.toString().padStart(3, '0')}%
                </span>
              </div>
            </div>
            <LungSvg damage={damage} />
          </div>

          {/* CONTROLS + VERDICT */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
            <div className="controls">
              <div className="ctrl">
                <label>Tempo de uso <span className="val">{years} {years === 1 ? 'ano' : 'anos'}</span></label>
                <input type="range" min="0" max="10" step="0.5" value={years} onChange={(e) => setYears(+e.target.value)} />
              </div>
              <div className="ctrl">
                <label>Puffs por dia <span className="val">{puffs}</span></label>
                <input type="range" min="0" max="800" step="10" value={puffs} onChange={(e) => setPuffs(+e.target.value)} />
              </div>
              <div className="ctrl">
                <label>Nicotina <span className="val">{nicotine} mg/ml</span></label>
                <input type="range" min="0" max="60" step="1" value={nicotine} onChange={(e) => setNicotine(+e.target.value)} />
              </div>
              <div className="ctrl">
                <label>Idade em que começou <span className="val">{startAge} anos</span></label>
                <input type="range" min="12" max="30" step="1" value={startAge} onChange={(e) => setStartAge(+e.target.value)} />
              </div>
            </div>

            {/* METRICS STRIP */}
            <div style={{
              display: 'grid', gridTemplateColumns: '1fr 1fr',
              gap: '1px', background: 'var(--line)',
              border: '1px solid var(--line)', margin: '24px 0 0'
            }}>
              {[
              { k: 'Dano estimado', v: pct + '%', accent: damage > 0.5 },
              { k: 'Cap. respiratória', v: capacity + '%', accent: false },
              { k: 'Carga de nicotina/dia', v: Math.round(puffs * nicotine / 1000 * 10) / 10 + 'mg', accent: false },
              { k: 'Anos de exposição', v: years + (years === 1 ? ' ano' : ' anos'), accent: false }].
              map((m, i) =>
              <div key={i} style={{
                background: 'var(--paper-2)', padding: '14px 16px'
              }}>
                  <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, color: 'var(--ink-faint)', letterSpacing: '.2em', textTransform: 'uppercase', marginBottom: 6 }}>
                    {m.k}
                  </div>
                  <div style={{
                  fontFamily: "'Instrument Serif',serif", fontSize: 28, lineHeight: 1,
                  color: m.accent ? verdict.color : 'var(--ink)', letterSpacing: '-.02em'
                }}>{m.v}</div>
                </div>
              )}
            </div>

            {/* VERDICT */}
            <div className="verdict">
              <div className="level" style={{ color: verdict.color }}>
                {verdict.level} · {pct}%
              </div>
              <h4>{verdict.title}</h4>
              <p>{verdict.body}</p>
              <p style={{ marginTop: 12, fontFamily: "'JetBrains Mono',monospace", fontSize: 11, color: 'var(--ink-faint)', letterSpacing: '.1em', lineHeight: 1.6 }}>
                {verdict.detail}
              </p>
            </div>
          </div>
        </div>
      </div>
    </section>);

}

/* ==================================================== */
/*  CALCULADORA DE ECONOMIA — layout compacto           */
/* ==================================================== */
function Economy() {
  const [price, setPrice] = useState(60);
  const [daysPerPod, setDaysPerPod] = useState(3);
  const [frame, setFrame] = useState('year');

  const perDay = price / daysPerPod;
  const totals = {
    week: perDay * 7,
    month: perDay * 30,
    year: perDay * 365,
    fiveYears: perDay * 365 * 5
  };
  const amount = totals[frame];
  const fmt = (n) => Math.round(n).toLocaleString('pt-BR');

  const frames = [
  { k: 'week', label: '7 dias' },
  { k: 'month', label: '30 dias' },
  { k: 'year', label: '1 ano' },
  { k: 'fiveYears', label: '5 anos' }];


  const comparisons = [
  { n: Math.floor(amount / 45), label: 'pizzas grandes' },
  { n: Math.floor(amount / 2500), label: 'passagens aéreas' },
  { n: Math.floor(amount / 800), label: 'cursos online' },
  { n: Math.floor(amount / 15), label: 'cafés especiais' },
  { n: Math.floor(amount / 3500), label: 'iPhones usados' },
  { n: Math.floor(amount / 350), label: 'shows / ingressos' }];


  return (
    <section id="economia">
      <div className="container">
        <div className="section-head">
          <div>
            <div className="num">03 — DINHEIRO QUEIMADO</div>
            <h2>calcule o que você <em>inalou</em> em reais.</h2>
          </div>
          <div className="right">Não é só saúde. É um carro popular a cada poucos anos — transformado em fumaça.</div>
        </div>

        <div className="econ">
          {/* LEFT — inputs + gasto diário lado a lado */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
            <div className="ctrl">
              <label>Preço por pod <span className="val">R$ {price.toFixed(0)}</span></label>
              <input type="range" min="15" max="150" step="5" value={price} onChange={(e) => setPrice(+e.target.value)} />
            </div>
            <div className="ctrl">
              <label>Duração do pod <span className="val">{daysPerPod} {daysPerPod === 1 ? 'dia' : 'dias'}</span></label>
              <input type="range" min="1" max="14" step="1" value={daysPerPod} onChange={(e) => setDaysPerPod(+e.target.value)} />
            </div>
            {/* gasto diário — logo abaixo dos sliders, sem gap */}
            <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', padding: '20px 22px', marginTop: 4 }}>
              <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, color: 'var(--ink-faint)', letterSpacing: '.25em', textTransform: 'uppercase', marginBottom: 10 }}>
                Gasto diário
              </div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
                <span style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 14, color: 'var(--ink-dim)' }}>R$</span>
                <span style={{ fontFamily: "'Instrument Serif',serif", fontSize: 52, lineHeight: 1, letterSpacing: '-.03em' }}>
                  {perDay.toFixed(2).replace('.', ',')}
                </span>
              </div>
              <div style={{ color: 'var(--ink-dim)', fontSize: 12, marginTop: 6, fontFamily: "'JetBrains Mono',monospace", letterSpacing: '.1em' }}>
                por dia, todos os dias
              </div>
            </div>

            {/* timeframe toggle */}
            <div>
              <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, color: 'var(--ink-faint)', letterSpacing: '.25em', textTransform: 'uppercase', marginBottom: 10 }}>
                Visualizar acumulado em:
              </div>
              <div className="timeframe">
                {frames.map((f) =>
                <button key={f.k} className={frame === f.k ? 'active' : ''} onClick={() => setFrame(f.k)}>{f.label}</button>
                )}
              </div>
            </div>
          </div>

          {/* RIGHT — total + comparisons */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
            <div>
              <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, color: 'var(--ink-faint)', letterSpacing: '.25em', textTransform: 'uppercase', marginBottom: 12 }}>
                Total em {frames.find((f) => f.k === frame).label}
              </div>
              <div className="money">
                <span className="rs">R$</span>{fmt(amount)}
              </div>
              <div style={{ marginTop: 8, fontFamily: "'JetBrains Mono',monospace", fontSize: 11, color: 'var(--ink-dim)', letterSpacing: '.1em' }}>
                {frame === 'year' && 'esse valor dobra a cada ano que passa'}
                {frame === 'fiveYears' && 'dá pra reformar um apartamento inteiro'}
                {frame === 'month' && 'por mês, que sai do seu bolso em fumaça'}
                {frame === 'week' && 'só nessa semana'}
              </div>
            </div>

            <div style={{ borderTop: '1px solid var(--line)', paddingTop: 20 }}>
              <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, color: 'var(--ink-faint)', letterSpacing: '.25em', textTransform: 'uppercase', marginBottom: 14 }}>
                Ou, traduzindo:
              </div>
              <div className="comparisons">
                {comparisons.map((c, i) =>
                <div className="cmp" key={i}>
                    <div className="n"><em>{c.n.toLocaleString('pt-BR')}</em></div>
                    <div className="l">{c.label}</div>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>);

}

/* ==================================================== */
/*  FAQ                                                 */
/* ==================================================== */
function FAQ() {
  const items = [
  { q: 'Como funciona o desafio de 30 dias?', a: 'Você preenche o formulário de entrada, faz seu onboarding para entendermos sua situação e recebe apoio de forma pessoal e pesonalizada pela equipe e conteúdos diários curtos (leitura de 2–3 min). Sem app, sem pagamento.' },
  { q: 'Preciso parar no dia 1?', a: 'Não. A primeira semana é de preparação — identificar gatilhos, reduzir gradualmente, montar rede de apoio. A abstinência começa formalmente no dia 8, com plano completo em mãos.' },
  { q: 'E se eu recair?', a: 'Recaída faz parte do processo — a ciência do comportamento é clara sobre isso. O programa tem protocolos de recomeço imediato sem culpa. O objetivo não é perfeição; é parar.' },
  { q: 'Meus dados são privados?', a: 'Sim. Os dados do formulário são usados exclusivamente para acompanhamento do projeto extensionista. Nada é compartilhado com terceiros.' },
  { q: 'Quem está por trás do Liberta?', a: 'Projeto de extensão universitária da unifor. Composto por alunos da Ciência da Computação com orientação acadêmica.' }];

  return (
    <section id="faq">
      <div className="container">
        <div className="section-head">
          <div>
            <div className="num">04 — DÚVIDAS COMUNS</div>
            <h2>o que <em>perguntam</em> antes de entrar.</h2>
          </div>
        </div>
        <div className="faq">
          {items.map((it, i) =>
          <details className="faq-item" key={i}>
              <summary>
                <span>{it.q}</span>
                <span className="plus">+</span>
              </summary>
              <div className="ans">{it.a}</div>
            </details>
          )}
        </div>
      </div>
    </section>);

}

/* ==================================================== */
/*  FINAL CTA                                           */
/* ==================================================== */
function Finale() {
  return (
    <section id="entrar" className="finale">
      <div className="container">
        <span className="eyebrow"><span className="pulse" />Inscrições abertas</span>
        <h2>É sua vez de <em>respirar</em>.<br />30 dias.</h2>
        <p>Preencha o formulário abaixo e entre no desafio. É gratuito, sem julgamento e começa quando você quiser.</p>
        <a href="https://docs.google.com/forms/d/e/1FAIpQLSfSJ81rwuzrUYojGygbZf2g2JBF4OHuO2AtdSCa_AUReFWDUg/viewform?usp=header"
        target="_blank" rel="noopener noreferrer"
        className="btn btn-primary">
          Quero entrar no desafio <span className="arrow">→</span>
        </a>
        <div style={{ margin: '28px auto 0', width: 'fit-content', display: 'flex', alignItems: 'center', gap: 10, fontFamily: "'JetBrains Mono',monospace", fontSize: 12, color: 'var(--ink-dim)', letterSpacing: '.18em', textTransform: 'uppercase', border: '1px solid var(--line)', padding: '10px 18px', justifyContent: "center" }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--warn)', display: 'inline-block', flexShrink: 0 }} />≈ 2 minutos para preencher
        </div>
      </div>
    </section>);

}

/* ==================================================== */
/*  FOOTER                                              */
/* ==================================================== */
function Footer() {
  return (
    <footer>
      <div className="container">
        <div className="row">
          <div>© 2026 · Projeto Liberta · Extensão Unifor</div>
          <a href="https://github.com/d3vluz/NaoPodFumar" target="_blank" rel="noopener noreferrer"
          style={{ display: 'flex', alignItems: 'center', gap: 8, color: 'var(--ink-faint)', textDecoration: 'none', transition: 'color .2s' }}
          onMouseEnter={(e) => e.currentTarget.style.color = 'var(--ink)'}
          onMouseLeave={(e) => e.currentTarget.style.color = 'var(--ink-faint)'}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
              <path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0 0 24 12c0-6.63-5.37-12-12-12z" />
            </svg>
            github.com/d3vluz/NaoPodFumar
          </a>
        </div>
      </div>
    </footer>);

}

/* ==================================================== */
/*  BACK TO TOP BUTTON                                  */
/* ==================================================== */
function BackToTop() {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      if (window.scrollY > window.innerHeight) {
        setVisible(true);
      } else {
        setVisible(false);
      }
    };
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  return (
    <div 
      className={`back-to-top ${visible ? 'visible' : ''}`}
      onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
      title="Voltar ao topo"
    >
      <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M12 19V5M5 12l7-7 7 7"/>
      </svg>
    </div>
  );
}

/* ==================================================== */
/*  APP                                                 */
/* ==================================================== */
function App() {
  const [tweaks, setTweaks] = useState({ ...window.__TWEAKS__ });
  const [editMode, setEditMode] = useState(false);

  useEffect(() => {
    window.__TWEAK_DEFAULTS_SNAPSHOT__ = { ...window.__TWEAKS__ };
    const onMsg = (e) => {
      const d = e.data || {};
      if (d.type === '__activate_edit_mode') setEditMode(true);
      if (d.type === '__deactivate_edit_mode') setEditMode(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  return (
    <>
      <Nav />
      <Hero tweaks={tweaks} />
      <Harms />
      <LungSimulator />
      <Economy />
      <FAQ />
      <Finale />
      <Footer />
      <BackToTop />
      <TweaksPanel tweaks={tweaks} setTweaks={setTweaks} visible={editMode} />
    </>);

}

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