// ====== PROMO POP-UP — Cupom AGENDA90 ======
// Configure SHEETS_ENDPOINT abaixo com a URL do seu Google Apps Script Web App
// para receber os leads numa planilha. Se vazio, o form continua funcionando
// (envia direto para WhatsApp) mas não grava na planilha.
//
// Como criar o endpoint:
// 1. Vá em sheets.google.com → crie nova planilha
// 2. Em Extensões → Apps Script, cole o código abaixo (substitua o ID da planilha):
//
//    function doPost(e) {
//      const sheet = SpreadsheetApp.openById('SEU_ID_DA_PLANILHA').getActiveSheet();
//      const data = JSON.parse(e.postData.contents);
//      sheet.appendRow([new Date(), data.nome, data.telefone, data.area, data.coupon, data.origin]);
//      return ContentService.createTextOutput(JSON.stringify({ok:true})).setMimeType(ContentService.MimeType.JSON);
//    }
//
// 3. Implantar → Nova implantação → Web app → Acesso: Qualquer pessoa
// 4. Copie a URL e cole abaixo
// 5. Na primeira linha da planilha, ponha cabeçalhos: Data | Nome | Telefone | Área | Cupom | Origem

const SHEETS_ENDPOINT = 'https://script.google.com/macros/s/AKfycbxuCVA_1WzM7jz-7nDOLZJIvbTW6PGVmq7BTbZaWfp7V7W8r4iJVkfro4jWdJQFbyRzMg/exec';

const PROMO_DELAY_MS = 120000; // 2 min
const PROMO_TIMER_S = 15 * 60; // 15 min countdown
const COUPON = 'AGENDA90';

const AREAS = [
'Buço',
'Axilas',
'Virilha',
'Pernas inteiras',
'Meia perna',
'Barba (masculino)',
'Costas (masculino)',
'Tórax (masculino)',
'Combo Mulher (axila + virilha + meia perna)',
'Combo Homem (barba + axila + nuca)',
'Outra área / não sei ainda'];


