// js/results.jsx — Results page + Starter Pack offer + Order bumps
// All window lookups done lazily inside components

// ─── NFC Product Placeholder ──────────────────────────────────────────
const NFCCard = () => (
  <div style={{
    width: 120, height: 76,
    background: 'linear-gradient(135deg, #1a1a1a 0%, #2a2a2a 60%, #1a1a1a 100%)',
    borderRadius: 10,
    border: '1px solid rgba(255,255,255,.18)',
    boxShadow: '0 12px 40px rgba(0,0,0,.6), 0 0 30px rgba(59,123,246,.2)',
    position: 'relative',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    flexShrink: 0,
    transform: 'rotate(12deg)',
  }}>
    <div style={{ textAlign: 'center' }}>
      <div style={{ fontFamily: 'Plus Jakarta Sans,sans-serif', fontWeight: 800, fontSize: 13, color: '#fff', letterSpacing: '-0.3px' }}>Go<span style={{ color: '#3B7BF6' }}>Rently</span></div>
    </div>
    <div style={{ position: 'absolute', top: 8, right: 10, fontSize: 14 }}>📡</div>
    {/* Metal sheen */}
    <div style={{ position: 'absolute', inset: 0, borderRadius: 10, background: 'linear-gradient(135deg, rgba(255,255,255,.08) 0%, transparent 60%)', pointerEvents: 'none' }} />
  </div>
);

// ─── Direct booking site mini mockup ─────────────────────────────────
const BookingSiteMockup = () => {
  const BrowserWindow = window.BrowserWindow;
  return (
  <BrowserWindow width={220} title="votre-location.fr">
    <div style={{ padding: '12px 14px' }}>
      <div style={{ height: 48, background: 'linear-gradient(135deg,#162B52,#1E3A6E)', borderRadius: 8, marginBottom: 10, display:'flex',alignItems:'center',justifyContent:'center',fontSize:10,color:'#94A3B8' }}>[ photo propriété ]</div>
      <div style={{ fontSize: 11, fontWeight: 700, color: '#fff', marginBottom: 6 }}>Loft Oberkampf · Paris 11e</div>
      <div style={{ display: 'flex', gap: 4, marginBottom: 8 }}>
        {['Juin','Juil','Août'].map((m,i) => (
          <div key={i} style={{ flex:1, background:'rgba(59,123,246,.15)', border:'1px solid rgba(59,123,246,.25)', borderRadius:5, padding:'4px 0', fontSize:9, color:'#7BA8F6', textAlign:'center' }}>{m}</div>
        ))}
      </div>
      <div style={{ background: '#3B7BF6', color: '#fff', borderRadius: 7, padding: '7px', fontSize: 11, fontWeight: 700, textAlign: 'center' }}>Réserver directement</div>
      <div style={{ fontSize: 9, color: '#4A6080', textAlign: 'center', marginTop: 5 }}>Code promo DIRECT10 — 10% off</div>
    </div>
  </BrowserWindow>
  );
};

// ─── Animated counter hook ────────────────────────────────────────────
const useCounter = (target, duration = 400) => {
  const [val, setVal] = React.useState(target);
  const prev = React.useRef(target);
  React.useEffect(() => {
    const start = prev.current;
    const diff = target - start;
    if (diff === 0) return;
    const startTime = performance.now();
    const step = (now) => {
      const elapsed = now - startTime;
      const progress = Math.min(elapsed / duration, 1);
      const eased = 1 - Math.pow(1 - progress, 3);
      setVal(Math.round(start + diff * eased));
      if (progress < 1) requestAnimationFrame(step);
      else prev.current = target;
    };
    requestAnimationFrame(step);
  }, [target]);
  return val;
};

