// ========= PREMIUM PAGE — single $20 premium vs free =========
const { useState, useEffect } = React;

// ── Query param helpers (url, email, score, title, promo, funnel) ──
const getQueryParams = () => {
  const p = new URLSearchParams(window.location.search);
  return {
    url: p.get('url') || '',
    email: p.get('email') || '',
    score: parseInt(p.get('score'), 10) || 0,
    title: p.get('title') || '',
    promo: (p.get('promo') || '').toUpperCase(),
    funnel: p.get('funnel') || '',
    event_id: p.get('event_id') || '',
  };
};

// UUID compartido entre browser (fbq) y server (CAPI) para dedup en Meta.
const newCheckoutEventId = () => {
  try {
    if (window.crypto && typeof window.crypto.randomUUID === 'function') {
      return window.crypto.randomUUID().replace(/-/g, '');
    }
  } catch (_) {}
  return 'eid_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 10);
};

// UTM data helper — read from localStorage (v1 pattern via window.getUtmData)
const getUtmData = () => {
  try {
    if (typeof window.getUtmData === 'function') return window.getUtmData();
    const raw = localStorage.getItem('auditbnb_utm');
    return raw ? JSON.parse(raw) : {};
  } catch (_) { return {}; }
};

const URL_PATTERN = /^https?:\/\/(www\.)?airbnb\.(mx|com|com\.mx)\/(rooms|h)\/\d+/i;
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

const PricingHero = () => (
  <section className="pricing-hero">
    <div className="wrap">
      <div className="eyebrow" style={{justifyContent:'center'}}>Precios</div>
      <h1 className="display" style={{marginTop: 24, maxWidth: 900, marginLeft:'auto', marginRight:'auto'}}>
        Un solo pago. <em>Reporte completo.</em>
      </h1>
      <p className="lede" style={{marginTop: 24, fontSize: 20, marginLeft:'auto', marginRight:'auto'}}>
        Audita gratis y obtén tu calificación. Si quieres el plan de acción
        completo, paga $20 USD una sola vez por propiedad.
      </p>
    </div>
  </section>
);

