/* ============================================================
   DatingScout.ai — Landing app (React)
   Quiz matcher + platform hub + card variants + hero variants.
   ============================================================ */
const { useState, useMemo, useRef, useEffect } = React;
const P = window.NN.platforms;

/* ---------------- QUIZ DEFINITION ---------------- */
const QUIZ = [
  { key:'goal', q:'What are you actually looking for?', sub:'No judgment. This shapes everything else.',
    opts:[
      { ic:'🫀', t:'A real companion', d:'Someone to talk to daily, who remembers you', v:{arch:'companion', memory:2} },
      { ic:'🔥', t:'Uncensored chat', d:'Spicy, adult, few guard-rails', v:{arch:'nsfw', nsfw:2} },
      { ic:'🎭', t:'Roleplay & stories', d:'Characters, scenarios, creative writing', v:{arch:'roleplay'} },
      { ic:'💝', t:'A virtual girlfriend', d:'The full girlfriend-experience package', v:{arch:'girlfriend', image:1} },
    ] },
  { key:'nsfw', q:'How important is NSFW / uncensored content?', sub:'The main site stays SFW — this just tunes your match.',
    opts:[
      { ic:'🌶️', t:'Essential', d:"It's the whole point", v:{nsfw:2} },
      { ic:'😏', t:'Nice to have', d:'I want the option there', v:{nsfw:1} },
      { ic:'🧊', t:'Prefer it SFW', d:'Keep things clean', v:{nsfw:-2, sfw:true} },
    ] },
  { key:'voice', q:'Do you want to actually hear them?', sub:'Voice calls vs. text-only.',
    opts:[
      { ic:'🎙️', t:'Yes — voice matters', d:'Real-time voice calls', v:{voice:2} },
      { ic:'💬', t:'Text is fine', d:"I'm here to read", v:{voice:0} },
    ] },
  { key:'memory', q:'Should they remember everything?', sub:'Long-term memory across weeks vs. short recall.',
    opts:[
      { ic:'🧠', t:'Yes, total recall', d:'Remember our whole history', v:{memory:2} },
      { ic:'🌗', t:'Basic recall is fine', d:'Recent context is enough', v:{memory:0} },
    ] },
  { key:'visual', q:'How much do visuals matter?', sub:'Selfies, generated images, lifelike avatars.',
    opts:[
      { ic:'📸', t:'Show me — images & selfies', d:'Lifelike, on demand', v:{image:2} },
      { ic:'✍️', t:"Words over pictures", d:'Conversation is what I want', v:{image:0} },
    ] },
  { key:'budget', q:"What's your budget?", sub:'Most have a free tier; pro unlocks the good stuff.',
    opts:[
      { ic:'🆓', t:'Free only', d:"Won't pay a cent", v:{budget:0} },
      { ic:'💸', t:'Under $15 / mo', d:'A reasonable subscription', v:{budget:1} },
      { ic:'💎', t:'Whatever it takes', d:'Best experience, price aside', v:{budget:2} },
    ] },
  { key:'extra', q:'Anything else that seals the deal?', sub:'Pick the one that matters most to you.',
    opts:[
      { ic:'🛠️', t:'I love to tinker', d:'Bring my own model, tweak settings', v:{tinker:true} },
      { ic:'🎚️', t:'Toy / Lovense sync', d:'Physical device integration', v:{lovense:true} },
      { ic:'🪶', t:'Keep it simple', d:'Set up fast, just works', v:{simple:true} },
    ] },
];

