/* global React, Button, Chip, Stamp, Reveal, Sticker */
const { useState, useEffect, useRef } = React;

/* ============================================================
   Before/After slider — uses two image-slot elements masked
   ============================================================ */
function BeforeAfterSlider({ idA = 'ba-before', idB = 'ba-after', label = 'Week 1 → Week 4' }) {
  const [pct, setPct] = useState(50);
  const wrapRef = useRef(null);
  const dragging = useRef(false);
  useEffect(() => {
    function move(e) {
      if (!dragging.current) return;
      const el = wrapRef.current; if (!el) return;
      const r = el.getBoundingClientRect();
      const x = (e.touches ? e.touches[0].clientX : e.clientX) - r.left;
      setPct(Math.max(2, Math.min(98, (x / r.width) * 100)));
    }
    function up() { dragging.current = false; }
    window.addEventListener('mousemove', move);
    window.addEventListener('touchmove', move, { passive:true });
    window.addEventListener('mouseup', up);
    window.addEventListener('touchend', up);
    return () => {
      window.removeEventListener('mousemove', move);
      window.removeEventListener('touchmove', move);
      window.removeEventListener('mouseup', up);
      window.removeEventListener('touchend', up);
    };
  }, []);
  return (
    <div ref={wrapRef} style={{
      position:'relative', width:'100%', aspectRatio:'4/3',
      border:'5px solid var(--tbb-ink)', borderRadius:32,
      boxShadow:'10px 10px 0 0 var(--tbb-ink)',
      overflow:'hidden', background:'var(--tbb-paper)',
      userSelect:'none',
    }}>
      <div style={{ position:'absolute', inset:0 }}>
        <image-slot id={idA} shape="rect" style={{ display:'block', width:'100%', height:'100%' }} placeholder="Drop the BEFORE pic"></image-slot>
      </div>
      <div style={{ position:'absolute', inset:0, clipPath:`inset(0 0 0 ${pct}%)` }}>
        <image-slot id={idB} shape="rect" style={{ display:'block', width:'100%', height:'100%' }} placeholder="Drop the AFTER pic"></image-slot>
      </div>
      <div style={{ position:'absolute', top:14, left:14, zIndex:3 }}>
        <Stamp tone="ink" rot={-4} style={{ background:'var(--tbb-ink)', color:'var(--tbb-paper)' }}>Before</Stamp>
      </div>
      <div style={{ position:'absolute', top:14, right:14, zIndex:3 }}>
        <Stamp tone="pink" rot={4}>After ♡</Stamp>
      </div>
      <div className="tbb-ba-handle" style={{ left: `${pct}%` }} />
      <div className="tbb-ba-knob"
           style={{ left:`${pct}%` }}
           onMouseDown={()=>{dragging.current=true;}}
           onTouchStart={()=>{dragging.current=true;}}>
        ↔
      </div>
      <div style={{ position:'absolute', bottom:14, left:'50%', transform:'translateX(-50%)' }}>
        <Stamp tone="butter" rot={-3}>{label}</Stamp>
      </div>
    </div>
  );
}

