// Landing page — editorial, warm, Instrument Serif hero

function Landing({ navigate }) {
  return (
    <div style={{ background:'var(--bg)', color:'var(--ink)' }}>
      <LandingNav navigate={navigate} />
      <LandingHero navigate={navigate} />
      <LandingLogos />
      <LandingHow navigate={navigate} />
      <LandingInteractivePreview />
      <LandingROI />
      <LandingPresets navigate={navigate} />
      <LandingPricing navigate={navigate} />
      <LandingFAQ />
      <LandingFooter />
    </div>
  );
}

function LandingNav({ navigate }) {
  const [menuOpen, setMenuOpen] = useState(false);

  return (
    <nav className="m-nav" style={{
      display:'flex', alignItems:'center', justifyContent:'space-between',
      padding: '22px 48px',
      paddingTop: 'calc(14px + var(--safe-top))',
      position:'sticky', top: 0, zIndex: 20,
      background: 'rgba(245,241,235,.82)', backdropFilter:'blur(12px)', WebkitBackdropFilter:'blur(12px)',
      borderBottom: '1px solid transparent',
    }}>
      <button onClick={() => navigate('#/landing')} style={{ display:'flex', alignItems:'center', gap: 10 }}>
        <AftershotMark />
        <span className="serif" style={{ fontSize: 26, lineHeight: 1 }}>Aftershot</span>
      </button>

      {/* Desktop nav */}
      <div className="hide-mobile" style={{ display:'flex', alignItems:'center', gap: 28, fontSize: 14, color:'var(--ink-2)' }}>
        <a href="#how">Como funciona</a>
        <a href="#presets">Predefinições</a>
        <a href="#pricing">Preços</a>
        <a href="#faq">Perguntas</a>
      </div>

      <div className="hide-mobile" style={{ display:'flex', alignItems:'center', gap: 10 }}>
        {window.USER ? (
          <div style={{ display:'flex', alignItems:'center', gap: 12 }}>
            <span style={{ fontSize: 14, color: DB.creditsAvailable() === 0 ? 'var(--accent)' : 'var(--ink-2)', fontWeight: 500 }}>
              {window.USER.name.split(' ')[0]} · {DB.creditsAvailable()} créditos
            </span>
            {DB.creditsAvailable() === 0 && (
              <Button variant="accent" size="sm" onClick={() => navigate('#/checkout')}>
                <Icons.Zap size={13}/> Comprar créditos
              </Button>
            )}
            <Button variant="primary" size="sm" onClick={() => navigate('#/dashboard')}>Editor</Button>
            <Button variant="secondary" size="sm" onClick={() => navigate('#/account')}>Minha conta</Button>
            <Button variant="ghost" size="sm" onClick={() => DB.logout()}>Sair</Button>
          </div>
        ) : (
          <>
            <Button variant="ghost" size="sm" onClick={() => navigate('#/login')}>Entrar</Button>
            <Button variant="primary" size="sm" onClick={() => navigate('#/signup')}>Assinar<Icons.Arrow size={14}/></Button>
          </>
        )}
      </div>

      {/* Mobile — botão primário + hamburger */}
      <div className="show-mobile" style={{ display:'none', alignItems:'center', gap: 8 }}>
        {window.USER ? (
          <Button variant="primary" size="sm" onClick={() => navigate('#/dashboard')}>Editor</Button>
        ) : (
          <Button variant="primary" size="sm" onClick={() => navigate('#/signup')}>Assinar</Button>
        )}
        <button onClick={() => setMenuOpen(true)} className="tap-fade"
          style={{ width: 40, height: 40, borderRadius: 10, background:'var(--paper)', border:'1px solid var(--line)', display:'flex', alignItems:'center', justifyContent:'center' }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M4 7h16M4 12h16M4 17h16"/></svg>
        </button>
      </div>

      {menuOpen && <MobileMenu onClose={() => setMenuOpen(false)} navigate={navigate}/>}
    </nav>
  );
}

function MobileMenu({ onClose, navigate }) {
  const go = (hash) => { onClose(); setTimeout(() => navigate(hash), 40); };
  const scrollTo = (id) => {
    onClose();
    setTimeout(() => {
      const el = document.getElementById(id);
      if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }, 60);
  };
  return (
    <div onClick={onClose} style={{
      position:'fixed', inset: 0, zIndex: 99,
      background:'rgba(31,26,21,.35)', backdropFilter:'blur(3px)',
    }}>
      <div onClick={e => e.stopPropagation()} className="sheet-in" style={{
        position:'absolute', right: 0, top: 0, bottom: 0,
        width: 'min(320px, 82vw)',
        background:'var(--bg-warm)',
        borderLeft:'1px solid var(--line)',
        padding: 'calc(20px + var(--safe-top)) 18px 24px',
        display:'flex', flexDirection:'column', gap: 8,
        animation:'none',
      }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 16 }}>
          <div style={{ display:'flex', alignItems:'center', gap: 8 }}>
            <AftershotMark size={26}/>
            <span className="serif" style={{ fontSize: 22 }}>Aftershot</span>
          </div>
          <button onClick={onClose} className="tap-fade"
            style={{ width: 36, height: 36, borderRadius: 10, background:'var(--paper)', border:'1px solid var(--line)', display:'flex', alignItems:'center', justifyContent:'center' }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6l-12 12"/></svg>
          </button>
        </div>

        {[
          ['Como funciona', 'how'],
          ['Predefinições', 'presets'],
          ['Preços', 'pricing'],
          ['Perguntas', 'faq'],
        ].map(([label, id]) => (
          <button key={id} onClick={() => scrollTo(id)} className="tap-fade" style={{
            padding:'14px 14px', borderRadius: 12, textAlign:'left',
            background:'var(--paper)', border:'1px solid var(--line)',
            fontSize: 15, fontWeight: 500, color:'var(--ink)',
          }}>{label}</button>
        ))}

        <div style={{ flex: 1 }}/>

        {window.USER ? (
          <>
            <Button variant="primary" size="lg" onClick={() => go('#/dashboard')} style={{ width:'100%' }}>Abrir editor</Button>
            <Button variant="secondary" size="lg" onClick={() => go('#/account')} style={{ width:'100%' }}>Minha conta</Button>
            <Button variant="ghost" size="lg" onClick={() => { DB.logout(); onClose(); }} style={{ width:'100%' }}>Sair</Button>
          </>
        ) : (
          <>
            <Button variant="primary" size="lg" onClick={() => go('#/signup')} style={{ width:'100%' }}>Criar conta</Button>
            <Button variant="secondary" size="lg" onClick={() => go('#/login')} style={{ width:'100%' }}>Entrar</Button>
          </>
        )}
      </div>
    </div>
  );
}

function LandingHero({ navigate }) {
  return (
    <section className="m-hero" style={{ padding: '72px 48px 40px', maxWidth: 1280, margin: '0 auto' }}>
      <div className="m-stack" style={{ display:'grid', gridTemplateColumns: '1.05fr 1fr', gap: 56, alignItems:'center' }}>
        <div>
          <Pill tone="accent">Para anfitriões · Powered by Google</Pill>
          <h1 className="serif m-h1" style={{ fontSize: 84, lineHeight: 0.98, margin: '20px 0 22px', letterSpacing:'-0.02em' }}>
            Fotos de estadia,<br/>
            <em style={{ color:'var(--accent)' }}>prontas para encantar</em>
          </h1>
          <p style={{ fontSize: 18, color:'var(--ink-2)', lineHeight: 1.55, maxWidth: 520, textWrap:'pretty' }}>
            Suba a foto do seu imóvel, escolha uma predefinição e receba a versão profissional em segundos.
            Sem Lightroom, sem briefing, sem esperar fotógrafo voltar.
          </p>
          <div className="m-stack" style={{ display:'flex', gap: 10, marginTop: 28 }}>
            <Button variant="primary" size="lg" onClick={() => navigate('#/dashboard')} className="m-btn-full">
              Editar uma foto agora <Icons.Arrow size={16}/>
            </Button>
            <Button variant="secondary" size="lg" onClick={() => navigate('#/presets')} className="m-btn-full">
              Ver predefinições
            </Button>
          </div>
          <div style={{ display:'flex', gap: 24, marginTop: 28, fontSize: 13, color:'var(--ink-3)' }}>
            <span style={{ display:'flex', alignItems:'center', gap: 6 }}><Icons.Check size={14}/> Cancelamento a qualquer hora</span>
          </div>
        </div>

        <HeroShowcase />
      </div>
    </section>
  );
}

function HeroShowcase() {
  const [pos, setPos] = useState(55);
  const [preset, setPreset] = useState(0);
  const scenes = [
    { label:'Manhã de sol', before: STOCK.livingRoomDim, after: STOCK.livingRoomBright },
    { label:'Entardecer', before: STOCK.exterior, after: STOCK.exteriorSunny },
    { label:'Noite aconchegante', before: STOCK.diningDark, after: STOCK.diningNight },
  ];
  const s = scenes[preset];
  return (
    <div style={{ position:'relative' }}>
      <div style={{
        borderRadius: 20, overflow:'hidden', background:'var(--paper)', border:'1px solid var(--line)',
        boxShadow:'var(--shadow-lg)', aspectRatio: '4/5', position:'relative',
      }}>
        <BeforeAfter before={s.before} after={s.after} pos={pos} setPos={setPos} />
        <div style={{ position:'absolute', top: 14, left: 14, right: 14, display:'flex', justifyContent:'space-between' }}>
          <Pill tone="ink">Antes</Pill>
          <Pill tone="accent">Depois · {s.label}</Pill>
        </div>
      </div>

      {/* preset chips */}
      <div style={{
        display:'flex', gap: 8, marginTop: 18, flexWrap:'wrap', justifyContent:'center',
      }}>
        {scenes.map((sc, i) => (
          <button key={i} onClick={() => setPreset(i)}
            style={{
              padding:'8px 14px', borderRadius: 999,
              background: preset===i ? 'var(--ink)' : 'var(--paper)',
              color: preset===i ? 'var(--bg-warm)' : 'var(--ink-2)',
              border: '1px solid ' + (preset===i ? 'var(--ink)' : 'var(--line-2)'),
              fontSize: 13, fontWeight: 500,
            }}>{sc.label}</button>
        ))}
      </div>

      {/* floating label */}
      <div className="hide-mobile" style={{
        position:'absolute', right: -20, bottom: 80, padding: '10px 14px',
        background:'var(--paper)', border:'1px solid var(--line)', borderRadius: 10,
        boxShadow:'var(--shadow-md)', fontSize: 12, display:'flex', alignItems:'center', gap: 8,
        transform:'rotate(3deg)',
      }}>
        <Icons.Zap size={14} style={{ color:'var(--accent)' }}/>
        <span><b>10 segundos</b> · foto pronta</span>
      </div>
    </div>
  );
}

function BeforeAfter({ before, after, pos, setPos, zoom = 1 }) {
  const ref = useRef(null);

  const updateFromEvent = (clientX) => {
    const r = ref.current?.getBoundingClientRect();
    if (!r) return;
    const x = clientX - r.left;
    setPos(Math.max(2, Math.min(98, (x / r.width) * 100)));
  };

  const onPointerDown = (e) => {
    e.preventDefault();
    try { e.currentTarget.setPointerCapture(e.pointerId); } catch {}
    updateFromEvent(e.clientX);
  };
  const onPointerMove = (e) => {
    if (e.buttons === 0 && e.pointerType === 'mouse') return;
    if (!e.currentTarget.hasPointerCapture?.(e.pointerId)) return;
    updateFromEvent(e.clientX);
  };
  const onPointerUp = (e) => {
    try { e.currentTarget.releasePointerCapture(e.pointerId); } catch {}
  };

  return (
    <div ref={ref}
         onPointerDown={onPointerDown}
         onPointerMove={onPointerMove}
         // ... rest of interaction
         style={{ position:'absolute', inset:0, cursor:'ew-resize', userSelect:'none', touchAction:'none', overflow:'hidden', borderRadius:'inherit' }}>
      <img src={after} alt="" style={{ position:'absolute', inset:0, width:'100%', height:'100%', objectFit:'cover', transform:`scale(${zoom})` }}/>
      <div style={{ position:'absolute', inset:0, clipPath:`inset(0 ${100-pos}% 0 0)` }}>
        <img src={before} alt="" style={{ width:'100%', height:'100%', objectFit:'cover', transform:`scale(${zoom})` }}/>
      </div>
      <div style={{
        position:'absolute', top:0, bottom:0, left: `${pos}%`, width: 2, background:'white',
        boxShadow:'0 0 0 1px rgba(0,0,0,.2)', transform:'translateX(-1px)', pointerEvents:'none',
      }}>
        <div style={{
          position:'absolute', top:'50%', left:'50%', transform:'translate(-50%,-50%)',
          width: 40, height: 40, borderRadius: 999, background:'white',
          boxShadow:'0 4px 14px rgba(0,0,0,.25)',
          display:'flex', alignItems:'center', justifyContent:'center', color:'var(--ink)',
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round">
            <path d="M8 6l-4 6 4 6"/><path d="M16 6l4 6-4 6"/>
          </svg>
        </div>
      </div>
    </div>
  );
}

function LandingLogos() {
  const items = ['Airbnb', 'Booking', 'VRBO', 'Hospedin', 'Stays', 'Quinto Andar'];
  return (
    <section className="m-section" style={{ padding: '40px 48px 20px', maxWidth: 1280, margin: '0 auto' }}>
      <div style={{ fontSize: 12, color:'var(--ink-3)', letterSpacing:'.12em', textTransform:'uppercase', textAlign:'center', marginBottom: 20 }}>
        Para anúncios em
      </div>
      <div style={{ display:'flex', justifyContent:'center', alignItems:'center', flexWrap:'wrap', gap: 22, opacity: .55 }}>
        {items.map(n => (
          <span key={n} className="serif" style={{ fontSize: 20, color:'var(--ink-2)', letterSpacing:'.01em' }}>{n}</span>
        ))}
      </div>
    </section>
  );
}

function LandingHow({ navigate }) {
  const [sel, setSel] = useState(0);
  const chips = PRESETS.map(p => ({
    n: p.name,
    c: p.accent,
    out: p.demo.after
  }));

  const steps = [
    { n:'01', t:'Suba sua foto', d:'Arraste uma imagem do seu quarto, sala, cozinha ou fachada. JPEG, PNG ou HEIC.', img: 'foto-original.webp' },
    { n:'02', t:'Escolha a predefinição', d:'Dez predefinições testadas para cada ambiente. Ajuste a intensidade se quiser.', img: null },
    { n:'03', t:'Baixe em alta', d:'Versão otimizada para plataformas em segundos. Reverta quando quiser.', img: chips[sel].out },
  ];
  return (
    <section id="how" className="m-section" style={{ padding: '100px 48px', maxWidth: 1280, margin: '0 auto' }}>
      <div className="m-stack" style={{ display:'flex', justifyContent:'space-between', alignItems:'end', marginBottom: 44, gap: 24 }}>
        <h2 className="serif m-h2" style={{ fontSize: 56, lineHeight: 1, margin: 0, maxWidth: 640, letterSpacing:'-0.015em' }}>
          Do celular à reserva,<br/>em <em style={{ color:'var(--accent)'}}>três passos</em>.
        </h2>
        <p style={{ fontSize: 15, color:'var(--ink-3)', maxWidth: 340, textWrap:'pretty' }}>
          Sem cursos de fotografia. Sem editor complexo. Sua próxima foto sai melhor que a do fotógrafo do vizinho.
        </p>
      </div>

      <div className="m-stack" style={{ display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap: 14 }}>
        {steps.map((s, i) => (
          <div key={i} style={{
            background:'var(--paper)', border:'1px solid var(--line)', borderRadius: 18,
            padding: 24, display:'flex', flexDirection:'column', gap: 14, minHeight: 380,
          }}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
              <span className="mono" style={{ fontSize: 12, color:'var(--accent)', letterSpacing:'.08em' }}>{s.n}</span>
              <span style={{ fontSize: 12, color:'var(--ink-4)' }}>{['Upload','Predefinição','Download'][i]}</span>
            </div>
            <div className="serif" style={{ fontSize: 28, lineHeight: 1.1, letterSpacing:'-0.01em' }}>{s.t}</div>
            <p style={{ margin: 0, color:'var(--ink-3)', fontSize: 14, lineHeight: 1.5 }}>{s.d}</p>
            <div style={{ flex: 1 }} />

            {i === 0 && <UploadStepVisual img={s.img} />}
            {i === 1 && <PresetStepVisual sel={sel} setSel={setSel} chips={chips} />}
            {i === 2 && <DownloadStepVisual img={s.img} />}
          </div>
        ))}
      </div>

      <div style={{ display:'flex', justifyContent:'center', marginTop: 32 }}>
        <Button variant="accent" size="lg" onClick={() => navigate('#/signup')} className="m-btn-full">
          Assinar e começar <Icons.Arrow size={16}/>
        </Button>
      </div>
    </section>
  );
}

function LandingInteractivePreview() {
  const [pos, setPos] = useState(50);
  const [preset, setPreset] = useState(0);
  
  const presets = PRESETS.map(p => ({
    label: p.name,
    file: p.demo.after
  }));
  
  return (
    <section className="m-section" style={{ padding: '0 48px 100px', maxWidth: 1280, margin: '0 auto' }}>
      <div style={{ textAlign:'center', marginBottom: 28 }}>
        <h2 className="serif m-h2" style={{ fontSize: 44, lineHeight: 1, letterSpacing:'-0.01em' }}>
          Interaja e veja a mágica
        </h2>
        <p style={{ color:'var(--ink-3)', fontSize: 15, marginTop: 10 }}>Arraste o slider para comparar a foto original e nossos processamentos.</p>
      </div>

      <div className="m-card-pad" style={{
        background:'var(--paper)', border:'1px solid var(--line)', borderRadius: 20,
        padding: 24, boxShadow:'var(--shadow-sm)'
      }}>
        <div style={{ display:'flex', gap: 10, justifyContent:'center', marginBottom: 24, flexWrap:'wrap' }}>
          {presets.map((p, i) => (
            <button key={i} onClick={() => setPreset(i)} style={{
              padding:'10px 18px', borderRadius: 999, fontSize: 13, fontWeight: 600,
              background: preset===i ? 'var(--ink)' : 'transparent',
              color: preset===i ? 'var(--bg-warm)' : 'var(--ink-2)',
              border: '1px solid ' + (preset===i ? 'var(--ink)' : 'var(--line-2)'),
              transition:'all .15s ease'
            }}>{p.label}</button>
          ))}
        </div>

        <div style={{
          borderRadius: 14, overflow:'hidden', position:'relative', aspectRatio:'16/9',
          border:'1px solid var(--line)', background:'black'
        }}>
          <BeforeAfter before="foto-original.webp" after={presets[preset].file} pos={pos} setPos={setPos} zoom={1.04} />
          <div style={{ position:'absolute', top: 18, left: 18, pointerEvents:'none' }}>
            <Pill tone="ink">Original sem edição</Pill>
          </div>
          <div style={{ position:'absolute', top: 18, right: 18, pointerEvents:'none' }}>
            <Pill tone="accent">Opção {presets[preset].label}</Pill>
          </div>
        </div>
      </div>
    </section>
  );
}

function LandingROI() {
  return (
    <section id="roi" className="m-section" style={{ padding: '40px 48px 100px', maxWidth: 1280, margin: '0 auto' }}>
      <div className="m-stack m-card-pad" style={{
        background: 'var(--ink)', borderRadius: 24, padding: '72px 64px',
        color: 'var(--bg)', display: 'flex', alignItems: 'center', gap: 40,
        boxShadow: 'var(--shadow-lg)'
      }}>
        <div style={{ flex: 1.1 }}>
          <div style={{
            display:'inline-flex', alignItems:'center', gap: 6, padding:'6px 12px',
            borderRadius: 999, background:'rgba(255,255,255,0.1)', color:'var(--accent)',
            fontSize: 13, fontWeight: 600, letterSpacing:'.05em', textTransform:'uppercase',
            marginBottom: 24
          }}>
            <Icons.Zap size={14}/>
            Retorno garantido
          </div>
          <h2 className="serif m-h2" style={{ fontSize: 52, lineHeight: 1.05, margin: '0 0 24px', letterSpacing: '-0.015em' }}>
            Fotos atrativas geram <span style={{ color: 'var(--accent)' }}>reservas automáticas.</span>
          </h2>
          <p style={{ fontSize: 16, color: 'rgba(255,255,255,0.8)', lineHeight: 1.5, margin: 0 }}>
            No Airbnb ou Booking, seu único vendedor é a foto de capa. Imóveis com fotos visualmente deslumbrantes e bem iluminadas recebem <strong>até 43% mais cliques</strong> e fecham muito mais diárias.
          </p>
          <div style={{ height: 1, background: 'rgba(255,255,255,0.1)', margin: '40px 0' }} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
             <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--accent)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', flexShrink: 0 }}>
               <Icons.Heart size={26}/>
             </div>
             <div>
               <div style={{ fontSize: 18, fontWeight: 600 }}>O investimento se paga na próxima locação.</div>
               <div style={{ fontSize: 15, color: 'rgba(255,255,255,0.7)', marginTop: 4, lineHeight: 1.4 }}>Uma única diária extra gerada pelas novas fotos cobre imediatamente todo o custo do seu pacote Aftershot. E as fotos são suas para sempre.</div>
             </div>
          </div>
        </div>
        <div style={{ flex: 0.9, width: '100%', borderRadius: 20, overflow: 'hidden', position: 'relative', aspectRatio: '4/4', boxShadow: '0 24px 48px rgba(0,0,0,0.4)', background: 'var(--ink)' }}>
            <img src={STOCK.exteriorSunny} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
            <div style={{ position: 'absolute', bottom: 24, left: 24, right: 24, background: 'rgba(31,26,21,0.6)', backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)', padding: 20, borderRadius: 16, display: 'flex', alignItems: 'center', justifyContent: 'space-between', border: '1px solid rgba(255,255,255,0.1)' }}>
               <div>
                 <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.7)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Aumento de cliques</div>
                 <div style={{ fontSize: 28, fontWeight: 700, color: '#fff', marginTop: 2 }}>+43%</div>
               </div>
               <div style={{ padding: '10px 16px', background: 'var(--accent)', color: 'white', borderRadius: 10, fontSize: 14, fontWeight: 600, display:'flex', alignItems:'center', gap: 6 }}>
                 <Icons.Eye size={16}/> Alta conversão
               </div>
            </div>
        </div>
      </div>
    </section>
  );
}

function UploadStepVisual({ img }) {
  return (
    <div style={{
      border: '1.5px dashed var(--line-2)', borderRadius: 12, padding: 18,
      display:'flex', alignItems:'center', gap: 12, background:'var(--bg-warm)',
    }}>
      <div style={{ width: 56, height: 56, borderRadius: 8, overflow:'hidden', flexShrink: 0,
                    backgroundImage:`url(${img})`, backgroundSize:'cover', backgroundPosition:'center' }}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 500 }}>area_piscina_01.jpg</div>
        <div className="mono" style={{ fontSize: 11, color:'var(--ink-3)', marginTop: 2 }}>3.2 MB · 4032×3024</div>
        <div style={{ height: 3, background:'var(--line)', borderRadius: 2, marginTop: 8, overflow:'hidden' }}>
          <div style={{ width: '100%', height:'100%', background:'var(--accent)' }}/>
        </div>
      </div>
      <Icons.Check size={18} style={{ color:'var(--olive)' }} />
    </div>
  );
}

