/* global React, Sparkle, Icon */
const { useState, useRef, useEffect } = React;

const GALLERY_ITEMS = [
  { kind: 'image', label: 'Unhas decorativas',       src: 'assets/galeria-unhas-decorativas.jpg', position: '60% center' },
  { kind: 'image', label: 'Podologia',               src: 'assets/galeria-podologia.jpg' },
  { kind: 'beforeafter', label: 'Escova modeladora',
    before: 'assets/galeria-escova-antes.jpg',
    after:  'assets/galeria-escova-depois.jpg' },
  { kind: 'image', label: 'Depilação — pernas',      src: 'assets/galeria-depilacao-pernas.jpg' },
  { kind: 'image', label: 'Massagem relaxante',      src: 'assets/galeria-massagem.jpg' },
  { kind: 'image', label: 'Design de sobrancelhas',  src: 'assets/galeria-sobrancelhas.jpg' },
  { kind: 'image', label: 'Esmaltação em gel',       src: 'assets/galeria-esmaltacao-gel.jpg' },
  { kind: 'image', label: 'Depilação — buço',        src: 'assets/galeria-depilacao-buco.jpg' },
  { kind: 'image', label: 'Cabelo · finalização',    src: 'assets/galeria-escova.jpg' },
];

function Gallery() {
  const scroller = useRef(null);
  const [pos, setPos] = useState(0);
  const [paused, setPaused] = useState(false);

  const updatePos = () => {
    if (!scroller.current) return;
    const el = scroller.current;
    const max = el.scrollWidth - el.clientWidth;
    setPos(max > 0 ? el.scrollLeft / max : 0);
  };

  const scrollBy = (dir) => {
    if (!scroller.current) return;
    const el = scroller.current;
    const cardW = el.querySelector('article')?.offsetWidth || 320;
    el.scrollBy({ left: dir * (cardW + 16), behavior: 'smooth' });
  };

  // Auto-advance every 3s; pause on hover/touch
  useEffect(() => {
    if (paused) return;
    const id = setInterval(() => {
      const el = scroller.current;
      if (!el) return;
      const card = el.querySelector('article');
      const cardW = (card?.offsetWidth || 320) + 16;
      const maxScroll = el.scrollWidth - el.clientWidth;
      // If near the end, loop back to start
      if (el.scrollLeft + cardW >= maxScroll - 4) {
        el.scrollTo({ left: 0, behavior: 'smooth' });
      } else {
        el.scrollBy({ left: cardW, behavior: 'smooth' });
      }
    }, 3000);
    return () => clearInterval(id);
  }, [paused]);

  return (
    <section id="galeria" style={galStyles.section}>
      <div className="container">
        <div style={galStyles.head}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <span className="kicker">Galeria · Antes e depois</span>
            <h2 style={galStyles.title}>O resultado fala por si</h2>
            <p style={galStyles.lede}>Arraste o controle nas imagens para ver a transformação. Fotos reais de clientes Refinada.</p>
          </div>
          <div className="hide-mobile" style={galStyles.controls}>
            <button onClick={() => scrollBy(-1)} style={galStyles.arrow} aria-label="Anterior">
              <Icon name="arrowLeft" size={18}/>
            </button>
            <button onClick={() => scrollBy(1)} style={galStyles.arrow} aria-label="Próximo">
              <Icon name="arrowRight" size={18}/>
            </button>
          </div>
        </div>

        <div ref={scroller}
          onScroll={updatePos}
          onMouseEnter={() => setPaused(true)}
          onMouseLeave={() => setPaused(false)}
          onTouchStart={() => setPaused(true)}
          onTouchEnd={() => setPaused(false)}
          className="no-scrollbar" style={galStyles.carousel}>
          {GALLERY_ITEMS.map((item, i) => (
            item.kind === 'beforeafter'
              ? <BeforeAfterCard key={i} item={item} />
              : <SimpleCard key={i} item={item} />
          ))}
        </div>

        <div style={galStyles.progressTrack}>
          <span style={{ ...galStyles.progressBar, transform: `translateX(${pos * 240}px)` }}/>
        </div>

        <div style={galStyles.foot}>
          <a href="https://www.instagram.com/refinada_beauty" target="_blank" className="btn btn--secondary">
            <Icon name="instagram" size={16}/> Veja mais no Instagram
          </a>
        </div>
      </div>
    </section>
  );
}