function scorePlatform(p, pref) {
  let s = 46;
  const memMap = { 'Excellent':2, 'Good':1.4, 'Average':0.8, 'Basic':0.3 };
  // archetype affinity
  const archCat = { companion:'COMPANION AI', nsfw:'NSFW COMPANION', roleplay:'ROLEPLAY', girlfriend:'AI GIRLFRIEND' };
  if (pref.arch && p.cat === archCat[pref.arch]) s += 12;
  if (pref.arch === 'companion' && p.f.memory === 'Excellent') s += 4;
  // nsfw
  if (pref.nsfw >= 2) s += p.f.nsfw ? 9 : -24;
  else if (pref.nsfw === 1) s += p.f.nsfw ? 5 : 0;
  if (pref.sfw && !p.f.nsfw) s += 14;
  if (pref.sfw && p.f.nsfw) s -= 8;
  // voice
  if (pref.voice >= 2) s += p.f.voice ? 7 : -18;
  // memory — graded, so Excellent/Good/Average/Basic spread out
  if (pref.memory >= 2) s += (memMap[p.f.memory] || 0) * 6;
  else s += (memMap[p.f.memory] || 0) * 1.5;
  // image
  if (pref.image >= 2) s += p.f.image ? 7 : -12;
  else if (pref.image === 1) s += p.f.image ? 4 : 0;
  // budget
  if (pref.budget === 0) s += (p.free || p.price === 0) ? 11 : -16;
  else if (pref.budget === 1) s += p.price <= 15 ? 6 : -7;
  else if (pref.budget === 2) s += 3;
  // extras
  if (pref.tinker && p.id === 'promptchan') s += 14;
  if (pref.lovense) s += p.f.lovense ? 20 : -12;
  if (pref.simple && (p.id === 'replika' || p.id === 'dreamgf' || p.id === 'character-ai')) s += 7;
  // quality signal — rating + review volume give natural separation
  s += (p.rating - 4) * 7;
  s += Math.min(p.reviews / 1400, 3);
  return Math.max(38, Math.min(97, Math.round(s)));
}

/* ---------------- STARS ---------------- */
function Stars({ r }) { return <span className="stars" dangerouslySetInnerHTML={{ __html: window.NN.stars(r) }} />; }