function PresetStepVisual({ sel, setSel, chips }) {
  return (
    <div style={{ display:'flex', flexDirection:'column', gap: 8 }}>
      {chips.map((c, i) => (
        <button key={i} onClick={() => setSel(i)}
          style={{
            display:'flex', alignItems:'center', gap: 10,
            padding: '10px 12px', borderRadius: 10,
            border: '1px solid ' + (sel===i ? 'var(--ink)' : 'var(--line)'),
            background: sel===i ? 'var(--bg-deep)' : 'var(--bg-warm)',
            textAlign:'left',
          }}>
          <span style={{ width: 12, height: 12, borderRadius: 3, background: c.c }}/>
          <span style={{ flex: 1, fontSize: 13, fontWeight: sel===i ? 600 : 500 }}>{c.n}</span>
          {sel===i && <Icons.Check size={14} style={{ color:'var(--accent)'}}/>}
        </button>
      ))}
    </div>
  );
}

function DownloadStepVisual({ img }) {
  return (
    <div style={{ display:'flex', flexDirection:'column', gap: 10 }}>
      <div style={{ aspectRatio:'16/10', borderRadius: 10, overflow:'hidden', position:'relative' }}>
          <div style={{ position:'absolute', inset:0, backgroundImage:`url(${img})`, backgroundSize:'cover', backgroundPosition:'center', transform:'scale(1.04)' }}/>
      </div>
      <div style={{ display:'flex', gap: 6 }}>
        <button style={{ flex: 1, padding:'10px', borderRadius: 10, background:'var(--ink)', color:'var(--bg-warm)', fontSize: 13, fontWeight: 500, display:'flex', alignItems:'center', justifyContent:'center', gap: 6 }}>
          <Icons.Download size={14}/> Baixar JPG
        </button>
        <button style={{ padding:'10px 12px', borderRadius: 10, background:'var(--paper)', border:'1px solid var(--line-2)', fontSize: 13 }}>
          <Icons.Photo size={14}/>
        </button>
      </div>
    </div>
  );
}