function PromoPopup() {
  const [open, setOpen] = React.useState(false);
  const [stage, setStage] = React.useState('offer'); // offer | success
  const [secondsLeft, setSecondsLeft] = React.useState(PROMO_TIMER_S);
  const [form, setForm] = React.useState({ nome: '', telefone: '', area: '' });
  const [errors, setErrors] = React.useState({});

  // Mostra após delay, se elegível
  React.useEffect(() => {
    try {
      if (localStorage.getItem('nubelle_promo_declined')) return;
      if (localStorage.getItem('nubelle_promo_claimed')) return;
    } catch (e) {}
    const id = setTimeout(() => setOpen(true), PROMO_DELAY_MS);
    return () => clearTimeout(id);
  }, []);

  // Trava scroll do body
  React.useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {document.body.style.overflow = prev;};
  }, [open]);

  // Cronômetro
  React.useEffect(() => {
    if (!open || stage !== 'offer') return;
    const id = setInterval(() => {
      setSecondsLeft((s) => {
        if (s <= 1) {
          clearInterval(id);
          setOpen(false); // expira sem marcar
          return 0;
        }
        return s - 1;
      });
    }, 1000);
    return () => clearInterval(id);
  }, [open, stage]);

  // ESC fecha (sem marcar)
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => {if (e.key === 'Escape') setOpen(false);};
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  function fmtTime(s) {
    const m = Math.floor(s / 60);
    const ss = s % 60;
    return `${String(m).padStart(2, '0')}:${String(ss).padStart(2, '0')}`;
  }

  function fmtPhone(v) {
    const d = v.replace(/\D/g, '').slice(0, 11);
    if (d.length <= 2) return d;
    if (d.length <= 6) return `(${d.slice(0, 2)}) ${d.slice(2)}`;
    if (d.length <= 10) return `(${d.slice(0, 2)}) ${d.slice(2, 6)}-${d.slice(6)}`;
    return `(${d.slice(0, 2)}) ${d.slice(2, 7)}-${d.slice(7)}`;
  }

  function handleDecline() {
    try {localStorage.setItem('nubelle_promo_declined', String(Date.now()));} catch (e) {}
    setOpen(false);
  }

  function handleClose() {
    // X — fecha sem marcar nada; pode reaparecer em outra visita após 120s
    setOpen(false);
  }

  function validate() {
    const e = {};
    if (form.nome.trim().split(/\s+/).length < 2) e.nome = 'Informe nome e sobrenome';
    const dig = form.telefone.replace(/\D/g, '');
    if (dig.length < 10) e.telefone = 'Telefone incompleto';
    if (!form.area) e.area = 'Selecione uma área';
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  function handleSubmit(ev) {
    ev.preventDefault();
    if (!validate()) return;
    const payload = {
      ...form,
      coupon: COUPON,
      at: new Date().toISOString(),
      origin: 'site-popup'
    };
    try {
      localStorage.setItem('nubelle_promo_claimed', JSON.stringify(payload));
    } catch (e) {}
    // Envia para Google Sheets em background (não bloqueia UX)
    if (SHEETS_ENDPOINT) {
      try {
        fetch(SHEETS_ENDPOINT, {
          method: 'POST',
          mode: 'no-cors',
          headers: { 'Content-Type': 'text/plain;charset=utf-8' },
          body: JSON.stringify(payload)
        }).catch(() => {});
      } catch (e) {}
    }
    setStage('success');
  }

  function whatsappLink() {
    const msg =
    `Olá! Acabei de ativar minha oferta no site da Nubelle 💚\n\n` +
    `*Cupom:* ${COUPON} (até R$ 90 OFF, limite 10% do valor)\n` +
    `*Bônus:* sessão experimental na axila ou buço (mediante disponibilidade)\n\n` +
    `*Nome:* ${form.nome}\n` +
    `*Telefone:* ${form.telefone}\n` +
    `*Área de interesse:* ${form.area}\n\n` +
    `Quero agendar imediatamente. Qual a melhor data disponível?`;
    return `https://wa.me/5571992628880?text=${encodeURIComponent(msg)}`;
  }

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center p-4" style={{ animation: 'promoFade 0.4s ease-out both' }}>
      <style>{`
        @keyframes promoFade { from { opacity: 0; } to { opacity: 1; } }
        @keyframes promoPop { from { opacity: 0; transform: translateY(20px) scale(0.95); } to { opacity: 1; transform: translateY(0) scale(1); } }
        @keyframes promoPulse { 0%,100% { box-shadow: 0 0 0 0 rgba(255,139,122,0.5); } 50% { box-shadow: 0 0 0 14px rgba(255,139,122,0); } }
        @keyframes promoShine { 0% { background-position: -200% 0; } 100% { background-position: 200% 0; } }
        .promo-shine {
          background: linear-gradient(90deg, #FF8B7A 0%, #FFC8B8 25%, #FF8B7A 50%, #FFC8B8 75%, #FF8B7A 100%);
          background-size: 200% 100%;
          animation: promoShine 6s linear infinite;
          -webkit-background-clip: text; background-clip: text; color: transparent;
        }
        .promo-coupon {
          font-family: 'Aventa', system-ui, sans-serif;
          letter-spacing: 0.06em;
        }
      `}</style>

      {/* Backdrop */}
      <div className="absolute inset-0 backdrop-blur-md" style={{ background: 'rgba(5,7,8,0.85)' }} onClick={handleClose}></div>

      {/* Card */}
      <div className="relative w-full max-w-[520px] rounded-[28px] overflow-hidden grain"
      style={{
        background: 'linear-gradient(160deg, #0E3B3A 0%, #0a2a29 100%)',
        border: '1px solid rgba(255,139,122,0.35)',
        boxShadow: '0 40px 80px -20px rgba(0,0,0,0.7), 0 0 80px rgba(255,139,122,0.15)',
        color: '#F4EDE3',
        animation: 'promoPop 0.6s cubic-bezier(.2,.7,.2,1) both'
      }}>

        {/* glow halo */}
        <div className="absolute -top-32 -right-32 w-[300px] h-[300px] rounded-full pointer-events-none" style={{
          background: 'radial-gradient(circle, rgba(255,139,122,0.35) 0%, transparent 60%)',
          filter: 'blur(40px)'
        }}></div>

        {/* Close X */}
        <button onClick={handleClose} aria-label="Fechar" className="absolute top-4 right-4 z-20 w-9 h-9 rounded-full flex items-center justify-center transition hover:scale-110" style={{
          background: 'rgba(244,237,227,0.08)',
          color: 'rgba(244,237,227,0.7)',
          border: '1px solid rgba(244,237,227,0.12)'
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="2"><path d="M2 2 L12 12 M12 2 L2 12" /></svg>
        </button>

        {stage === 'offer' &&
        <div className="relative px-7 sm:px-9 py-8 sm:py-10">
            {/* Header / pill */}
            <div className="inline-flex items-center gap-2 text-[10px] uppercase tracking-[0.3em] mb-5 px-3 py-1.5 rounded-full" style={{
            color: 'var(--neon)', border: '1px solid rgba(255,139,122,0.4)', background: 'rgba(255,139,122,0.08)'
          }}>
              <span className="w-1.5 h-1.5 rounded-full bg-[var(--neon)]" style={{ boxShadow: '0 0 10px var(--neon)', animation: 'promoPulse 2s infinite' }}></span>
              oferta especial · só hoje
            </div>

            {/* Headline */}
            <h2 className="font-display mb-3" style={{ fontSize: 'clamp(28px, 6vw, 38px)', lineHeight: 0.98, fontWeight: 700, letterSpacing: '-0.025em' }}>
              Um presente <br />
              <span className="promo-shine" style={{ fontStyle: 'italic', fontWeight: 900 }}>de boas-vindas.</span>
            </h2>

            <p className="text-sm mb-6" style={{ color: 'rgba(244,237,227,0.75)', lineHeight: 1.55 }}>
              Para quem agendar <em style={{ color: 'var(--neon)', fontStyle: 'italic', fontWeight: 600 }}>imediatamente</em>:
            </p>

            {/* Benefits list */}
            <div className="space-y-3 mb-6">
              <div className="flex items-start gap-3 p-3.5 rounded-2xl" style={{ background: 'rgba(255,139,122,0.06)', border: '1px solid rgba(255,139,122,0.15)' }}>
                <div className="shrink-0 w-9 h-9 rounded-full flex items-center justify-center font-display" style={{ background: 'var(--neon)', color: '#0E3B3A', fontWeight: 900, fontSize: 14 }}>−</div>
                <div className="flex-1">
                  <div className="font-display text-base mb-0.5" style={{ fontWeight: 700, letterSpacing: '-0.01em' }}>Até R$ 90 OFF</div>
                  <div className="text-xs" style={{ color: 'rgba(244,237,227,0.6)', lineHeight: 1.45 }}>em qualquer protocolo · uso máximo de 10% do valor total</div>
                </div>
              </div>
              <div className="flex items-start gap-3 p-3.5 rounded-2xl" style={{ background: 'rgba(255,139,122,0.06)', border: '1px solid rgba(255,139,122,0.15)' }}>
                <div className="shrink-0 w-9 h-9 rounded-full flex items-center justify-center font-display" style={{ background: 'var(--neon)', color: '#0E3B3A', fontWeight: 900, fontSize: 16 }}>★</div>
                <div className="flex-1">
                  <div className="font-display text-base mb-0.5" style={{ fontWeight: 700, letterSpacing: '-0.01em' }}>Sessão experimental grátis</div>
                  <div className="text-xs" style={{ color: 'rgba(244,237,227,0.6)', lineHeight: 1.45 }}>na axila ou buço · mediante disponibilidade</div>
                </div>
              </div>
            </div>

            {/* Coupon + Timer */}
            <div className="flex items-stretch gap-2.5 mb-6">
              <div className="flex-1 rounded-2xl flex flex-col items-center justify-center py-3 px-3" style={{
              background: '#050708',
              border: '1.5px dashed rgba(255,139,122,0.5)'
            }}>
                <div className="text-[9px] uppercase tracking-[0.3em] mb-1" style={{ color: 'rgba(244,237,227,0.5)' }}>seu cupom</div>
                <div className="promo-coupon" style={{ fontSize: 22, fontWeight: 900, color: 'var(--neon)', textShadow: '0 0 12px rgba(255,139,122,0.5)' }}>{COUPON}</div>
              </div>
              <div className="rounded-2xl flex flex-col items-center justify-center py-3 px-4" style={{
              background: '#050708',
              border: '1px solid rgba(244,237,227,0.1)'
            }}>
                <div className="text-[9px] uppercase tracking-[0.3em] mb-1" style={{ color: 'rgba(244,237,227,0.5)' }}>expira em</div>
                <div className="font-display tabular-nums" style={{ fontSize: 22, fontWeight: 700, color: '#F4EDE3' }}>{fmtTime(secondsLeft)}</div>
              </div>
            </div>

            {/* Form */}
            <form onSubmit={handleSubmit} className="space-y-3">
              <div>
                <input
                type="text"
                placeholder="Nome completo"
                value={form.nome}
                onChange={(e) => setForm({ ...form, nome: e.target.value })}
                className="w-full px-4 py-3 rounded-xl text-sm transition focus:outline-none"
                style={{
                  background: 'rgba(244,237,227,0.06)',
                  border: errors.nome ? '1px solid #ff6b6b' : '1px solid rgba(244,237,227,0.12)',
                  color: '#F4EDE3'
                }} />

                {errors.nome && <div className="text-[11px] mt-1 px-1" style={{ color: '#ff8585' }}>{errors.nome}</div>}
              </div>
              <div>
                <input
                type="tel"
                placeholder="(71) 99999-9999"
                value={form.telefone}
                onChange={(e) => setForm({ ...form, telefone: fmtPhone(e.target.value) })}
                className="w-full px-4 py-3 rounded-xl text-sm transition focus:outline-none tabular-nums"
                style={{
                  background: 'rgba(244,237,227,0.06)',
                  border: errors.telefone ? '1px solid #ff6b6b' : '1px solid rgba(244,237,227,0.12)',
                  color: '#F4EDE3'
                }} />

                {errors.telefone && <div className="text-[11px] mt-1 px-1" style={{ color: '#ff8585' }}>{errors.telefone}</div>}
              </div>
              <div>
                <select
                value={form.area}
                onChange={(e) => setForm({ ...form, area: e.target.value })}
                className="w-full px-4 py-3 rounded-xl text-sm transition focus:outline-none appearance-none"
                style={{
                  background: 'rgba(244,237,227,0.06)',
                  border: errors.area ? '1px solid #ff6b6b' : '1px solid rgba(244,237,227,0.12)',
                  color: form.area ? '#F4EDE3' : 'rgba(244,237,227,0.5)',
                  backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'><path d='M1 1l5 5 5-5' stroke='%23FF8B7A' stroke-width='1.5' fill='none' stroke-linecap='round' stroke-linejoin='round'/></svg>")`,
                  backgroundRepeat: 'no-repeat',
                  backgroundPosition: 'right 16px center',
                  paddingRight: 40
                }}>

                  <option value="" style={{ background: '#0E3B3A' }}>Área de interesse</option>
                  {AREAS.map((a) => <option key={a} value={a} style={{ background: '#0E3B3A' }}>{a}</option>)}
                </select>
                {errors.area && <div className="text-[11px] mt-1 px-1" style={{ color: '#ff8585' }}>{errors.area}</div>}
              </div>

              <button type="submit" className="w-full py-4 rounded-full font-display transition hover:scale-[1.02]" style={{
              background: 'var(--neon)',
              color: '#0E3B3A',
              fontWeight: 700,
              fontSize: 15,
              letterSpacing: '-0.01em',
              boxShadow: '0 12px 30px -8px rgba(255,139,122,0.5)'
            }}>
                Quero ativar minha oferta →
              </button>
            </form>

            {/* Decline */}
            <button onClick={handleDecline} className="block mx-auto mt-5 text-xs underline-offset-4 hover:underline transition" style={{ color: 'rgba(244,237,227,0.4)' }}>
              Não tenho interesse, obrigada
            </button>

            <div className="text-[10px] text-center mt-4" style={{ color: 'rgba(244,237,227,0.3)', lineHeight: 1.5 }}>
              Ao enviar você concorda em receber contato no WhatsApp informado.<br />
              Cupom não-cumulativo · válido para agendamento imediato.
            </div>
          </div>
        }

        {stage === 'success' &&
        <div className="relative px-7 sm:px-9 py-10 sm:py-12 text-center">
            {/* check icon */}
            <div className="mx-auto mb-6 w-20 h-20 rounded-full flex items-center justify-center" style={{
            background: 'rgba(255,139,122,0.12)',
            border: '1.5px solid rgba(255,139,122,0.5)',
            animation: 'promoPulse 2s infinite'
          }}>
              <svg width="36" height="36" viewBox="0 0 36 36" fill="none" stroke="var(--neon)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M8 18 L15 25 L28 11" />
              </svg>
            </div>

            <div className="text-[10px] uppercase tracking-[0.3em] mb-3" style={{ color: 'var(--neon)' }}>● tudo pronto</div>

            <h2 className="font-display mb-4" style={{ fontSize: 'clamp(26px, 5.5vw, 34px)', lineHeight: 1, fontWeight: 700, letterSpacing: '-0.025em' }}>
              Sua oferta está <br />
              <span className="promo-shine" style={{ fontStyle: 'italic', fontWeight: 900 }}>ativada, {form.nome.split(' ')[0]}.</span>
            </h2>

            <p className="text-sm mb-6 max-w-[380px] mx-auto" style={{ color: 'rgba(244,237,227,0.75)', lineHeight: 1.55 }}>
              Agora é só falar com nossos especialistas pelo WhatsApp e solicitar a melhor data para sua agenda.
            </p>

            {/* Coupon highlight */}
            <div className="rounded-2xl py-4 px-5 mb-6" style={{
            background: '#050708',
            border: '1.5px dashed rgba(255,139,122,0.5)'
          }}>
              <div className="text-[9px] uppercase tracking-[0.3em] mb-1" style={{ color: 'rgba(244,237,227,0.5)' }}>informe o cupom no atendimento</div>
              <div className="promo-coupon" style={{ fontSize: 28, fontWeight: 900, color: 'var(--neon)', textShadow: '0 0 14px rgba(255,139,122,0.5)' }}>{COUPON}</div>
            </div>

            <a href={whatsappLink()} target="_blank" rel="noopener" className="block w-full py-4 rounded-full font-display transition hover:scale-[1.02]" style={{
            background: 'var(--neon)',
            color: '#0E3B3A',
            fontWeight: 700,
            fontSize: 15,
            letterSpacing: '-0.01em',
            boxShadow: '0 12px 30px -8px rgba(255,139,122,0.5)'
          }}>
              <span className="inline-flex items-center gap-2">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M17.6 6.32A7.85 7.85 0 0 0 12.05 4a7.94 7.94 0 0 0-6.88 11.9L4 20l4.2-1.1a7.93 7.93 0 0 0 3.84.98h.01a7.94 7.94 0 0 0 5.55-13.56zm-5.55 12.21h-.01a6.6 6.6 0 0 1-3.36-.92l-.24-.14-2.5.65.67-2.43-.16-.25a6.6 6.6 0 1 1 12.24-3.5 6.6 6.6 0 0 1-6.64 6.59zm3.61-4.93c-.2-.1-1.17-.58-1.35-.64-.18-.07-.31-.1-.45.1s-.51.64-.62.78c-.12.13-.23.15-.42.05-.2-.1-.84-.31-1.6-.99-.59-.52-.99-1.17-1.1-1.37-.12-.2-.01-.3.09-.4.09-.09.2-.23.3-.35.1-.12.13-.2.2-.33.06-.13.03-.25-.02-.35-.05-.1-.45-1.08-.62-1.48-.16-.39-.33-.34-.45-.34l-.38-.01a.74.74 0 0 0-.53.25c-.18.2-.7.69-.7 1.67 0 .98.71 1.93.81 2.07.1.13 1.4 2.13 3.4 2.99.47.2.84.33 1.13.42.48.15.91.13 1.25.08.38-.06 1.17-.48 1.34-.94.16-.46.16-.86.12-.94-.05-.09-.18-.14-.38-.24z" /></svg>
                Solicitar minha data agora
              </span>
            </a>

            <button onClick={() => setOpen(false)} className="block mx-auto mt-5 text-xs underline-offset-4 hover:underline transition" style={{ color: 'rgba(244,237,227,0.4)' }}>
              Fechar e continuar navegando
            </button>
          </div>
        }
      </div>
    </div>);

}

Object.assign(window, { PromoPopup });