function BeforeAfterCard({ item }) {
  const [pos, setPos] = useState(50);
  const wrap = useRef(null);
  const dragging = useRef(false);

  const update = (clientX) => {
    if (!wrap.current) return;
    const rect = wrap.current.getBoundingClientRect();
    const p = Math.max(0, Math.min(100, ((clientX - rect.left) / rect.width) * 100));
    setPos(p);
  };

  useEffect(() => {
    const onMove = (e) => {
      if (!dragging.current) return;
      const x = e.touches ? e.touches[0].clientX : e.clientX;
      update(x);
    };
    const onUp = () => { dragging.current = false; };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('touchmove', onMove, { passive: true });
    window.addEventListener('mouseup', onUp);
    window.addEventListener('touchend', onUp);
    return () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('touchmove', onMove);
      window.removeEventListener('mouseup', onUp);
      window.removeEventListener('touchend', onUp);
    };
  }, []);

  return (
    <article style={galStyles.card}>
      <div ref={wrap} style={galStyles.media}
        onMouseDown={(e) => { dragging.current = true; update(e.clientX); }}
        onTouchStart={(e) => { dragging.current = true; update(e.touches[0].clientX); }}>
        <img src={item.after} alt="Depois" style={galStyles.img}/>
        <div style={{ ...galStyles.beforeOver, clipPath: `inset(0 ${100 - pos}% 0 0)` }}>
          <img src={item.before} alt="Antes" style={galStyles.img}/>
        </div>
        <div style={{ ...galStyles.handle, left: `${pos}%` }}>
          <div style={galStyles.handleLine}/>
          <div style={galStyles.handleKnob}>
            <Icon name="arrowLeft" size={14}/>
            <Icon name="arrowRight" size={14}/>
          </div>
        </div>
        <span style={{ ...galStyles.chip, left: 14, background: 'rgba(43,27,18,0.7)', color: 'var(--rb-creme)' }}>Antes</span>
        <span style={{ ...galStyles.chip, right: 14, background: 'rgba(255,247,240,0.95)', color: 'var(--rb-espresso)' }}>Depois</span>
      </div>
      <div style={galStyles.cardFoot}>
        <span className="kicker" style={{ fontSize: 16 }}>Antes & depois</span>
        <span style={galStyles.cardTitle}>{item.label}</span>
      </div>
    </article>
  );
}

function SimpleCard({ item }) {
  return (
    <article style={galStyles.card}>
      <div style={{ ...galStyles.media, cursor: 'default' }}>
        <img src={item.src} alt={item.label} style={{ ...galStyles.img, ...(item.position ? { objectPosition: item.position } : {}) }}/>
      </div>
      <div style={galStyles.cardFoot}>
        <span className="kicker" style={{ fontSize: 16 }}>No salão</span>
        <span style={galStyles.cardTitle}>{item.label}</span>
      </div>
    </article>
  );
}

const galStyles = {
  section: { background: 'var(--bg-2)', padding: 'var(--section-pad) var(--page-pad)' },
  head: {
    display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
    gap: 24, marginBottom: 36, flexWrap: 'wrap',
  },
  title: { fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 'clamp(32px, 4.4vw, 52px)', lineHeight: 1.05, letterSpacing: '-0.01em', margin: 0, color: 'var(--fg-1)', maxWidth: 540 },
  lede: { fontFamily: 'var(--font-sans)', fontSize: 'clamp(14px, 1.3vw, 15px)', lineHeight: 1.65, color: 'var(--fg-2)', margin: 0, maxWidth: 480 },
  controls: { display: 'flex', gap: 10 },
  arrow: {
    width: 48, height: 48, borderRadius: 999,
    border: '1px solid var(--rb-champagne)',
    background: 'var(--rb-creme)',
    cursor: 'pointer', color: 'var(--rb-espresso)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    transition: 'all 220ms var(--ease-refined)',
  },
  carousel: {
    display: 'flex', gap: 16,
    overflowX: 'auto',
    scrollSnapType: 'x mandatory',
    paddingBottom: 8,
    /* Bleed slightly into page padding so the row visually extends to the edge */
    marginLeft: 'calc(var(--page-pad) * -1)',
    marginRight: 'calc(var(--page-pad) * -1)',
    paddingLeft: 'var(--page-pad)',
    paddingRight: 'var(--page-pad)',
  },
  progressTrack: {
    height: 2, width: 240, maxWidth: '100%', background: 'var(--rb-champagne)', borderRadius: 999,
    marginTop: 24, position: 'relative', overflow: 'hidden',
  },
  progressBar: {
    position: 'absolute', left: 0, top: 0, bottom: 0, width: 60, background: 'var(--rb-rose)', borderRadius: 999,
    transition: 'transform 220ms var(--ease-refined)',
  },
  card: {
    flex: '0 0 clamp(280px, 36vw, 380px)',
    scrollSnapAlign: 'start',
    display: 'flex', flexDirection: 'column', gap: 12,
    background: 'var(--rb-creme)', borderRadius: 14, overflow: 'hidden',
    border: '1px solid var(--rb-champagne)',
  },
  media: {
    position: 'relative', aspectRatio: '4 / 5',
    cursor: 'ew-resize', userSelect: 'none', overflow: 'hidden',
  },
  img: { width: '100%', height: '100%', objectFit: 'cover', display: 'block', pointerEvents: 'none' },
  beforeOver: { position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none' },
  handle: {
    position: 'absolute', top: 0, bottom: 0, width: 2,
    background: 'var(--rb-creme)', transform: 'translateX(-1px)',
    boxShadow: '0 0 0 1px rgba(43,27,18,0.15), 0 0 12px rgba(255,247,240,0.4)',
    pointerEvents: 'none',
  },
  handleLine: { display: 'none' },
  handleKnob: {
    position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)',
    width: 44, height: 44, borderRadius: 999, background: 'var(--rb-creme)',
    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 0,
    color: 'var(--rb-espresso)', boxShadow: '0 4px 14px rgba(43,27,18,0.25)',
  },
  chip: {
    position: 'absolute', top: 14,
    fontFamily: 'var(--font-sans)', fontSize: 10, fontWeight: 600,
    letterSpacing: '0.2em', textTransform: 'uppercase',
    padding: '6px 12px', borderRadius: 999,
  },
  cardFoot: { padding: '14px 20px 18px', display: 'flex', flexDirection: 'column', gap: 2 },
  cardTitle: { fontFamily: 'var(--font-display)', fontSize: 18, color: 'var(--fg-1)' },
  foot: { display: 'flex', justifyContent: 'center', marginTop: 40 },
};

Object.assign(window, { Gallery });