// ── Premium CTA button: handles /api/create-checkout wiring ──
// Flow:
//   Si faltan URL o email → expande form inline con los inputs que necesita
//   (el user nunca es pateado fuera de la página para "primero audita").
//   Al completar + submit → POST /api/create-checkout → redirect a MP.
const PremiumCTA = ({ ctaStyle = 'accent', label = 'Obtener reporte premium', promoOverride = '' }) => {
  const [state, setState] = useState('idle'); // idle | form | loading | error
  const [errorMsg, setErrorMsg] = useState('');
  const [formUrl, setFormUrl] = useState('');
  const [formEmail, setFormEmail] = useState('');
  const [params, setParams] = useState(getQueryParams());

  useEffect(() => {
    const p = getQueryParams();
    setParams(p);
    if (p.url) setFormUrl(p.url);
    if (p.email) setFormEmail(p.email);
  }, []);

  // Effective promo: explicit override from PromoToggle wins over URL param.
  const effectivePromo = (promoOverride || params.promo || '').toUpperCase();

  const normalizeUrl = (raw) => {
    let u = (raw || '').trim();
    if (!u) return u;
    if (!/^https?:\/\//i.test(u)) u = 'https://' + u;
    try { const p = new URL(u); p.search = ''; p.hash = ''; return p.toString(); } catch (_) { return u; }
  };

  // Payment provider — read once on mount from /api/payment-config (server env).
  // The v2 React frontend is CDN-loaded (no build step), so we can't use
  // process.env.NEXT_PUBLIC_* — server endpoint surfaces the choice instead.
  const [provider, setProvider] = useState(null);
  useEffect(() => {
    fetch('/api/payment-config')
      .then(r => r.ok ? r.json() : null)
      .then(d => setProvider((d && d.provider) || 'mercadopago'))
      .catch(() => setProvider('mercadopago'));
  }, []);

  const checkout = async ({ url, email, title, score, promo }) => {
    setState('loading');
    setErrorMsg('');
    // Reusa event_id pasado desde la landing; si falta, genera uno nuevo.
    const eid = params.event_id || newCheckoutEventId();
    // Real charged value depends on promo. Stash for success.html Purchase fbq.
    const valueUSD = (promo || '').toUpperCase() === 'PROMO10' ? 10 : 20;
    // promo arrives already resolved (effectivePromo) from handlePrimary/handleFormSubmit.
    try { localStorage.setItem('abnb_last_value_usd', String(valueUSD)); } catch (_) {}
    if (typeof window.fbq === 'function') {
      try {
        window.fbq('track', 'InitiateCheckout', { value: valueUSD, currency: 'USD' }, { eventID: eid });
      } catch (_) {}
    }
    try {
      const payload = Object.assign({
        email, url, title: title || '', score: isNaN(score) ? 0 : score, promo: promo || '',
        event_id: eid,
      }, getUtmData());
      // Provider switch: stripe → /api/create-checkout-stripe; default MP.
      // Both endpoints return {init_point: <redirect_url>, event_id} so the
      // redirect line below stays identical.
      const endpoint = (provider === 'stripe')
        ? '/api/create-checkout-stripe'
        : '/api/create-checkout';
      const res = await fetch(endpoint, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.error || `Error ${res.status}`);
      }
      const data = await res.json();
      if (data.init_point) {
        window.location.href = data.init_point;
      } else {
        throw new Error('No se recibió el link de pago.');
      }
    } catch (err) {
      setErrorMsg(err.message || 'No pudimos iniciar el pago. Intenta de nuevo.');
      setState('error');
    }
  };

  const handlePrimary = () => {
    // Si ya tenemos URL + email (viene de la landing con params), salto directo a MP.
    if (URL_PATTERN.test(params.url) && EMAIL_PATTERN.test((params.email || '').trim().toLowerCase())) {
      checkout({
        url: params.url, email: params.email.trim().toLowerCase(),
        title: params.title, score: params.score, promo: effectivePromo,
      });
      return;
    }
    // Si falta algo, expandir form inline para capturarlo sin salir de la página.
    setState('form');
  };

  const handleFormSubmit = (e) => {
    e?.preventDefault?.();
    const nUrl = normalizeUrl(formUrl);
    const nEmail = (formEmail || '').trim().toLowerCase();
    if (!URL_PATTERN.test(nUrl)) {
      setErrorMsg('Ingresa una URL válida de Airbnb (airbnb.mx/rooms/...)');
      return;
    }
    if (!EMAIL_PATTERN.test(nEmail)) {
      setErrorMsg('Ingresa un email válido.');
      return;
    }
    setErrorMsg('');
    checkout({
      url: nUrl, email: nEmail,
      title: params.title, score: params.score, promo: params.promo,
    });
  };

  if (state === 'form' || state === 'loading' || (state === 'error' && formUrl && formEmail)) {
    const inputStyle = {
      width:'100%', padding:'12px 14px', fontSize:15,
      border:'1px solid var(--line-2, #d9d4c8)', borderRadius:10,
      background:'var(--card,#fff)', color:'var(--ink,#111)',
      fontFamily:'inherit', boxSizing:'border-box',
    };
    return (
      <form onSubmit={handleFormSubmit} style={{display:'flex', flexDirection:'column', gap: 10, marginTop: 8}}>
        <input
          type="text" placeholder="https://airbnb.mx/rooms/..."
          value={formUrl}
          autoFocus={!formUrl}
          onChange={(e) => { setFormUrl(e.target.value); if (errorMsg) setErrorMsg(''); }}
          disabled={state === 'loading'}
          style={inputStyle}
        />
        <input
          type="email" placeholder="tu@email.com"
          value={formEmail}
          autoFocus={!!formUrl && !formEmail}
          onChange={(e) => { setFormEmail(e.target.value); if (errorMsg) setErrorMsg(''); }}
          disabled={state === 'loading'}
          style={inputStyle}
        />
        <button type="submit" className={`btn btn-${ctaStyle} btn-lg plan-cta`} disabled={state === 'loading'}>
          {state === 'loading' ? 'Procesando…' : (effectivePromo === 'PROMO10' ? 'Continuar al pago · $10 USD' : 'Continuar al pago · $20 USD')}
        </button>
        {errorMsg && (
          <div role="alert" style={{fontSize: 13, color:'#B8392B'}}>{errorMsg}</div>
        )}
        <div className="muted" style={{fontSize: 12, textAlign:'center'}}>
          Pago seguro con MercadoPago · Sin suscripción
        </div>
        <div className="muted" style={{fontSize: 12, textAlign:'center', marginTop: 6}}>
          ¿No te ayudó? Escríbenos en 30 días y te devolvemos los $20.
        </div>
      </form>
    );
  }

  return (
    <>
      <button
        type="button"
        className={`btn btn-${ctaStyle} btn-lg plan-cta`}
        onClick={handlePrimary}
        disabled={state === 'loading'}
      >
        {state === 'loading' ? 'Procesando…' : label}
      </button>
      {errorMsg && (
        <div role="alert" style={{fontSize: 13, color:'#B8392B', marginTop: 10, textAlign:'center'}}>
          {errorMsg}
          {errorMsg.indexOf('audita') >= 0 && (
            <>
              {' '}<a href="/" style={{color:'var(--accent)', textDecoration:'underline'}}>Ir al auditor</a>
            </>
          )}
        </div>
      )}
      <div className="muted" style={{fontSize: 12, textAlign:'center', marginTop: 10}}>
        ¿No te ayudó? Escríbenos en 30 días y te devolvemos los $20.
      </div>
    </>
  );
};