function LandingPresets({ navigate }) {
  const featured = PRESETS.slice(0, 4);
  return (
    <section id="presets" className="m-section" style={{ padding: '100px 48px', maxWidth: 1280, margin: '0 auto' }}>
      <div className="m-stack" style={{ display:'flex', justifyContent:'space-between', alignItems:'end', marginBottom: 28, gap: 24 }}>
        <h2 className="serif m-h2" style={{ fontSize: 56, lineHeight: 1, margin: 0, letterSpacing:'-0.015em' }}>
          Dez predefinições.<br/><em style={{ color:'var(--accent)'}}>Zero curva de aprendizado.</em>
        </h2>
        <Button variant="secondary" onClick={() => navigate('#/presets')} className="m-btn-full">
          Ver todas <Icons.Arrow size={14}/>
        </Button>
      </div>
      <div className="m-grid-2" style={{ display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap: 14 }}>
        {featured.map(p => (
          <div key={p.id} style={{
            background:'var(--paper)', border:'1px solid var(--line)', borderRadius: 16,
            overflow:'hidden', display:'flex', flexDirection:'column',
          }}>
            <div style={{ position:'relative', aspectRatio:'4/5' }}>
              <img src={p.demo.after} alt="" style={{ position:'absolute', inset:0, width:'100%', height:'100%', objectFit:'cover', transform:'scale(1.04)' }}/>
              <div style={{ position:'absolute', top: 10, left: 10 }}>
                <Pill tone="ink">{p.tag || 'Predefinição'}</Pill>
              </div>
              <div style={{
                position:'absolute', bottom: 10, left: 10, padding:'4px 8px',
                background:'rgba(255,255,255,.92)', borderRadius: 6, fontSize: 11,
                fontFamily:'var(--mono)', color:'var(--ink)',
              }}>AFTER</div>
            </div>
            <div style={{ padding: 16 }}>
              <div className="serif" style={{ fontSize: 22, lineHeight: 1.1 }}>{p.name}</div>
              <div style={{ fontSize: 13, color:'var(--ink-3)', marginTop: 6, lineHeight: 1.45, textWrap:'pretty' }}>{p.desc}</div>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

function LandingPricing({ navigate }) {
  return (
    <section id="pricing" className="m-section" style={{ padding: '100px 48px', maxWidth: 1280, margin: '0 auto' }}>
      <div style={{ textAlign:'center', marginBottom: 36 }}>
        <Pill tone="accent">Planos e preços</Pill>
        <h2 className="serif m-h2" style={{ fontSize: 56, lineHeight: 1, margin: '16px 0 10px', letterSpacing:'-0.015em' }}>
          Um crédito, <em style={{ color:'var(--accent)'}}>uma foto pronta.</em>
        </h2>
        <p style={{ color:'var(--ink-3)', fontSize: 15, maxWidth: 560, margin:'0 auto' }}>
          Compre créditos, use quando quiser. Cada crédito = uma foto editada profissionalmente. Pagamento único, sem mensalidade.
        </p>
      </div>
      <div className="m-stack" style={{ display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap: 14, maxWidth: 820, margin:'0 auto' }}>
        {PLANS.map(p => (
          <button key={p.id} onClick={() => navigate(window.USER ? `#/checkout?plan=${p.id}` : '#/signup')}
            className="tap-fade" style={{
              background: p.featured ? 'var(--ink)' : 'var(--paper)',
              color: p.featured ? 'var(--bg-warm)' : 'var(--ink)',
              border: '1.5px solid ' + (p.featured ? 'var(--ink)' : 'var(--line)'),
              borderRadius: 16, padding: '24px 22px', textAlign:'left',
              display:'flex', flexDirection:'column', gap: 10, position:'relative',
              boxShadow: p.featured ? 'var(--shadow-lg)' : 'var(--shadow-sm)',
              transform: p.featured ? 'scale(1.04)' : 'none',
              transition: 'transform .15s, box-shadow .15s',
              cursor:'pointer',
          }}>
            {p.featured && (
              <div style={{
                position:'absolute', top: -10, right: 16,
                padding:'4px 10px', borderRadius: 999,
                background:'var(--accent)', color:'white',
                fontSize: 10, fontWeight: 700, letterSpacing:'.06em', textTransform:'uppercase',
              }}>Mais escolhido</div>
            )}
            <span className="serif" style={{ fontSize: 20, lineHeight: 1 }}>{p.name}</span>
            <div style={{ display:'flex', alignItems:'baseline', gap: 4 }}>
              <span style={{ fontSize: 12, opacity: .6 }}>R$</span>
              <span className="serif" style={{ fontSize: 42, lineHeight: 1, letterSpacing:'-0.02em' }}>{p.price}</span>
            </div>
            <span style={{ fontSize: 13, opacity: .65 }}>{p.credits} créditos · {p.credits} fotos</span>
            <div style={{
              marginTop: 6, padding:'10px 0', borderRadius: 10, textAlign:'center',
              background: p.featured ? 'var(--accent)' : 'var(--bg-deep)',
              color: p.featured ? 'white' : 'var(--ink)',
              fontSize: 13, fontWeight: 600,
            }}>
              Comprar {p.credits} créditos
            </div>
          </button>
        ))}
      </div>
      <div style={{ display:'flex', justifyContent:'center', gap: 20, marginTop: 24, fontSize: 12, color:'var(--ink-3)' }}>
        <span style={{ display:'flex', alignItems:'center', gap: 5 }}><Icons.Check size={13}/> Pagamento único</span>
        <span style={{ display:'flex', alignItems:'center', gap: 5 }}><Icons.Check size={13}/> Sem mensalidade</span>
        <span style={{ display:'flex', alignItems:'center', gap: 5 }}><Icons.Check size={13}/> Todas as predefinições</span>
      </div>
    </section>
  );
}

function LandingFooter() {
  return (
    <footer className="m-section" style={{
      borderTop:'1px solid var(--line)', padding:'40px 48px', marginTop: 40,
      background:'var(--bg-warm)',
      paddingBottom: 'calc(40px + var(--safe-bottom))',
    }}>
      <div style={{ maxWidth: 1280, margin:'0 auto', display:'flex', justifyContent:'space-between', alignItems:'center', flexWrap:'wrap', gap: 20 }}>
        <div style={{ display:'flex', alignItems:'center', gap: 10 }}>
          <AftershotMark size={24}/>
          <span className="serif" style={{ fontSize: 20 }}>Aftershot</span>
          <span style={{ fontSize: 13, color:'var(--ink-3)', marginLeft: 10 }}>© 2026 · Feito em São Paulo</span>
        </div>
        <div style={{ display:'flex', gap: 22, fontSize: 13, color:'var(--ink-3)' }}>
          <a href="#">Termos</a><a href="#">Privacidade</a><a href="#">Contato</a><a href="#">Blog</a>
        </div>
      </div>
    </footer>
  );
}

function LandingFAQ() {
  const [open, setOpen] = useState(null);
  const [contactName, setContactName] = useState('');
  const [contactEmail, setContactEmail] = useState('');
  const [contactMsg, setContactMsg] = useState('');
  const [contactSent, setContactSent] = useState(false);

  const faqs = [
    {
      q: 'Como funcionam os créditos?',
      a: 'Cada crédito permite editar uma foto com qualquer predefinição disponível. Compre um pacote, use quando quiser. Um crédito = uma foto editada profissionalmente.'
    },
    {
      q: 'Quanto tempo leva para editar uma foto?',
      a: 'Entre 10 e 30 segundos, dependendo da complexidade da imagem. A edição é processada por IA em tempo real — você não precisa esperar horas como num serviço tradicional.'
    },
    {
      q: 'Posso usar qualquer foto?',
      a: 'Sim! Funciona com fotos de celular ou câmera profissional. Aceitamos JPG, PNG e HEIC. A IA corrige automaticamente problemas de iluminação, distorção, ruído e até remove bagunça da cena.'
    },
    {
      q: 'As fotos editadas são minhas?',
      a: 'Sim, 100%. Todas as fotos editadas são de sua propriedade. Use à vontade no Airbnb, Booking, seu site, redes sociais ou qualquer outro lugar.'
    },
    {
      q: 'A edição altera objetos ou adiciona móveis?',
      a: 'Não. Nossas predefinições são focadas em iluminação, atmosfera e correção óptica. Nenhum objeto é adicionado ou removido da cena (a menos que você ative a opção de limpeza, que remove bagunça e pessoas).'
    },
    {
      q: 'Posso pedir um ajuste depois de editar?',
      a: 'Sim! O primeiro ajuste de cada edição é gratuito. Basta descrever o que deseja mudar (ex: "céu mais vibrante" ou "mais luz na cozinha") e a IA aplica a correção sobre a mesma foto.'
    },
    {
      q: 'Funciona para fotos de fachada e áreas externas?',
      a: 'Perfeitamente. Temos predefinições específicas para exteriores como "Entardecer" e "Neblina da montanha", além do modo de longa exposição noturna que corrige até a geometria da foto.'
    },
    {
      q: 'Posso pedir reembolso?',
      a: 'Por se tratar de produto digital de acesso imediato, conforme o artigo 49 §2º do Código de Defesa do Consumidor, não é possível exercer o direito de arrependimento após o acesso ao conteúdo. Ao adquirir créditos, você concorda com os Termos de Uso da plataforma. Se tiver qualquer problema técnico, entre em contato e resolveremos.'
    },
    {
      q: 'As fotos são armazenadas por quanto tempo?',
      a: 'Suas fotos editadas ficam disponíveis na galeria por 30 dias. Recomendamos baixar as versões finais logo após a edição. Após 30 dias, elas são removidas automaticamente por segurança.'
    },
  ];

  const toggle = (i) => setOpen(open === i ? null : i);

  const handleContactSubmit = (e) => {
    e.preventDefault();
    if (!contactName.trim() || !contactEmail.trim() || !contactMsg.trim()) return;
    // Compose a mailto link with the message
    const subject = encodeURIComponent(`Dúvida Aftershot — ${contactName}`);
    const body = encodeURIComponent(`Nome: ${contactName}\nEmail: ${contactEmail}\n\n${contactMsg}`);
    window.open(`mailto:contato@aftershot.com.br?subject=${subject}&body=${body}`, '_blank');
    setContactSent(true);
  };

  return (
    <section id="faq" className="m-section" style={{ padding: '100px 48px', maxWidth: 1280, margin: '0 auto' }}>
      <div className="m-stack" style={{ display: 'grid', gridTemplateColumns: '1fr 1.2fr', gap: 40, alignItems: 'flex-start' }}>
        {/* Left: heading */}
        <div className="m-faq-heading" style={{ position: 'sticky', top: 100 }}>
          <Pill tone="accent">Perguntas frequentes</Pill>
          <h2 className="serif m-h2" style={{ fontSize: 52, lineHeight: 1.05, margin: '16px 0 14px', letterSpacing: '-0.015em' }}>
            Tire suas <em style={{ color: 'var(--accent)' }}>dúvidas.</em>
          </h2>
          <p style={{ color: 'var(--ink-3)', fontSize: 16, lineHeight: 1.55, maxWidth: 400 }}>
            Não encontrou o que precisa? Mande uma mensagem no formulário abaixo — respondemos em até 24 horas.
          </p>
        </div>

        {/* Right: accordion */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
          {faqs.map((faq, i) => {
            const isOpen = open === i;
            return (
              <div key={i} style={{
                borderBottom: '1px solid var(--line)',
                ...(i === 0 ? { borderTop: '1px solid var(--line)' } : {}),
              }}>
                <button
                  onClick={() => toggle(i)}
                  style={{
                    width: '100%', textAlign: 'left', padding: '20px 0',
                    display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
                    fontSize: 16, fontWeight: 500, color: 'var(--ink)',
                    cursor: 'pointer',
                  }}>
                  <span>{faq.q}</span>
                  <span style={{
                    width: 28, height: 28, borderRadius: 8,
                    background: isOpen ? 'var(--accent-soft)' : 'var(--bg-deep)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    flexShrink: 0,
                    transition: 'transform .2s, background .2s',
                    transform: isOpen ? 'rotate(45deg)' : 'none',
                    color: isOpen ? 'var(--accent)' : 'var(--ink-3)',
                  }}>
                    <Icons.Plus size={16} />
                  </span>
                </button>
                {isOpen && (
                  <div style={{
                    paddingBottom: 20, paddingRight: 44,
                    fontSize: 15, color: 'var(--ink-2)', lineHeight: 1.6,
                    animation: 'faqFadeIn .2s ease',
                  }}>
                    {faq.a}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>

      {/* Contact box */}
      <div className="m-stack m-card-pad" style={{
        marginTop: 56, background: 'var(--paper)', border: '1px solid var(--line)',
        borderRadius: 24, padding: '48px 56px',
        display: 'grid', gridTemplateColumns: '1fr 1.1fr', gap: 32, alignItems: 'center',
        boxShadow: 'var(--shadow-sm)',
      }}>
        <div>
          <h3 className="serif" style={{ fontSize: 36, lineHeight: 1.1, margin: '0 0 12px', letterSpacing: '-0.01em' }}>
            Ainda tem dúvidas?
          </h3>
          <p style={{ color: 'var(--ink-3)', fontSize: 15, lineHeight: 1.55, margin: 0 }}>
            Mande sua pergunta e nossa equipe responde em até 24 horas úteis. Se preferir, escreva diretamente para{' '}
            <a href="mailto:contato@aftershot.com.br" style={{ color: 'var(--accent)', textDecoration: 'underline', textUnderlineOffset: 2 }}>
              contato@aftershot.com.br
            </a>
          </p>
        </div>

        {contactSent ? (
          <div style={{
            padding: '28px 24px', background: '#EAF2E4', border: '1px solid var(--olive)',
            borderRadius: 16, textAlign: 'center', color: 'var(--olive)',
          }}>
            <Icons.Check size={28} style={{ marginBottom: 8 }} />
            <div style={{ fontSize: 18, fontWeight: 600, marginBottom: 4 }}>Mensagem enviada!</div>
            <div style={{ fontSize: 14, opacity: .8 }}>Responderemos em breve no e-mail informado.</div>
          </div>
        ) : (
          <form onSubmit={handleContactSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <div className="m-stack" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <input
                value={contactName} onChange={e => setContactName(e.target.value)}
                placeholder="Seu nome" required
                style={faqInput}
              />
              <input
                type="email" value={contactEmail} onChange={e => setContactEmail(e.target.value)}
                placeholder="Seu e-mail" required
                style={faqInput}
              />
            </div>
            <textarea
              value={contactMsg} onChange={e => setContactMsg(e.target.value)}
              placeholder="Escreva sua dúvida ou mensagem..."
              required rows={4}
              style={{ ...faqInput, resize: 'vertical', minHeight: 100 }}
            />
            <Button variant="primary" size="lg" type="submit" style={{ alignSelf: 'flex-start' }}>
              Enviar mensagem <Icons.Arrow size={16} />
            </Button>
          </form>
        )}
      </div>

      <style>{`@keyframes faqFadeIn { from { opacity: 0; transform: translateY(-6px); } to { opacity: 1; transform: none; } }`}</style>
    </section>
  );
}

const faqInput = {
  width: '100%', padding: '13px 16px', borderRadius: 12,
  border: '1px solid var(--line-2)', background: 'var(--bg-warm)',
  fontSize: 14, color: 'var(--ink)', outline: 'none',
  fontFamily: 'var(--sans)',
};


Object.assign(window, { Landing, BeforeAfter });
