const { Pill } = window.CammusDesignSystem_2ef585;

/* THE RESULTS — real assets, attached as delivered. The queue on the left is
   now a tab list: Carousel (deck of cards, auto-plays while on screen),
   One-pager (full artwork, opens full-size), Reels (streamed video, 9:16),
   Lead magnet (PDF). The active row's lime dot is the single UI signal of
   this viewport. Heavy media (video, full-res one-pager) streams from the
   platform bucket; carousel slides are embedded local. */

const RESULTS_BUCKET = 'https://gavnsveoalgbtaukqpaw.supabase.co/storage/v1/object/public/landing-page/';
const RESULTS_N = 11;
const RESULTS_SLIDES = Array.from({ length: RESULTS_N }, (_, i) =>
  'assets/results/carousel-' + String(i + 1).padStart(2, '0') + '.jpg');
const MAGNET_N = 12;
const MAGNET_PAGES = Array.from({ length: MAGNET_N }, (_, i) =>
  RESULTS_BUCKET + 'ISCA%20DIGITAL%20(LEAD%20MAGNET)/jpeg/page-' + String(i + 1).padStart(2, '0') + '.jpg');

function QueueGlyph({ kind, size }) {
  const S = 'var(--cam-text-auxiliary)';
  const common = { fill: 'none', stroke: S, strokeWidth: 1.5, strokeLinecap: 'round' };
  return (
    <svg aria-hidden="true" width={size || 24} height={size || 24} viewBox="0 0 24 24" style={{ display: 'block', flex: 'none' }}>
      {kind === 'carousel' && <g {...common}>
        <path d="M8.5 6 V5 a1.5 1.5 0 0 1 1.5 -1.5 h9 a1.5 1.5 0 0 1 1.5 1.5 v9 a1.5 1.5 0 0 1 -1.5 1.5 h-1" />
        <rect x="3.5" y="7.5" width="13" height="13" rx="1.5" />
      </g>}
      {kind === 'onepager' && <g {...common}>
        <rect x="6" y="3" width="12" height="18" rx="1.5" />
        <line x1="9" y1="7.5" x2="15" y2="7.5" />
        <line x1="9" y1="11" x2="15" y2="11" />
        <line x1="9" y1="14.5" x2="12.5" y2="14.5" />
      </g>}
      {kind === 'reels' && <g>
        <rect x="3.5" y="4.5" width="17" height="15" rx="2.5" fill="none" stroke={S} strokeWidth="1.5" />
        <polygon points="10.5,9 15,12 10.5,15" fill={S} />
      </g>}
      {kind === 'magnet' && <g {...common}>
        <line x1="12" y1="3.5" x2="12" y2="12.5" />
        <polyline points="8.5,9.5 12,13 15.5,9.5" />
        <polyline points="4,15.5 4,19.5 20,19.5 20,15.5" />
      </g>}
    </svg>
  );
}

function DeckArrow({ dir, onClick, label }) {
  return (
    <button type="button" onClick={onClick} aria-label={label} style={{
      width: 38, height: 38, borderRadius: '50%', cursor: 'pointer',
      background: 'transparent', border: '1px solid var(--cam-border-strong)',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', padding: 0,
    }}>
      <span style={{
        width: 0, height: 0, borderTop: '5px solid transparent', borderBottom: '5px solid transparent',
        borderLeft: dir === 'next' ? '7px solid var(--cam-text-secondary)' : 'none',
        borderRight: dir === 'prev' ? '7px solid var(--cam-text-secondary)' : 'none',
        marginLeft: dir === 'next' ? 3 : -3,
      }} />
    </button>
  );
}