const PromoToggle = ({ promo, onApply }) => {
  const [open, setOpen] = useState(false);
  const [code, setCode] = useState('');
  const [msg, setMsg] = useState('');
  const applied = promo === 'PROMO10';

  const submit = (e) => {
    e?.preventDefault?.();
    const normalized = (code || '').trim().toUpperCase();
    if (normalized === 'PROMO10') {
      onApply('PROMO10');
      setMsg('Código aplicado · -50%');
      // Persist in URL so refreshes keep the discount.
      try {
        const u = new URL(window.location.href);
        u.searchParams.set('promo', 'PROMO10');
        window.history.replaceState({}, '', u.toString());
      } catch (_) {}
    } else {
      setMsg('Código no válido.');
    }
  };

  if (applied) {
    return (
      <div className="muted" style={{fontSize: 12, textAlign:'center', marginTop: 10, color: 'var(--accent, #E25A4A)'}}>
        ✓ Código PROMO10 aplicado · -50%
      </div>
    );
  }

  if (!open) {
    return (
      <div style={{textAlign:'center', marginTop: 10}}>
        <button
          type="button"
          onClick={() => setOpen(true)}
          style={{
            background:'none', border:'none', padding: 0, cursor:'pointer',
            fontSize: 12, color:'var(--muted, #7A7876)',
            fontFamily:'inherit', textDecoration:'underline',
          }}
        >
          ¿Tienes código de promoción?
        </button>
      </div>
    );
  }

  return (
    <form onSubmit={submit} style={{display:'flex', gap: 8, marginTop: 10, alignItems:'stretch'}}>
      <input
        type="text"
        placeholder="Código"
        value={code}
        onChange={(e) => { setCode(e.target.value); if (msg) setMsg(''); }}
        autoFocus
        style={{
          flex: 1, padding:'10px 12px', fontSize: 14,
          border:'1px solid var(--line-2, #d9d4c8)', borderRadius: 8,
          background:'var(--card,#fff)', color:'var(--ink,#111)',
          fontFamily:'inherit', boxSizing:'border-box',
          textTransform:'uppercase', letterSpacing:'0.05em',
        }}
      />
      <button
        type="submit"
        style={{
          padding:'10px 16px', fontSize: 14, fontWeight: 600,
          border:'1px solid var(--ink, #111)', borderRadius: 8,
          background:'var(--ink, #111)', color:'#fff', cursor:'pointer',
          fontFamily:'inherit',
        }}
      >
        Aplicar
      </button>
      {msg && (
        <div style={{flexBasis:'100%', fontSize: 12, color: msg.indexOf('aplicado') >= 0 ? 'var(--accent, #E25A4A)' : '#B8392B', marginTop: -2}}>
          {msg}
        </div>
      )}
    </form>
  );
};