/* ---------------- QUIZ WIDGET ---------------- */
function Quiz({ compact }) {
  const [started, setStarted] = useState(false);
  const [step, setStep] = useState(0);
  const [answers, setAnswers] = useState({});
  const total = QUIZ.length;
  const done = step >= total;

  const pref = useMemo(() => {
    const acc = { nsfw:0, voice:0, memory:0, image:0, budget:1 };
    Object.values(answers).forEach(v => {
      Object.entries(v).forEach(([k, val]) => {
        if (typeof val === 'number') acc[k] = (acc[k] || 0) + val;
        else acc[k] = val;
      });
    });
    return acc;
  }, [answers]);

  const results = useMemo(() => {
    if (!done) return [];
    return P.map(p => ({ p, score: scorePlatform(p, pref) }))
      .sort((a, b) => b.score - a.score).slice(0, 3);
  }, [done, pref]);

  function pick(opt) {
    const q = QUIZ[step];
    setAnswers(a => ({ ...a, [q.key]: opt.v }));
    setTimeout(() => setStep(s => s + 1), 180);
  }
  function reset() { setStarted(false); setStep(0); setAnswers({}); }

  const pct = done ? 100 : Math.round((step / total) * 100);

  if (!started) {
    return (
      <div className="quiz quiz-intro">
        <div className="eyebrow" style={{ color:'var(--violet)' }}>// THE MATCHER</div>
        <h2 style={{ marginTop:14, fontSize:'clamp(26px,3.2vw,40px)' }}>Which AI companion<br/>is built for <span className="neon-text">you?</span></h2>
        <p style={{ marginTop:14, fontSize:17, maxWidth:'46ch' }}>
          Seven quick questions. We weigh NSFW policy, voice, memory, visuals and price
          across {P.length} platforms — and hand you a ranked top three.
        </p>
        <div style={{ display:'flex', gap:12, marginTop:26, flexWrap:'wrap', alignItems:'center' }}>
          <button className="btn btn-neon btn-lg" onClick={() => setStarted(true)}>Start matching →</button>
          <span className="mono" style={{ fontSize:13, color:'var(--ink-dim)' }}>~40 seconds · no signup</span>
        </div>
        <div className="quiz-orbit" aria-hidden="true">
          {P.slice(0,5).map((p,i)=>(
            <span key={p.id} className="orbit-chip" style={{ background:`linear-gradient(140deg,${p.accent[0]},${p.accent[1]})`, '--i':i }}>{p.name.charAt(0)}</span>
          ))}
        </div>
      </div>
    );
  }

  if (done) {
    return (
      <div className="quiz">
        <div className="quiz-prog"><i style={{ width:'100%' }} /></div>
        <div style={{ display:'flex', alignItems:'center', gap:10, marginTop:20 }}>
          <span className="tag-verified">✓ MATCH COMPLETE</span>
        </div>
        <h2 style={{ marginTop:12, fontSize:'clamp(24px,3vw,34px)' }}>Your top {results.length} matches</h2>
        <p className="muted" style={{ marginTop:6, fontSize:15 }}>Ranked by fit against your answers.</p>
        <div className="result-list">
          {results.map((r, i) => (
            <a key={r.p.id} className="result-row" href={`/reviews/platforms/${r.p.id}/`}>
              <span className="result-rank">{i + 1}</span>
              <span className="logo-chip" style={{ width:44, height:44, fontSize:18, background:`linear-gradient(140deg,${r.p.accent[0]},${r.p.accent[1]})`, boxShadow:`0 0 18px ${r.p.accent[0]}55` }}>{r.p.name.charAt(0)}</span>
              <span style={{ minWidth:0 }}>
                <b style={{ fontFamily:'var(--f-head)', fontSize:17, display:'block' }}>{r.p.name}</b>
                <span className="pcard-cat">{r.p.best}</span>
              </span>
              <span className="result-match">
                <b>{r.score}<small>%</small></b>
                <span className="mono" style={{ fontSize:10, color:'var(--ink-dim)', letterSpacing:'0.1em' }}>MATCH</span>
              </span>
            </a>
          ))}
        </div>
        <div style={{ display:'flex', gap:12, marginTop:20, flexWrap:'wrap' }}>
          <a className="btn btn-cta" href={`/reviews/platforms/${results[0].p.id}/`}>See why {results[0].p.name} won →</a>
          <button className="btn btn-ghost" onClick={reset}>Retake</button>
        </div>
      </div>
    );
  }

  const q = QUIZ[step];
  return (
    <div className="quiz">
      <div className="quiz-prog"><i style={{ width: pct + '%' }} /></div>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginTop:18 }}>
        <span className="quiz-step">Question {step + 1} / {total}</span>
        <button className="quiz-step" onClick={reset} style={{ background:'none', border:'none', cursor:'pointer', color:'var(--ink-dim)' }}>↺ restart</button>
      </div>
      <div className="quiz-q" style={{ marginTop:12 }}>{q.q}</div>
      <p className="muted" style={{ marginTop:8, marginBottom:22, fontSize:15 }}>{q.sub}</p>
      <div className="quiz-opts">
        {q.opts.map((o, i) => (
          <button key={i} className={'qopt' + (answers[q.key] === o.v ? ' sel' : '')} onClick={() => pick(o)}>
            <span className="qopt-ico">{o.ic}</span>
            <span className="qopt-txt"><b>{o.t}</b><span>{o.d}</span></span>
            <span className="qopt-key">{i + 1}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

/* ---------------- PLATFORM CARD (3 variants) ---------------- */
function PlatformCard({ p, variant }) {
  const foot = (
    <div className="pcard-foot">
      <div className="price">{p.free ? <b className="free">Free</b> : <><b>${p.price}</b><span className="per">/mo</span></>}</div>
      <a className="btn btn-cta" href={`/reviews/platforms/${p.id}/`} onClick={e => e.stopPropagation()}>Try {p.name} →</a>
    </div>
  );
  const head = (
    <div className="pcard-head">
      <span className="logo-chip" style={{ width:46, height:46, fontSize:19, background:`linear-gradient(140deg,${p.accent[0]},${p.accent[1]})`, boxShadow:`0 0 20px ${p.accent[0]}55` }}>{p.name.charAt(0)}</span>
      <div><div className="pcard-title">{p.name}</div><div className="pcard-cat">{p.cat}</div></div>
      <div style={{ marginLeft:'auto' }} className="tag-verified">★&nbsp;{p.best}</div>
    </div>
  );
  const rating = (
    <div className="row" style={{ gap:7 }}>
      <Stars r={p.rating} /><span className="rating-num">{p.rating.toFixed(1)}</span>
      <span className="rating-ct">({p.reviews.toLocaleString()})</span>
    </div>
  );
  const badges = <div className="badges">{p.badges.map((b, i) => <span key={i} className={'badge' + (i === 1 ? ' cy' : '')}>{b}</span>)}</div>;

  return (
    <div className={'pcard pcard--' + variant} style={{ cursor:'pointer' }}
      onClick={() => { window.location.href = `/reviews/platforms/${p.id}/`; }}>
      {head}{rating}
      <p style={{ fontSize:14.5, color:'var(--ink-soft)', minHeight:42 }}>{p.tagline}</p>
      {badges}
      <hr className="divider" />
      {foot}
    </div>
  );
}

/* ---------------- HUB SECTION ---------------- */
const FILTERS = [
  { id:'all', label:'All Platforms', test:() => true },
  { id:'beginners', label:'Best for Beginners', test:p => ['replika','character-ai','dreamgf'].includes(p.id) },
  { id:'nsfw', label:'NSFW', test:p => p.f.nsfw },
  { id:'voice', label:'With Voice', test:p => p.f.voice },
  { id:'lovense', label:'Lovense Compatible', test:p => p.f.lovense },
  { id:'free', label:'Free Tier', test:p => p.freeTier },
];

function ToyAdVertical() {
  const toy = {
    name: "Solace Pro",
    tag: "VR & AI Sync",
    desc: "AI-sync auto masturbator. Syncs with your AI companion in real time.",
    url: "https://www.lovense.com/r/9crg5t",
    img: "https://cdn.lovense-api.com/images/toy-images/Solace-Pro.png",
    accent: "#7B5FFF",
    cta: "Shop Solace Pro",
  };
  return (
    <a href={toy.url} rel="nofollow sponsored" target="_blank"
      style={{ display:'flex', flexDirection:'column', background:'var(--surface)', border:'1px solid var(--line)',
        borderRadius:'var(--r-lg)', overflow:'hidden', color:'var(--ink)', textDecoration:'none' }}>
      <div style={{ fontFamily:'var(--f-mono)', fontSize:9, color:'var(--ink-dim)', letterSpacing:'.12em',
        padding:'8px 12px 0', textAlign:'right' }}>SPONSORED</div>
      <div style={{ background:'var(--surface-2)', padding:20, display:'flex', alignItems:'center',
        justifyContent:'center', minHeight:150 }}>
        <img src={toy.img} alt={toy.name}
          style={{ maxWidth:120, maxHeight:120, width:'auto', height:'auto', objectFit:'contain' }} />
      </div>
      <div style={{ padding:'14px 16px', display:'flex', flexDirection:'column', alignItems:'center',
        textAlign:'center', gap:7 }}>
        <div style={{ fontFamily:'var(--f-mono)', fontSize:9, color:toy.accent, letterSpacing:'.1em' }}>{toy.tag}</div>
        <div style={{ fontFamily:'var(--f-head)', fontSize:16, fontWeight:700 }}>{toy.name}</div>
        <div style={{ fontSize:12, color:'var(--ink-soft)', lineHeight:1.5 }}>{toy.desc}</div>
        <span style={{ marginTop:6, display:'inline-block', padding:'9px 16px',
          background:`linear-gradient(135deg,${toy.accent},var(--violet))`,
          borderRadius:'var(--r-pill)', fontFamily:'var(--f-head)', fontSize:12,
          fontWeight:700, color:'#fff' }}>{toy.cta} →</span>
      </div>
    </a>
  );
}

function ToyAdHorizontal() {
  const toy = {
    name: "Edge 2",
    tag: "AI Sync · For Him",
    desc: "Adjustable prostate massager with app control. Pairs perfectly with AI companion roleplay.",
    url: "https://www.lovense.com/r/8qmm0w",
    img: "https://rugcdn.lovense.com/UploadFiles/web/affiliateMaterials/20250710/217b9aaa157a4820bfe36a46825200d2.jpg",
    accent: "#3B82F6",
    cta: "Shop Edge 2",
  };
  return (
    <div style={{ border:'1px solid var(--line)', borderRadius:'var(--r-lg)', overflow:'hidden',
      margin:'8px 0', background:'linear-gradient(160deg,rgba(59,130,246,0.08),var(--surface))',
      gridColumn:'1 / -1' }}>
      <div style={{ fontFamily:'var(--f-mono)', fontSize:9, color:'var(--ink-dim)', letterSpacing:'.12em',
        padding:'8px 16px 0', textAlign:'right' }}>SPONSORED</div>
      <img src={toy.img} alt={toy.name}
        style={{ width:'100%', maxHeight:180, objectFit:'cover', display:'block' }} />
      <div style={{ padding:'16px 24px 20px', textAlign:'center' }}>
        <div style={{ fontFamily:'var(--f-mono)', fontSize:10, color:toy.accent,
          letterSpacing:'.1em', marginBottom:6 }}>// {toy.tag.toUpperCase()}</div>
        <div style={{ fontFamily:'var(--f-head)', fontSize:20, fontWeight:700, marginBottom:6 }}>{toy.name}</div>
        <div style={{ fontSize:14, color:'var(--ink-soft)', lineHeight:1.6,
          marginBottom:14, maxWidth:'48ch', margin:'0 auto 14px' }}>{toy.desc}</div>
        <a href={toy.url} rel="nofollow sponsored" target="_blank"
          style={{ display:'inline-block', padding:'11px 24px',
            background:`linear-gradient(135deg,${toy.accent},var(--violet))`,
            borderRadius:'var(--r-pill)', fontFamily:'var(--f-head)', fontSize:14,
            fontWeight:700, color:'#fff', textDecoration:'none' }}>{toy.cta} →</a>
      </div>
    </div>
  );
}

function Hub({ cardVariant, setCardVariant }) {
  const [filter, setFilter] = useState('all');
  const active = FILTERS.find(f => f.id === filter);
  const list = P.filter(active.test);

  // Build cards with ads injected
  const cards = [];
  list.forEach((p, i) => {
    cards.push(<PlatformCard key={p.id} p={p} variant={cardVariant} />);
    // After every 8 cards inject horizontal banner
    if ((i + 1) % 8 === 0 && i + 1 < list.length) {
      cards.push(<ToyAdHorizontal key={'ad-h-' + i} />);
    }
  });

  return (
    <section className="section" id="platforms">
      <div className="wrap-wide">
        <div style={{ display:'flex', alignItems:'flex-start', gap:24 }}>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ display:'flex', alignItems:'flex-end', justifyContent:'space-between', gap:24, flexWrap:'wrap', marginBottom:28 }}>
              <div>
                <div className="eyebrow">// THE HUB</div>
                <h2 style={{ marginTop:14 }}>Every platform, scored</h2>
              </div>
              <span className="mono" style={{ fontSize:13, color:'var(--ink-dim)' }}>{list.length} of {P.length} shown</span>
            </div>
            <div className="pills" style={{ marginBottom:30 }}>
              {FILTERS.map(f => {
                const ct = P.filter(f.test).length;
                return (
                  <button key={f.id} className={'pill' + (filter === f.id ? ' active' : '')} onClick={() => setFilter(f.id)}>
                    {f.label} <span className="ct">{ct}</span>
                  </button>
                );
              })}
            </div>
            <div className="card-grid">
              {cards}
            </div>
          </div>
          <div style={{ width:280, flexShrink:0, position:'sticky', top:80 }}>
            <ToyAdVertical />
          </div>
        </div>
      </div>
    </section>
  );
}

window.LandingParts = { Quiz, Hub, PlatformCard, P };