function ResultsShowcase() {
  const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  const deckRef = React.useRef(null);
  const [tab, setTab] = React.useState('carousel');
  const [cur, setCur] = React.useState(0);
  const [hover, setHover] = React.useState(false);
  const [inView, setInView] = React.useState(false);
  const [mPage, setMPage] = React.useState(0);

  React.useEffect(() => {
    const el = deckRef.current;
    if (!el) return;
    const io = new IntersectionObserver((es) => setInView(es[0].isIntersecting), { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  React.useEffect(() => {
    if (!inView || hover || reduce || tab !== 'carousel') return;
    const t = setInterval(() => setCur((c) => (c + 1) % RESULTS_N), 3000);
    return () => clearInterval(t);
  }, [inView, hover, tab]);

  const next = () => setCur((c) => (c + 1) % RESULTS_N);
  const prev = () => setCur((c) => (c - 1 + RESULTS_N) % RESULTS_N);
  const mNext = () => setMPage((c) => (c + 1) % MAGNET_N);
  const mPrev = () => setMPage((c) => (c - 1 + MAGNET_N) % MAGNET_N);

  /* Position in the deck relative to the front card */
  const styleFor = (k) => {
    const base = { transition: 'transform .65s cubic-bezier(.3, .7, .3, 1), opacity .5s ease' };
    if (k === 0) return { ...base, transform: 'none', opacity: 1, zIndex: 5 };
    if (k === 1) return { ...base, transform: 'translate(3.5%, 2.6%) rotate(2.2deg) scale(.975)', opacity: .85, zIndex: 4 };
    if (k === 2) return { ...base, transform: 'translate(7%, 5.2%) rotate(4.4deg) scale(.95)', opacity: .5, zIndex: 3 };
    if (k === RESULTS_N - 1) return { ...base, transition: 'transform .55s cubic-bezier(.3, .7, .3, 1), opacity .32s ease', transform: 'translate(-15%, -2%) rotate(-5deg)', opacity: 0, zIndex: 6 }; /* the card that just swiped away — stays inside the deck footprint */
    return { ...base, transform: 'translate(7%, 5.2%) rotate(4.4deg) scale(.95)', opacity: 0, zIndex: 1 };
  };

  const queue = [
    { k: 'carousel', name: 'Carousel', meta: 'Instagram · 11 slides' },
    { k: 'onepager', name: 'One-pager', meta: 'LinkedIn' },
    { k: 'reels', name: 'Reels', meta: 'Instagram · video' },
    { k: 'magnet', name: 'Lead magnet', meta: 'Capture · PDF' },
  ];
  const linkStyle = {
    color: 'var(--cam-text-secondary)', fontWeight: 'var(--fw-semibold)',
    fontSize: 'var(--fs-small)', letterSpacing: 'var(--track-text)',
    textDecoration: 'none', borderBottom: '1px solid var(--cam-border-strong)', paddingBottom: 2,
  };

  return (
    <div id="results" data-screen-label="The Results" style={{ marginTop: 'var(--beat-gap)' }}>
      <div className="lp-reveal">
        <div style={{
          color: 'var(--cam-text-inactive)', fontSize: 'var(--fs-eyebrow)',
          fontWeight: 'var(--fw-semibold)', textTransform: 'uppercase',
          letterSpacing: 'var(--track-eyebrow)', marginBottom: 'var(--space-4)',
        }}>The Results</div>
        <h3 style={{
          margin: 0, fontSize: 'var(--fs-h2)', fontWeight: 'var(--fw-black)',
          letterSpacing: 'var(--track-display)', lineHeight: 'var(--lh-snug)',
          color: 'var(--cam-text-primary)',
        }}>Shipped from a single input.</h3>
        <p style={{
          margin: 'var(--space-4) 0 0', fontSize: 'var(--fs-lead)',
          color: 'var(--cam-text-secondary)', letterSpacing: 'var(--track-text)',
          lineHeight: 1.5, maxWidth: '58ch',
        }}>Real assets produced inside the platform, attached exactly as delivered.</p>
      </div>

      <div className="lp-results">
        {/* Format tabs */}
        <div className="lp-group" role="tablist" aria-label="Delivered formats">
          {queue.map((q, i) => {
            const active = tab === q.k;
            return (
              <button key={q.k} type="button" role="tab" aria-selected={active} onClick={() => setTab(q.k)} className="lp-item" style={{
                '--d': (i * 0.1) + 's',
                display: 'flex', alignItems: 'center', gap: 'var(--space-4)',
                padding: 'var(--space-5) 0', width: '100%', textAlign: 'left',
                background: 'transparent', border: 'none', cursor: 'pointer',
                borderTop: '1px solid var(--cam-border-subtle)',
                borderBottom: i === queue.length - 1 ? '1px solid var(--cam-border-subtle)' : 'none',
                fontFamily: 'inherit',
              }}>
                <QueueGlyph kind={q.k} />
                <span style={{ display: 'flex', flexDirection: 'column', gap: 3, minWidth: 0, flex: 1 }}>
                  <span style={{
                    color: active ? 'var(--cam-text-primary)' : 'var(--cam-text-auxiliary)',
                    fontWeight: 'var(--fw-semibold)', fontSize: '1rem', letterSpacing: 'var(--track-text)',
                    transition: 'color .25s ease',
                  }}>{q.name}</span>
                  <span style={{
                    color: 'var(--cam-text-inactive)', fontSize: '10px', fontWeight: 'var(--fw-semibold)',
                    textTransform: 'uppercase', letterSpacing: 'var(--track-eyebrow)',
                  }}>{q.meta}</span>
                </span>
                {active ? (
                  <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--cam-accent-lime)', display: 'inline-block', flex: 'none' }} />
                ) : (
                  <span aria-hidden="true" style={{
                    width: 0, height: 0, borderTop: '4px solid transparent', borderBottom: '4px solid transparent',
                    borderLeft: '6px solid var(--cam-border-strong)', display: 'inline-block', flex: 'none',
                  }} />
                )}
              </button>
            );
          })}
          <p style={{
            margin: 'var(--space-5) 0 0', fontFamily: 'var(--font-serif)', fontStyle: 'italic',
            fontSize: 'var(--fs-lead)', color: 'var(--cam-text-secondary)', lineHeight: 1.4,
          }}>The consistency of a system, not the talent of a single piece.</p>
        </div>

        {/* Viewer */}
        <div className="lp-reveal">
          {tab === 'carousel' && (
            <React.Fragment>
              <div ref={deckRef} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} onClick={next}
                role="group" aria-label={'Instagram carousel, slide ' + (cur + 1) + ' of ' + RESULTS_N}
                style={{ position: 'relative', aspectRatio: '4 / 5', cursor: 'pointer', margin: '0 26px 0 0' }}>
                {RESULTS_SLIDES.map((src, i) => {
                  const k = (i - cur + RESULTS_N) % RESULTS_N;
                  return (
                    <div key={src} aria-hidden={k !== 0} style={{
                      position: 'absolute', inset: 0, borderRadius: 'var(--radius-card)',
                      overflow: 'hidden', border: '1px solid var(--cam-border-strong)',
                      background: 'var(--cam-surface-card)', ...styleFor(k),
                    }}>
                      <img src={src} alt={'Carousel slide ' + (i + 1) + ', produced by Cammus'} draggable={false}
                        style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                    </div>
                  );
                })}
              </div>
              <div style={{ marginTop: 'var(--space-6)', display: 'flex', alignItems: 'center', gap: 'var(--space-4)' }}>
                <Pill style={{ background: 'var(--cam-surface-section)' }}>Real output</Pill>
                <span style={{ flex: 1 }} />
                <DeckArrow dir="prev" onClick={(e) => { e.stopPropagation(); prev(); }} label="Previous slide" />
                <span style={{
                  color: 'var(--cam-text-auxiliary)', fontSize: 'var(--fs-small)',
                  fontVariantNumeric: 'tabular-nums', letterSpacing: 'var(--track-text)', minWidth: 52, textAlign: 'center',
                }}>{String(cur + 1).padStart(2, '0')} / {RESULTS_N}</span>
                <DeckArrow dir="next" onClick={(e) => { e.stopPropagation(); next(); }} label="Next slide" />
              </div>
            </React.Fragment>
          )}

          {tab === 'onepager' && (
            <React.Fragment>
              <div style={{
                position: 'relative', aspectRatio: '4 / 5', borderRadius: 'var(--radius-card)',
                overflow: 'hidden', border: '1px solid var(--cam-border-strong)', background: 'var(--cam-surface-card)',
              }}>
                <img src="assets/results/one-pager.jpg" alt="One-pager produced by Cammus" draggable={false}
                  style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
              </div>
              <div style={{ marginTop: 'var(--space-6)', display: 'flex', alignItems: 'center', gap: 'var(--space-4)' }}>
                <Pill style={{ background: 'var(--cam-surface-section)' }}>Real output</Pill>
                <span style={{ flex: 1 }} />
                <a href={RESULTS_BUCKET + 'ONE%20PAGER/one-pager.png'} target="_blank" rel="noreferrer" style={linkStyle}>Open full size</a>
              </div>
            </React.Fragment>
          )}

          {tab === 'reels' && (
            <React.Fragment>
              <div style={{ display: 'flex', justifyContent: 'center' }}>
                <video controls playsInline preload="metadata"
                  src={RESULTS_BUCKET + 'REELS/definitivo%20-%20teste.mp4'}
                  style={{
                    height: 'min(72vh, 560px)', aspectRatio: '9 / 16', maxWidth: '100%',
                    borderRadius: 'var(--radius-card)', border: '1px solid var(--cam-border-strong)',
                    background: '#000', display: 'block',
                  }} />
              </div>
              <div style={{ marginTop: 'var(--space-6)', display: 'flex', alignItems: 'center', gap: 'var(--space-4)', justifyContent: 'center' }}>
                <Pill style={{ background: 'var(--cam-surface-section)' }}>Real output</Pill>
                <span style={{ color: 'var(--cam-text-inactive)', fontSize: 'var(--fs-small)', letterSpacing: 'var(--track-text)' }}>Reels · streamed from the platform</span>
              </div>
            </React.Fragment>
          )}

          {tab === 'magnet' && (
            <React.Fragment>
              <div onClick={mNext} role="group" aria-label={'Lead magnet, page ' + (mPage + 1) + ' of ' + MAGNET_N} style={{
                position: 'relative', aspectRatio: '210 / 297', cursor: 'pointer',
                borderRadius: 'var(--radius-card)', overflow: 'hidden',
                border: '1px solid var(--cam-border-strong)', background: 'var(--cam-surface-card)',
              }}>
                {MAGNET_PAGES.map((src, i) => (
                  <img key={src} src={src} alt={'Lead magnet page ' + (i + 1) + ', produced by Cammus'} draggable={false}
                    loading={i === 0 ? 'eager' : 'lazy'} aria-hidden={i !== mPage} style={{
                      position: 'absolute', inset: 0, width: '100%', height: '100%',
                      objectFit: 'cover', display: 'block',
                      opacity: i === mPage ? 1 : 0, transition: 'opacity .3s ease',
                    }} />
                ))}
              </div>
              <div style={{ marginTop: 'var(--space-6)', display: 'flex', alignItems: 'center', gap: 'var(--space-4)' }}>
                <Pill style={{ background: 'var(--cam-surface-section)' }}>Real output</Pill>
                <a href={RESULTS_BUCKET + 'ISCA%20DIGITAL%20(LEAD%20MAGNET)/lead-magnet.pdf'} target="_blank" rel="noreferrer" style={linkStyle}>Open the PDF</a>
                <span style={{ flex: 1 }} />
                <DeckArrow dir="prev" onClick={(e) => { e.stopPropagation(); mPrev(); }} label="Previous page" />
                <span style={{
                  color: 'var(--cam-text-auxiliary)', fontSize: 'var(--fs-small)',
                  fontVariantNumeric: 'tabular-nums', letterSpacing: 'var(--track-text)', minWidth: 52, textAlign: 'center',
                }}>{String(mPage + 1).padStart(2, '0')} / {MAGNET_N}</span>
                <DeckArrow dir="next" onClick={(e) => { e.stopPropagation(); mNext(); }} label="Next page" />
              </div>
            </React.Fragment>
          )}
        </div>
      </div>
    </div>
  );
}
window.ResultsShowcase = ResultsShowcase;