const PlanCard = ({ plan }) => {
  const [promo, setPromo] = useState('');
  useEffect(() => { setPromo(getQueryParams().promo); }, []);
  const promoActive = plan.key === 'premium' && promo === 'PROMO10';
  const promoPrice = 10;
  const ctaLabel = promoActive ? `${plan.cta} → $10 USD` : plan.cta;
  return (
  <div className={`plan-card ${plan.featured ? 'featured' : ''}`}>
    {plan.featured && <div className="plan-badge">Recomendado</div>}
    <div className="plan-head">
      <h3 className="serif" style={{fontSize: 32, margin: 0, letterSpacing:'-0.02em'}}>{plan.name}</h3>
      <p className="muted" style={{marginTop: 6, fontSize: 14}}>{plan.tagline}</p>
    </div>
    <div className="plan-price">
      {plan.price === 0 ? (
        <div className="serif" style={{fontSize: 56, lineHeight: 1, letterSpacing: '-0.03em'}}>$0</div>
      ) : promoActive ? (
        <>
          <div className="serif" style={{fontSize: 28, lineHeight: 1, color: 'var(--muted)', textDecoration: 'line-through', letterSpacing: '-0.02em'}}>
            ${plan.price} USD
          </div>
          <div className="serif" style={{fontSize: 56, lineHeight: 1, letterSpacing: '-0.03em', marginTop: 6}}>
            ${promoPrice}<span style={{fontSize: 18, color:'var(--muted)', fontFamily: 'var(--font-sans)', marginLeft: 4}}>USD</span>
          </div>
          <div className="muted" style={{fontSize: 13, marginTop: 6}}>Promo bienvenida · -50% · Solo desde tu email</div>
        </>
      ) : (
        <>
          <div className="serif" style={{fontSize: 56, lineHeight: 1, letterSpacing: '-0.03em'}}>
            ${plan.price}<span style={{fontSize: 18, color:'var(--muted)', fontFamily: 'var(--font-sans)', marginLeft: 4}}>USD</span>
          </div>
          <div className="muted" style={{fontSize: 13, marginTop: 6}}>Pago único por propiedad · Sin suscripción</div>
        </>
      )}
    </div>
    {plan.key === 'premium' ? (
      <>
        <PremiumCTA ctaStyle={plan.ctaStyle} label={ctaLabel} promoOverride={promo} />
        <PromoToggle promo={promo} onApply={setPromo} />
      </>
    ) : (
      <a href="/" className={`btn btn-${plan.ctaStyle} btn-lg plan-cta`} style={{textDecoration:'none', display:'inline-flex', alignItems:'center', justifyContent:'center'}}>
        {plan.cta}
      </a>
    )}
    <hr className="hr" style={{margin: '28px 0'}} />
    <ul className="plan-features">
      {plan.features.map((f, i) => (
        <li key={i} className={f.included ? '' : 'not-included'}>
          <span className="feat-check">
            {f.included ? (
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M20 6L9 17l-5-5"/></svg>
            ) : (
              <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6L6 18M6 6l12 12"/></svg>
            )}
          </span>
          <span style={{fontWeight: f.bold ? 600 : 400}}>{f.text}</span>
        </li>
      ))}
    </ul>
  </div>
  );
};