function BeforeAfterSection() {
  const pairs = [
    { idA:'ba3-before', idB:'ba3-after', label:'Client 01' },
    { idA:'ba2-before', idB:'ba2-after', label:'Client 02' },
  ];
  const [i, setI] = useState(0);
  const p = pairs[i];
  return (
    <section id="beforeafter" style={{
      padding:'80px 48px', background:'var(--tbb-bubblegum)',
      borderTop:'3px solid var(--tbb-ink)', borderBottom:'3px solid var(--tbb-ink)',
      position:'relative', overflow:'hidden',
    }}>
      <div className="tbb-halftone" style={{ position:'absolute', inset:0, pointerEvents:'none', opacity:0.5 }} />
      <div style={{ position:'relative', maxWidth:1200, margin:'0 auto' }}>
        <div style={{ textAlign:'center', marginBottom:36 }}>
          <Chip tone="ink" rot={-2} sticker>The Korean lash lift glow up</Chip>
          <h2 style={{ fontFamily:'Olivita, system-ui', fontStyle:'italic', fontSize:'clamp(36px, 5vw, 68px)', lineHeight:0.9, margin:'18px 0 8px' }}>
            One appointment. Eight weeks of lift.
          </h2>
          <div style={{ marginTop:12 }}>
            <Chip tone="pink" rot={-2} sticker>★ One of our most-booked services</Chip>
          </div>
          <p style={{ fontFamily:'Nunito', fontSize:17, fontWeight:500, color:'var(--fg2)', maxWidth:560, margin:'18px auto 0', lineHeight:1.55 }}>
            The <strong>Korean lash lift</strong> is a babe favorite — drag the slider through three real clients. Natural lashes curled and tinted in 60 minutes. No extensions, no daily mascara, just wake up like that.
          </p>
        </div>

        <Reveal>
          <BeforeAfterSlider key={p.idA} {...p} />
        </Reveal>

        <div style={{ display:'flex', justifyContent:'center', gap:10, marginTop:28, flexWrap:'wrap' }}>
          {pairs.map((pp, idx) => (
            <Button key={pp.idA} size="sm" variant={i===idx ? 'ink' : 'secondary'} onClick={()=>setI(idx)}>
              {pp.label}
            </Button>
          ))}
        </div>
        <div style={{ display:'flex', justifyContent:'center', marginTop:18 }}>
          <Button size="lg" as="a" href="https://www.vagaro.com/tokyobikinibar/services" target="_blank" rel="noreferrer">Book a Korean lash lift →</Button>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   Instagram-style feed — real posts, horizontally scrolling
   ============================================================ */
function IGReelTile({ src, poster }) {
  const [playing, setPlaying] = useState(false);
  return (
    <div style={{
      width:'100%', height:'100%',
      border:'3px solid var(--tbb-ink)', borderRadius:18,
      boxShadow:'5px 5px 0 0 var(--tbb-ink)',
      overflow:'hidden', position:'relative', background:'var(--tbb-ink)',
      cursor:'pointer',
    }} onClick={() => setPlaying((p) => !p)}>
      {playing ?
        <video
          src={src} poster={poster}
          autoPlay loop muted playsInline
          style={{ width:'100%', height:'100%', objectFit:'cover', objectPosition:'top', display:'block' }}
        /> :
        <img src={poster} alt="Reel preview" style={{ width:'100%', height:'100%', objectFit:'cover', objectPosition:'top', display:'block' }} />}

      <div style={{
        position:'absolute', top:10, right:10,
        background:'var(--tbb-ink)', color:'var(--tbb-paper)',
        padding:'4px 9px', borderRadius:999,
        fontFamily:'Nunito Sans', fontWeight:900, fontSize:10,
        letterSpacing:'0.1em', textTransform:'uppercase',
        border:'2px solid var(--tbb-paper)',
        display:'flex', alignItems:'center', gap:4,
      }}>▶ Reel</div>

      {!playing &&
      <div style={{
        position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center',
        pointerEvents:'none',
      }}>
        <div style={{
          width:56, height:56, borderRadius:999,
          background:'rgba(20,20,20,0.55)', border:'3px solid var(--tbb-paper)',
          display:'flex', alignItems:'center', justifyContent:'center',
        }}>
          <div style={{
            width:0, height:0, marginLeft:4,
            borderTop:'11px solid transparent', borderBottom:'11px solid transparent',
            borderLeft:'18px solid var(--tbb-paper)',
          }} />
        </div>
      </div>}
    </div>
  );
}

function IGFeed() {
  const tiles = [
    { type:'photo', src:'assets/feed/feed-1.jpg', alt:'Brow lamination client result', rot:-2, tall:false },
    { type:'photo', src:'assets/feed/feed-2.jpg', alt:'Lash lift client result', rot:1,  tall:false },
    { type:'reel',  src:'assets/feed/feed-reel.mp4', poster:'assets/feed/feed-reel-poster.jpg', alt:'Brow wax reel', rot:-1, tall:true },
    { type:'photo', src:'assets/feed/feed-3.jpg', alt:'Lash lift client result', rot:2,  tall:false },
    { type:'photo', src:'assets/feed/feed-4.jpg', alt:'Lash lift client result', rot:-2, tall:false },
    { type:'photo', src:'assets/feed/feed-5.jpg', alt:'Lash lift client result', rot:1,  tall:false },
    { type:'photo', src:'assets/feed/feed-6.jpg', alt:'Lash lift client result', rot:-1, tall:false },
  ];

  const loopTiles = [...tiles, ...tiles];

  const scrollRef = useRef(null);
  const pausedRef = useRef(false);
  const resumeTimer = useRef(null);

  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const SPEED = 36; // px / second
    let last = null;
    let raf;
    function tick(now) {
      if (last === null) last = now;
      const dt = now - last;
      last = now;
      if (!pausedRef.current && el.scrollWidth > 0) {
        const half = el.scrollWidth / 2;
        el.scrollLeft += SPEED * dt / 1000;
        if (el.scrollLeft >= half) el.scrollLeft -= half;
      }
      raf = requestAnimationFrame(tick);
    }
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  function pause() {
    pausedRef.current = true;
    if (resumeTimer.current) { clearTimeout(resumeTimer.current); resumeTimer.current = null; }
  }
  function resume(delay = 0) {
    if (resumeTimer.current) clearTimeout(resumeTimer.current);
    resumeTimer.current = setTimeout(() => { pausedRef.current = false; }, delay);
  }

  function scrollByAmount(dir) {
    const el = scrollRef.current; if (!el) return;
    pause();
    el.scrollBy({ left: dir * Math.min(340, el.clientWidth * 0.8), behavior: 'smooth' });
    resume(2000);
  }

  return (
    <section id="lookbook" style={{
      padding:'80px 0', background:'var(--tbb-paper)', position:'relative', overflow:'hidden',
    }}>
      <div style={{ maxWidth:1400, margin:'0 auto', padding:'0 48px' }}>
        <div style={{ display:'flex', alignItems:'flex-end', justifyContent:'space-between', marginBottom:36, flexWrap:'wrap', gap:16 }}>
          <div>
            <Chip tone="pink" rot={-3} sticker>The lookbook</Chip>
            <h2 style={{ fontFamily:'Olivita, system-ui', fontStyle:'italic', fontSize:'clamp(36px, 5vw, 68px)', lineHeight:0.9, margin:'18px 0 4px' }}>
              From the @feed.
            </h2>
            <div style={{ fontFamily:'Nunito Sans', fontWeight:800, fontSize:14, letterSpacing:'0.14em', textTransform:'uppercase', color:'var(--fg2)' }}>
              @tokyobikinibar · photos &amp; reels
            </div>
          </div>
          <div style={{ display:'flex', alignItems:'center', gap:12 }}>
            <button aria-label="Scroll left" onClick={() => scrollByAmount(-1)} style={{
              width:48, height:48, borderRadius:999, cursor:'pointer',
              background:'var(--tbb-paper)', border:'3px solid var(--tbb-ink)',
              boxShadow:'4px 4px 0 0 var(--tbb-ink)',
              fontFamily:'Nunito Sans', fontWeight:900, fontSize:18, lineHeight:1,
            }}>←</button>
            <button aria-label="Scroll right" onClick={() => scrollByAmount(1)} style={{
              width:48, height:48, borderRadius:999, cursor:'pointer',
              background:'var(--tbb-paper)', border:'3px solid var(--tbb-ink)',
              boxShadow:'4px 4px 0 0 var(--tbb-ink)',
              fontFamily:'Nunito Sans', fontWeight:900, fontSize:18, lineHeight:1,
            }}>→</button>
            <Button variant="primary" size="lg" as="a" href="https://www.instagram.com/tokyobikinibar/" target="_blank" rel="noreferrer">Follow on IG →</Button>
          </div>
        </div>
      </div>

      <div ref={scrollRef} className="tbb-ig-scroll"
        onMouseEnter={pause} onMouseLeave={() => resume(0)}
        onTouchStart={pause} onTouchEnd={() => resume(1500)}
        style={{
          display:'flex', alignItems:'center', gap:22,
          overflowX:'auto',
          padding:'12px 48px 28px',
        }}>
        {loopTiles.map((t, i) => (
          <Reveal key={`${t.src}-${i}`} delay={(i % tiles.length)*50} style={{ flex:'0 0 auto' }}>
            <div className="tbb-ig-card">
              <div style={{ position:'relative', transform:`rotate(${t.rot}deg)` }}>
                <div style={{ width:'100%', aspectRatio: t.tall ? '9/16' : '4/5' }}>
                  {t.type === 'reel' ?
                    <IGReelTile src={t.src} poster={t.poster} /> :
                    <div style={{
                      width:'100%', height:'100%',
                      border:'3px solid var(--tbb-ink)', borderRadius:18,
                      boxShadow:'5px 5px 0 0 var(--tbb-ink)', overflow:'hidden',
                    }}>
                      <img src={t.src} alt={t.alt} loading="lazy" style={{ width:'100%', height:'100%', objectFit:'cover', display:'block' }} />
                    </div>}
                </div>
              </div>
            </div>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

/* ============================================================
   Testimonials carousel
   ============================================================ */
const TESTIMONIALS = [
  { name:'Verified client', loc:'Vagaro review', text:"Leia is super friendly and made me feel comfortable right away. My bikini wax was done so quickly and was painless. Great service!!", tone:'lime', rot:-2 },
  { name:'Verified client', loc:'Vagaro review', text:"Very very satisfied with my service! Quick and definitely less painful than other waxes I've had. Super efficient. Most importantly though, didn't irritate my very sensitive skin. Thank you!!", tone:'butter', rot:2 },
  { name:'Verified client', loc:'Vagaro review', text:"Super sweet, professional & she makes you feel like you've known her forever. It has been the fastest Brazilian I've ever gotten in my years of getting waxed — I was there exactly 15 min. I definitely recommend her if you're in the area or make that 30–40 min drive, worth it! & the price is even better!", tone:'sky', rot:-1 },
  { name:'Verified client', loc:'Vagaro review', text:"Leia was so awesome! She got me in and out and made the appt super comfortable!", tone:'pink', rot:1 },
  { name:'Verified client', loc:'Vagaro review', text:"She was amazing and it was my first time!!", tone:'bubble', rot:-2 },
];

function TestimonialCarousel() {
  const [i, setI] = useState(0);
  const t = TESTIMONIALS[i];
  const toneMap = {
    lime:'var(--tbb-lime)', pink:'var(--tbb-hotpink)', sky:'var(--tbb-sky)',
    butter:'var(--tbb-butter)', bubble:'var(--tbb-bubblegum)', coral:'var(--tbb-coral)',
  };
  const fgMap = {
    pink:'var(--tbb-paper)', coral:'var(--tbb-paper)',
  };
  return (
    <section id="testimonials" style={{
      padding:'80px 48px', background:'var(--tbb-ink)', color:'var(--tbb-paper)',
      borderTop:'3px solid var(--tbb-ink)', borderBottom:'3px solid var(--tbb-ink)',
      position:'relative', overflow:'hidden',
    }}>
      <div style={{
        position:'absolute', inset:0, pointerEvents:'none', opacity:0.10,
        backgroundImage:'radial-gradient(rgba(251,246,238,0.7) 1.4px, transparent 1.5px)',
        backgroundSize:'14px 14px',
      }} />
      <div className="tbb-testimonial-grid" style={{
        position:'relative', maxWidth:1300, margin:'0 auto',
        display:'grid', gridTemplateColumns:'0.9fr 1.1fr', gap:56, alignItems:'center',
      }}>
        {/* Left — copy */}
        <Reveal>
          <div>
            <Chip tone="pink" rot={-3} sticker>What the babes say</Chip>
            <h2 style={{ fontFamily:'Olivita, system-ui', fontStyle:'italic', fontSize:'clamp(36px, 4.4vw, 60px)', lineHeight:0.95, margin:'18px 0 16px', color:'var(--tbb-paper)' }}>
              130 five-star reviews.
            </h2>
            <p style={{ fontFamily:'Nunito', fontSize:17, fontWeight:500, lineHeight:1.6, color:'#D8D2C6', maxWidth:440, marginBottom:24 }}>
              Every single review on Vagaro is five stars — <strong style={{ color:'var(--tbb-paper)' }}>130 and counting</strong>. Real babes, real appointments, no fluff.
            </p>
            <div style={{ display:'flex', alignItems:'center', gap:16, flexWrap:'wrap', marginBottom:28 }}>
              <Sticker tone="paper" radius={22} style={{ padding:'16px 22px', display:'flex', alignItems:'center', gap:14 }}>
                <div style={{ fontFamily:'Olivita, system-ui', fontStyle:'italic', fontSize:34, color:'var(--tbb-ink)' }}>5.0</div>
                <div>
                  <div style={{ fontFamily:'Olivita, system-ui', fontStyle:'italic', fontSize:16, color:'var(--tbb-hotpink)' }}>★★★★★</div>
                  <div style={{ fontFamily:'Nunito Sans', fontWeight:800, fontSize:11, letterSpacing:'0.1em', textTransform:'uppercase', color:'var(--fg2)' }}>130+ Vagaro reviews</div>
                </div>
              </Sticker>
            </div>
            <Button variant="secondary" size="lg" as="a" href="https://www.vagaro.com/tokyobikinibar/services" target="_blank" rel="noreferrer">Read the reviews on Vagaro →</Button>
          </div>
        </Reveal>

        {/* Right — carousel */}
        <div style={{ position:'relative', minHeight:340 }}>
          {TESTIMONIALS.map((tm, idx) => (
            <div key={idx} style={{
              position: idx === i ? 'relative' : 'absolute',
              inset: 0,
              opacity: idx === i ? 1 : 0,
              transform: idx === i ? `rotate(${tm.rot}deg) scale(1)` : `rotate(${tm.rot}deg) scale(0.94)`,
              transition: 'opacity 400ms ease, transform 500ms var(--bounce)',
              pointerEvents: idx === i ? 'auto' : 'none',
            }}>
              <div style={{
                background: toneMap[tm.tone],
                color: fgMap[tm.tone] || 'var(--tbb-ink)',
                border:'3px solid var(--tbb-ink)',
                borderRadius:32,
                boxShadow:'10px 10px 0 0 var(--tbb-paper)',
                padding:'40px 44px',
              }}>
                <div style={{ fontFamily:'Olivita, system-ui', fontStyle:'italic', fontSize:'clamp(24px, 2.6vw, 34px)', lineHeight:1.15, marginBottom:24 }}>
                  "{tm.text}"
                </div>
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', flexWrap:'wrap', gap:14 }}>
                  <div>
                    <div style={{ fontFamily:'Nunito Sans', fontWeight:900, fontSize:16, letterSpacing:'0.06em', textTransform:'uppercase' }}>{tm.name}</div>
                    <div style={{ fontFamily:'Nunito', fontWeight:600, fontSize:14, opacity:0.75 }}>{tm.loc}</div>
                  </div>
                  <div style={{ fontFamily:'Olivita, system-ui', fontStyle:'italic', fontSize:28 }}>✦✦✦✦✦</div>
                </div>
              </div>
            </div>
          ))}

          {/* dots */}
          <div style={{ display:'flex', justifyContent:'center', gap:10, marginTop:32 }}>
            {TESTIMONIALS.map((_, idx) => (
              <button key={idx} onClick={()=>setI(idx)} style={{
                width: idx===i ? 36 : 14, height:14, borderRadius:999,
                border:'2.5px solid var(--tbb-paper)',
                background: idx===i ? 'var(--tbb-hotpink)' : 'transparent',
                cursor:'pointer', transition:'all 240ms var(--bounce)',
              }} aria-label={`Go to testimonial ${idx+1}`} />
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   Press feature — Bushbalm Esthetician of the Month
   ============================================================ */
function PressFeature() {
  return (
    <section id="press" style={{
      padding:'80px 48px', background:'var(--tbb-butter)',
      borderTop:'3px solid var(--tbb-ink)', borderBottom:'3px solid var(--tbb-ink)',
      position:'relative', overflow:'hidden',
    }}>
      <div className="tbb-press-grid" style={{
        position:'relative', maxWidth:1200, margin:'0 auto',
        display:'grid', gridTemplateColumns:'0.9fr 1.1fr', gap:56, alignItems:'center',
      }}>
        <Reveal>
          <div style={{
            background:'var(--tbb-paper)', border:'3px solid var(--tbb-ink)', borderRadius:28,
            boxShadow:'8px 8px 0 0 var(--tbb-ink)',
            padding:'44px 36px', display:'flex', alignItems:'center', justifyContent:'center',
            transform:'rotate(-2deg)',
          }}>
            <img src="assets/bushbalm-pro-logo.png" alt="Bushbalm Pro" style={{ width:'100%', maxWidth:320, height:'auto', display:'block' }} />
          </div>
        </Reveal>

        <Reveal delay={120}>
          <div>
            <Chip tone="ink" rot={-2} sticker>✦ Featured</Chip>
            <h2 style={{ fontFamily:'Olivita, system-ui', fontStyle:'italic', fontSize:'clamp(32px, 4vw, 52px)', lineHeight:0.95, margin:'18px 0 16px' }}>
              Esthetician of the Month.
            </h2>
            <p style={{ fontFamily:'Nunito', fontSize:17, fontWeight:500, lineHeight:1.6, color:'var(--fg2)', maxWidth:480, marginBottom:24 }}>
              Bushbalm named me their October Esthetician of the Month — spotlighting my story building Tokyo Bikini Bar and my approach to safe, empowering waxing appointments. So grateful for the feature ♡
            </p>
            <Button variant="ink" size="lg" as="a" href="https://pros.bushbalm.com/blogs/featured-esthetician/october-esthetician-of-the-month-2025" target="_blank" rel="noreferrer">Read the feature →</Button>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { BeforeAfterSection, IGFeed, TestimonialCarousel, PressFeature });