// ─── Order bump card ──────────────────────────────────────────────────
const OrderBumpCard = ({ title, desc, checked, onToggle, onTotalChange, accent, children }) => {
  return (
    <div
      onClick={onToggle}
      style={{
        background: checked ? `${accent}0F` : 'rgba(255,255,255,.04)',
        border: `1.5px solid ${checked ? accent : 'rgba(255,255,255,.1)'}`,
        borderRadius: 16,
        padding: '20px 22px',
        cursor: 'pointer',
        transition: 'all .25s ease',
        marginBottom: 16,
      }}
    >
      <div style={{ display: 'flex', gap: 16, alignItems: 'flex-start' }}>
        {/* Checkbox */}
        <div style={{
          width: 22, height: 22, borderRadius: 6,
          background: checked ? `linear-gradient(135deg,${accent},#1a4fd6)` : 'rgba(255,255,255,.08)',
          border: `2px solid ${checked ? accent : 'rgba(255,255,255,.2)'}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0, marginTop: 2, transition: 'all .2s',
        }}>
          {checked && (
            <svg width="12" height="9" viewBox="0 0 12 9" fill="none" style={{ animation: 'fadeIn .2s ease' }}>
              <path d="M1 4L4.5 7.5L11 1" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          )}
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: 'Plus Jakarta Sans,sans-serif', fontWeight: 700, fontSize: 15, color: '#fff', marginBottom: 6 }}>{title}</div>
          <p style={{ fontSize: 13, color: '#94A3B8', lineHeight: 1.65, marginBottom: checked ? 14 : 0 }}>{desc}</p>
          {checked && children}
        </div>
      </div>
    </div>
  );
};

// ─── Main Results Page ────────────────────────────────────────────────
const ResultsPage = ({ answers = {}, onRestart }) => {
  const { useTweaks, useInView, GlowOrb, PillBadge, PDFCard, CTAButton, BrowserWindow } = window;
  const { accent } = useTweaks();
  const [visible, setVisible] = React.useState(false);
  const [bump1, setBump1] = React.useState(false);
  const [bump2, setBump2] = React.useState(false);
  const [nfcQty, setNfcQty] = React.useState(1);
  const [ref, inView] = useInView(0.01);

  const nfcPrices = { 1: 39, 3: 99, 5: 149 };
  const basePrice = 197;
  const totalTarget = basePrice + (bump1 ? nfcPrices[nfcQty] : 0) + (bump2 ? 297 : 0);
  const displayTotal = useCounter(totalTarget);

  React.useEffect(() => {
    const t = setTimeout(() => setVisible(true), 100);
    return () => clearTimeout(t);
  }, []);

  // Determine which diagnostic blocks to show based on answers
  const platforms = answers.q2 || [];
  const onlyAirbnb = platforms.length === 0 || (platforms.length === 1 && platforms[0] === 'Airbnb') || platforms.length === 0;
  const pricingIssue = ['Un prix fixe toute l\'année','Je varie manuellement selon les saisons','Je m\'adapte au marché mais sans outil précis'].includes(answers.q4);
  const portalIssue = ['Un message automatique Airbnb avec les informations de base','Rien de particulier, ils me contactent si besoin'].includes(answers.q5);
  const upsellIssue = ['Non, je n\'y ai pas pensé','Parfois, de manière informelle'].includes(answers.q6);

  // Show all 4 blocks if no real answers (demo mode), else show relevant ones
  const hasAnswers = Object.keys(answers).length > 1;
  const showDistrib = !hasAnswers || onlyAirbnb;
  const showPricing = !hasAnswers || pricingIssue;
  const showPortal  = !hasAnswers || portalIssue;
  const showUpsell  = !hasAnswers || upsellIssue;

  const diagBlocks = [
    showDistrib && { icon:'🔴', label:'Distribution limitée', text:"Vous dépendez à 100% de l'algorithme Airbnb. Vous êtes invisible pour tous les voyageurs qui cherchent sur Booking.com ou Abritel. C'est votre premier levier de croissance." },
    showPricing && { icon:'🔴', label:'Prix sous-optimisés', text:"Votre tarif ne s'adapte pas automatiquement à la demande. Résultat : des réservations perdues en période creuse et de l'argent laissé sur la table en haute saison." },
    showPortal  && { icon:'🔴', label:'Expérience voyageur basique', text:"Vos voyageurs arrivent sans information structurée. Cela génère des questions répétitives, réduit la perception de qualité et vous prive des services additionnels." },
    showUpsell  && { icon:'🔴', label:'Revenus additionnels inexistants', text:"Chaque séjour se termine sans revenu complémentaire. Transfert aéroport, panier d'accueil, late check-out — ces offres ne nécessitent aucun effort si elles sont intégrées à votre système." },
  ].filter(Boolean);

  const firstName = answers.firstName || 'vous';

  const packItems = [
    { icon:'📱', title:'Votre guestbook digital', subtitle:'Créé par notre équipe', desc:"WiFi, instructions, guide local, règles, services — configuré pour votre propriété. Prêt en 48h.", value:'97€', color:'#10B981' },
    { icon:'💰', title:"Système d'upsell", subtitle:'Intégré au portal', desc:"Vos offres de services directement dans le portal. Chaque voyageur voit les options. Chaque commande est un revenu supplémentaire.", value:'67€', color:'#10B981' },
    { icon:'✉️', title:'Pack Templates Communication', subtitle:'Messages prêts à envoyer', desc:"Accueil, check-in, check-out, demande d'avis — chaque étape couverte par un message professionnel.", value:'37€', color:'#10B981' },
    { icon:'🤖', title:'Outils IA GoRently', subtitle:'Accès à vie', desc:"Générez des titres d'annonces, descriptions optimisées et réponses aux avis en quelques secondes.", value:'47€', color:'#10B981' },
  ];

  return (
    <div style={{
      minHeight: '100vh',
      background: '#0A1628',
      animation: 'fadeIn .5s ease',
    }}>
      {/* Header */}
      <div style={{ background: 'linear-gradient(180deg,#162B52 0%,#0A1628 100%)', padding: 'clamp(48px,8vw,80px) clamp(16px,6vw,80px) 60px', textAlign: 'center', position: 'relative', overflow: 'hidden' }}>
        <GlowOrb size={500} opacity={0.12} top={-100} left={'calc(50% - 250px)'} />
        <div style={{ position: 'relative', zIndex: 2 }}>
          <div style={{ marginBottom: 16 }}>
            <PillBadge>Votre diagnostic GoRently</PillBadge>
          </div>
          <h1 style={{ fontFamily: 'Plus Jakarta Sans,sans-serif', fontWeight: 800, fontSize: 44, color: '#fff', letterSpacing: '-1.5px', lineHeight: 1.2, marginBottom: 16, textWrap: 'balance' }}>
            {firstName !== 'vous' ? `${firstName}, votre` : 'Votre'} location a des atouts réels —<br/>et des leviers que vous <span className="grad">n'exploitez pas encore.</span>
          </h1>
          <p style={{ fontSize: 17, color: '#94A3B8', maxWidth: 560, margin: '0 auto' }}>
            Voici ce que nous avons identifié à partir de vos réponses, et comment GoRently peut vous aider à passer au niveau supérieur.
          </p>
        </div>
      </div>

      <div ref={ref} style={{ maxWidth: 860, margin: '0 auto', padding: '0 clamp(16px,4vw,40px) 80px' }}>

        {/* Diagnostic blocks */}
        <div style={{ marginBottom: 60 }}>
          <h2 style={{ fontFamily: 'Plus Jakarta Sans,sans-serif', fontWeight: 700, fontSize: 22, color: '#fff', marginBottom: 20, marginTop: 48 }}>Ce que nous avons détecté :</h2>
          {diagBlocks.map((b, i) => (
            <div key={i} style={{
              background: 'rgba(239,68,68,.06)',
              borderLeft: '3px solid #EF4444',
              borderRadius: '0 10px 10px 0',
              padding: '16px 20px',
              marginBottom: 12,
              display: 'flex', gap: 14, alignItems: 'flex-start',
              opacity: visible ? 1 : 0,
              transform: visible ? 'translateX(0)' : 'translateX(-24px)',
              transition: `opacity .5s ${i * .18}s, transform .5s ${i * .18}s`,
            }}>
              <span style={{ fontSize: 18, flexShrink: 0 }}>{b.icon}</span>
              <div>
                <div style={{ fontFamily: 'Plus Jakarta Sans,sans-serif', fontWeight: 700, fontSize: 14, color: '#EF4444', marginBottom: 4 }}>{b.label}</div>
                <p style={{ fontSize: 14, color: '#94A3B8', lineHeight: 1.65, margin: 0 }}>{b.text}</p>
              </div>
            </div>
          ))}
        </div>

        {/* Transition phrase */}
        <div style={{ borderLeft: `3px solid ${accent}`, padding: '16px 24px', marginBottom: 60, background: `${accent}0A`, borderRadius: '0 12px 12px 0' }}>
          <p style={{ fontSize: 17, color: '#fff', fontStyle: 'italic', lineHeight: 1.7, margin: 0 }}>
            Bonne nouvelle : tout ce que nous venons d'identifier, GoRently le résout. En 48h. Sans que vous ayez quoi que ce soit à configurer.
          </p>
        </div>

        {/* Starter Pack */}
        <div style={{ marginBottom: 40 }}>
          <div style={{ textAlign: 'center', marginBottom: 36 }}>
            <div style={{ display: 'inline-block', background: `${accent}20`, color: accent, borderRadius: 100, padding: '4px 16px', fontSize: 11, fontWeight: 700, letterSpacing: '1px', textTransform: 'uppercase', marginBottom: 14 }}>La solution adaptée à votre situation</div>
            <h2 style={{ fontFamily: 'Plus Jakarta Sans,sans-serif', fontWeight: 800, fontSize: 36, color: '#fff', letterSpacing: '-1px', marginBottom: 10 }}>GoRently Starter Pack</h2>
            <p style={{ fontSize: 15, color: '#94A3B8' }}>Un système complet, installé pour vous. Pas un outil. Pas un template. Un setup prêt à l'emploi.</p>
          </div>

          {/* Pack items */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {packItems.map((item, i) => (
              <div key={i} style={{
                background: 'rgba(255,255,255,.04)',
                border: '1px solid rgba(255,255,255,.08)',
                borderLeft: `3px solid ${item.color}`,
                borderRadius: '0 12px 12px 0',
                padding: '16px 20px',
                display: 'flex', gap: 16, alignItems: 'center',
                opacity: visible ? 1 : 0,
                transform: visible ? 'translateX(0)' : 'translateX(24px)',
                transition: `opacity .5s ${.4 + i * .12}s, transform .5s ${.4 + i * .12}s`,
              }}>
                <div style={{ width: 44, height: 44, background: 'rgba(16,185,129,.12)', borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22, flexShrink: 0 }}>{item.icon}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
                    <span style={{ fontFamily: 'Plus Jakarta Sans,sans-serif', fontWeight: 700, fontSize: 15, color: '#fff' }}>{item.title}</span>
                    <span style={{ fontSize: 11, color: '#94A3B8' }}>— {item.subtitle}</span>
                  </div>
                  <p style={{ fontSize: 13, color: '#94A3B8', lineHeight: 1.6, margin: 0 }}>{item.desc}</p>
                </div>
                <div style={{ textAlign: 'right', flexShrink: 0 }}>
                  <div style={{ fontSize: 12, color: '#4A6080', textDecoration: 'line-through' }}>{item.value}</div>
                  <div style={{ fontSize: 13, color: '#10B981', fontWeight: 700 }}>Inclus</div>
                </div>
              </div>
            ))}
          </div>

          {/* BONUS Card */}
          <div style={{
            marginTop: 16,
            background: 'linear-gradient(135deg,rgba(245,158,11,.08),rgba(59,123,246,.06))',
            border: '1.5px solid',
            borderImageSource: 'linear-gradient(135deg,rgba(245,158,11,.6),rgba(59,123,246,.4))',
            borderImageSlice: 1,
            borderRadius: 16,
            padding: '22px 24px',
            position: 'relative',
            opacity: visible ? 1 : 0,
            transition: 'opacity .6s 1s',
          }}>
            <div style={{ position: 'absolute', top: -12, left: 20, background: 'linear-gradient(135deg,#F59E0B,#FBBF24)', color: '#0A1628', borderRadius: 8, padding: '4px 12px', fontSize: 11, fontWeight: 800, transform: 'rotate(-1.5deg)', boxShadow: '0 4px 16px rgba(245,158,11,.4)' }}>🎁 BONUS EXCLUSIF</div>
            <div style={{ display: 'flex', gap: 20, alignItems: 'flex-start', marginTop: 10 }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: 'Plus Jakarta Sans,sans-serif', fontWeight: 800, fontSize: 17, color: '#fff', marginBottom: 8 }}>Audit Setup &amp; Opportunités — votre feuille de route personnalisée</div>
                <p style={{ fontSize: 13, color: '#94A3B8', lineHeight: 1.7, marginBottom: 12 }}>Ce n'est pas le diagnostic de 3 minutes que vous venez de faire. C'est une analyse individuelle approfondie de votre setup complet : annonce, positionnement prix, expérience voyageur, distribution, opportunités d'upsell.</p>
                <p style={{ fontSize: 13, color: '#CBD5E1', lineHeight: 1.7, marginBottom: 0 }}>Vous recevez un <strong>plan d'action détaillé en PDF</strong> + <strong>walkthrough vidéo</strong>. Et après ça, vous n'êtes plus seul.</p>
              </div>
              <div style={{ display: 'flex', gap: 12, flexShrink: 0, alignItems: 'center' }}>
                <PDFCard rotation={-5} width={130} />
              </div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 12 }}>
              <div style={{ fontSize: 12, color: '#4A6080', textDecoration: 'line-through', marginRight: 8 }}>197€</div>
              <div style={{ fontSize: 14, color: '#F59E0B', fontWeight: 700 }}>Offert</div>
            </div>
          </div>
        </div>

        {/* Price summary */}
        <div style={{
          background: 'rgba(255,255,255,.04)',
          border: `1.5px solid ${accent}44`,
          borderRadius: 20,
          padding: '32px',
          textAlign: 'center',
          marginBottom: 32,
          boxShadow: `0 0 60px ${accent}18`,
        }}>
          <div style={{ fontSize: 13, color: '#94A3B8', marginBottom: 6 }}>Valeur totale : <span style={{ textDecoration: 'line-through' }}>445€</span></div>
          <div style={{ fontFamily: 'Plus Jakarta Sans,sans-serif', fontWeight: 800, fontSize: 56, color: '#fff', letterSpacing: '-2px', lineHeight: 1.1 }}>197€</div>
          <p style={{ fontSize: 15, color: '#94A3B8', fontStyle: 'italic', marginTop: 8 }}>C'est votre première étape avec GoRently. Pas la dernière.</p>
        </div>

        {/* Order Bumps */}
        <div style={{ marginBottom: 32 }}>
          <h3 style={{ fontFamily: 'Plus Jakarta Sans,sans-serif', fontWeight: 700, fontSize: 18, color: '#fff', marginBottom: 16 }}>Personnalisez votre commande :</h3>

          <OrderBumpCard
            title="Oui, j'ajoute les plaques NFC GoRently"
            desc="Vos voyageurs sortent leurs bagages — la plaque GoRently est posée sur la table d'entrée. Un scan de téléphone, le portal s'ouvre immédiatement. Un objet élégant, une interaction intuitive."
            checked={bump1}
            onToggle={() => setBump1(b => !b)}
            accent={accent}
          >
            <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
              <NFCCard />
              <div>
                <div style={{ fontSize: 12, color: '#94A3B8', marginBottom: 8 }}>Choisissez votre quantité :</div>
                <div style={{ display: 'flex', gap: 8 }}>
                  {[{q:1,p:'39€'},{q:3,p:'99€ (33€/pièce)'},{q:5,p:'149€ (30€/pièce)'}].map(({q,p}) => (
                    <div key={q} onClick={e => { e.stopPropagation(); setNfcQty(q); }}
                      style={{ background: nfcQty===q ? `${accent}22` : 'rgba(255,255,255,.05)', border:`1.5px solid ${nfcQty===q ? accent : 'rgba(255,255,255,.12)'}`, borderRadius:8, padding:'6px 12px', fontSize:11, color: nfcQty===q ? '#fff' : '#94A3B8', cursor:'pointer', fontWeight: nfcQty===q ? 700 : 400, whiteSpace:'nowrap', transition:'all .2s' }}>
                      {q} plaque{q>1?'s':<></>} — +{p}
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </OrderBumpCard>

          <OrderBumpCard
            title="Oui, je veux mon site de réservation directe"
            desc="Airbnb prend entre 15% et 20% sur chaque réservation. Votre portal GoRently peut changer ça. On crée votre site de réservation personnel avec calendrier, paiement Stripe intégré et code de réduction exclusif."
            checked={bump2}
            onToggle={() => setBump2(b => !b)}
            accent={accent}
          >
            <div style={{ display: 'flex', gap: 16, alignItems: 'flex-start', flexWrap: 'wrap' }}>
              <BookingSiteMockup />
              <div style={{ fontSize: 12, color: '#94A3B8', lineHeight: 1.7 }}>
                <div style={{ fontWeight: 600, color: '#fff', marginBottom: 4 }}>Inclus :</div>
                {['Site one-page à votre image','Calendrier synchronisé','Paiement Stripe intégré','Code promo intégré au portal'].map(i => (
                  <div key={i} style={{ display: 'flex', gap: 6, marginBottom: 3 }}>
                    <span style={{ color: '#10B981' }}>✓</span> {i}
                  </div>
                ))}
                <div style={{ marginTop: 8 }}>
                  <span style={{ textDecoration: 'line-through', color: '#4A6080' }}>497€</span>{' '}
                  <span style={{ color: '#fff', fontWeight: 700 }}>→ +297€</span>
                </div>
              </div>
            </div>
          </OrderBumpCard>
        </div>

        {/* Final CTA */}
        <div style={{ textAlign: 'center' }}>
          <CTAButton size="large" fullWidth style={{ fontSize: 18, animation: 'pulseGlow 2.5s ease-in-out infinite' }}>
            Valider ma commande — {displayTotal}€ →
          </CTAButton>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 16, marginTop: 18, color: '#4A6080', fontSize: 13, flexWrap: 'wrap' }}>
            <span>🔒 Paiement sécurisé</span>
            <span style={{ fontWeight: 700, color: '#6B7FBF', letterSpacing: '.5px' }}>stripe</span>
            <span>·</span>
            <span>Garantie satisfaction 14 jours</span>
            <span>·</span>
            <span>Vos données ne sont jamais partagées</span>
          </div>

          <button onClick={onRestart} style={{ marginTop: 32, background: 'transparent', border: 'none', color: '#4A6080', fontSize: 13, cursor: 'pointer', textDecoration: 'underline' }}>
            ← Recommencer le diagnostic
          </button>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { ResultsPage });