const plans = [
  {
    key: 'free',
    name: 'Gratis',
    tagline: 'Descubre tu calificación',
    price: 0,
    cta: 'Audita gratis',
    ctaStyle: 'outline',
    features: [
      { text: 'Calificación global A–D', included: true },
      { text: 'Score en las 9 categorías', included: true },
      { text: '3 áreas críticas identificadas', included: true },
      { text: 'Recomendaciones específicas por categoría', included: false },
      { text: 'Plan de acción priorizado por impacto', included: false },
      { text: 'Título y descripción reescritos con IA', included: false },
      { text: 'Análisis de competencia local', included: false },
      { text: 'Reporte en PDF descargable', included: false },
    ],
  },
  {
    key: 'premium',
    name: 'Premium',
    tagline: 'Reporte completo con plan de acción',
    price: 20,
    cta: 'Obtener reporte premium',
    ctaStyle: 'accent',
    featured: true,
    features: [
      { text: 'Todo lo de Gratis', included: true, bold: true },
      { text: 'Recomendaciones específicas por categoría', included: true },
      { text: 'Plan de acción priorizado por impacto', included: true },
      { text: 'Título y descripción reescritos con IA', included: true },
      { text: 'Análisis de competencia local (5 propiedades)', included: true },
      { text: 'Sugerencias de pricing por temporada', included: true },
      { text: 'Reporte en PDF descargable', included: true },
      { text: 'Re-audita sin costo durante 30 días', included: true },
    ],
  },
];

const PricingTable = () => (
  <section className="section" style={{paddingTop: 32}}>
    <div className="wrap">
      <div className="plans-grid plans-grid-2">
        {plans.map(p => <PlanCard key={p.key} plan={p} />)}
      </div>
      <p className="muted" style={{textAlign:'center', fontSize: 13, marginTop: 32}}>
        Precios en dólares americanos; Mercado Pago cobra el equivalente en MXN. Garantía de satisfacción de 30 días.
      </p>
    </div>
  </section>
);

const WhatYouGet = () => {
  const items = [
    { title: 'Calificación clara A–D', desc: 'Un resumen ejecutivo de la salud de tu propiedad en 9 categorías, con una calificación tipo boleta que se entiende al instante.' },
    { title: 'Recomendaciones accionables', desc: 'No es teoría. Cada área débil trae una instrucción concreta: qué foto cambiar, qué palabra añadir al título, qué precio ajustar.' },
    { title: 'Reescritura con IA', desc: 'Nuestra IA reescribe tu título y descripción usando palabras clave de alta conversión en tu zona y tu tipo de propiedad.' },
    { title: 'Competencia local', desc: 'Comparamos tu anuncio con 5 competidores directos: amenities que te faltan, gaps de precio y qué están haciendo mejor que tú.' },
    { title: 'Plan priorizado', desc: 'Ordenamos las mejoras por impacto estimado en reservas. Empieza por lo que más mueve la aguja, no por lo más fácil.' },
    { title: 'Reporte PDF', desc: 'Descarga todo el análisis en un PDF claro que puedes compartir con tu socio, asistente o property manager.' },
  ];
  return (
    <section className="section section-tinted">
      <div className="wrap">
        <div className="section-head" style={{textAlign:'center', margin: '0 auto 48px'}}>
          <span className="eyebrow" style={{justifyContent:'center'}}>Qué incluye el premium</span>
          <h2 className="h2" style={{margin: '16px auto 0', maxWidth: 700}}>
            Todo lo que necesitas para subir tu calificación.
          </h2>
        </div>
        <div className="what-grid">
          {items.map((it, i) => (
            <div key={i} className="what-card">
              <div className="mono muted" style={{fontSize: 12, letterSpacing: '0.04em'}}>{String(i+1).padStart(2, '0')}</div>
              <h3 className="serif" style={{fontSize: 24, margin: '16px 0 10px', letterSpacing:'-0.015em'}}>{it.title}</h3>
              <p className="muted" style={{margin: 0, lineHeight: 1.55, fontSize: 14}}>{it.desc}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

const ROICalc = () => {
  const [revenue, setRevenue] = useState(30000);
  const uplift = Math.round(revenue * 0.23);
  const payback = Math.max(1, Math.ceil(20 * 18 / Math.max(1, uplift/30))); // days
  return (
    <section className="section">
      <div className="wrap">
        <div className="roi-grid">
          <div>
            <span className="eyebrow">Calculadora</span>
            <h2 className="h2" style={{margin: '16px 0 16px'}}>
              Tu ROI estimado<br/>en <em>10 segundos</em>.
            </h2>
            <p className="muted" style={{maxWidth: 440}}>
              Nuestros usuarios premium han visto un +23% de revenue mensual
              tras aplicar las recomendaciones. Este es tu potencial:
            </p>
          </div>
          <div className="roi-card card card-pad">
            <label className="eyebrow">Tu revenue mensual actual (MXN)</label>
            <div className="roi-input">
              <span>$</span>
              <input type="range" min="5000" max="100000" step="1000" value={revenue} onChange={e => setRevenue(+e.target.value)} />
            </div>
            <div className="mono" style={{fontSize: 32, fontWeight: 500, marginTop: 8}}>
              ${revenue.toLocaleString('es-MX')}<span className="muted" style={{fontSize: 14}}> MXN</span>
            </div>
            <hr className="hr" style={{margin: '28px 0'}} />
            <div className="roi-result">
              <div>
                <div className="muted" style={{fontSize: 12, textTransform:'uppercase', letterSpacing: '0.08em'}}>Revenue potencial extra</div>
                <div className="serif" style={{fontSize: 48, color: 'var(--good)', letterSpacing:'-0.02em', marginTop: 4}}>
                  +${uplift.toLocaleString('es-MX')}<span style={{fontSize: 16, color:'var(--muted)', fontFamily:'var(--font-sans)'}}>/mes</span>
                </div>
              </div>
            </div>
            <div className="roi-payback">
              <span>El reporte de $20 USD se paga solo en</span>
              <strong className="mono">&lt; 1 día</strong>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

const FAQ = () => {
  const [open, setOpen] = useState(0);
  const qs = [
    { q: '¿Qué necesito para auditar mi Airbnb?', a: 'Solo el link público de tu anuncio. No pedimos credenciales ni acceso a tu cuenta de Airbnb — auditamos datos públicos y los complementamos con información del mercado local.' },
    { q: '¿El pago de $20 es mensual?', a: 'No, es un pago único por propiedad. Durante 30 días puedes re-auditar esa misma propiedad sin costo para ver tu progreso.' },
    { q: '¿Cómo funciona el análisis de competencia?', a: 'Identificamos 5 propiedades similares a la tuya en un radio cercano y comparamos precio, amenities, puntuación y calidad del anuncio. Ves exactamente dónde te quedas atrás.' },
    { q: '¿La reescritura con IA respeta mi estilo?', a: 'Sí. Partimos de tu anuncio actual y conservamos tu tono. Solo optimizamos palabras clave, estructura y llamados a acción según lo que funciona en tu zona.' },
    { q: '¿Qué pasa si no me gusta el reporte?', a: 'Tenemos garantía de satisfacción de 30 días. Si el reporte no te aporta valor, te devolvemos el pago completo sin preguntas.' },
    { q: '¿Tienen descuento por volumen?', a: 'Sí. Si gestionas 5 o más propiedades, escríbenos y te hacemos una propuesta ajustada.' },
  ];
  return (
    <section className="section" id="faq">
      <div className="wrap">
        <div className="section-head" style={{textAlign:'center', margin: '0 auto 48px'}}>
          <span className="eyebrow" style={{justifyContent:'center'}}>Preguntas frecuentes</span>
          <h2 className="h2" style={{margin: '16px auto 0'}}>Antes de que preguntes</h2>
        </div>
        <div className="faq">
          {qs.map((item, i) => (
            <div key={i} className={`faq-item ${open === i ? 'open' : ''}`}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                <span>{item.q}</span>
                <span className="faq-icon">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 9l6 6 6-6"/></svg>
                </span>
              </button>
              <div className="faq-a"><p>{item.a}</p></div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { PricingHero, PricingTable, WhatYouGet, ROICalc, FAQ, PremiumCTA });
