/* global React */
/* Spec-Ring Case Study v2 — "Year in Review" timeline scrubber.

   A 4-milestone horizontal timeline drives a single hero stage:
   - Left: a leaderboard that animates Spec-Ring's row overtaking competitors
   - Right: a "revenue receipt" that prints longer with each milestone
   - Bottom: a quote/highlight tied to that moment in time
*/

const { useEffect, useState, useRef, useMemo } = React;

const MILESTONES = [
  {
    key: 'dec24', label: 'Dec 2024', short: 'Dec ’24',
    rank: 38,
    revenueIndex: 1.0,
    revenueLabel: '1.0×',
    headline: 'Buried on page 4.',
    quote: 'Spec-Ring is averaging position 38 — invisible to anyone outside the brand-name search.',
    chips: ['38th avg position', 'Page 4 of Google', 'Brand-only traffic'],
  },
  {
    key: 'mar25', label: 'Mar 2025', short: 'Mar ’25',
    rank: 22,
    revenueIndex: 1.6,
    revenueLabel: '1.6×',
    headline: 'Foundations rebuilt.',
    quote: 'New site speed, restructured ad spend, schema cleanup. Climbing fast.',
    chips: ['22nd avg position', 'Page 3 → Page 2', 'CWV: passing'],
  },
  {
    key: 'aug25', label: 'Aug 2025', short: 'Aug ’25',
    rank: 12,
    revenueIndex: 2.7,
    revenueLabel: '2.7×',
    headline: 'Climbing the front page.',
    quote: 'Email engine live. Paid spend tightening. Compounding revenue.',
    chips: ['12th avg position', 'Page 1 entered', '+170% YoY'],
  },
  {
    key: 'dec25', label: 'Dec 2025', short: 'Dec ’25',
    rank: 6,
    revenueIndex: 3.88,
    revenueLabel: '3.9×',
    headline: 'Front row, nearly 4× the sales.',
    quote: 'Spec-Ring is ranking 6th on average — and outperforming 2024 by 288%.',
    chips: ['6th avg position', 'Top of page 1', '+288% YoY'],
  },
];

// Competitor leaderboard rows (visual flavor — only the 6 visible at the end matter for accuracy)
const COMPETITORS = [
  { id: 'a', name: 'Auto Parts Hub' },
  { id: 'b', name: 'Wheelmart' },
  { id: 'c', name: 'PartFinder' },
  { id: 'd', name: 'Garage Direct' },
  { id: 'e', name: 'Mech Supply' },
  { id: 'f', name: 'OEMShop' },
  { id: 'g', name: 'TorqueZone' },
  { id: 'h', name: 'PistonPro' },
];

const easeOut = (t) => 1 - Math.pow(1 - t, 3);

function useInView(ref, threshold = 0.25) {
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } });
    }, { threshold });
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return seen;
}

// Smoothly tween a numeric value between milestone steps so charts feel alive.
function useSmoothValue(target, duration = 800) {
  const [val, setVal] = useState(target);
  const fromRef = useRef(target);
  const startRef = useRef(0);
  const targetRef = useRef(target);
  useEffect(() => {
    fromRef.current = val;
    targetRef.current = target;
    startRef.current = performance.now();
    let raf;
    const tick = (now) => {
      const t = Math.min(1, (now - startRef.current) / duration);
      const eased = easeOut(t);
      setVal(fromRef.current + (targetRef.current - fromRef.current) * eased);
      if (t < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target]);
  return val;
}

// ─── Leaderboard panel ─────────────────────────────────────────────
function Leaderboard({ rank }) {
  const smoothRank = useSmoothValue(rank, 1100);
  const live = Math.round(smoothRank);

  // Build the visible window: rows around current rank.
  // Show ranks 1–10 always; if current rank > 10, show a clipped indicator.
  const visibleCount = 8;
  const windowTop = live <= 10 ? 1 : Math.max(1, live - 3);
  const rows = [];
  for (let r = windowTop; r < windowTop + visibleCount; r++) {
    rows.push(r);
  }
  // Make sure rank 1 is always visible if window doesn't include it
  const includesUs = rows.includes(live);

  return (
    <div className="cs2-board">
      <div className="cs2-board-head">
        <span className="cs2-board-eyebrow">Google · "automotive parts"</span>
        <span className="cs2-board-rank">
          <span className="num">{live}</span>
          <span className="suf">{live === 1 ? 'st' : live === 2 ? 'nd' : live === 3 ? 'rd' : 'th'}</span>
        </span>
      </div>
      <ul className="cs2-board-list">
        {rows.map((r, i) => {
          const isUs = r === live;
          const competitor = COMPETITORS[(r - 1) % COMPETITORS.length];
          return (
            <li
              key={`${r}-${i}`}
              className={isUs ? 'cs2-board-row is-us' : 'cs2-board-row'}
              style={{ '--row-i': i }}
            >
              <span className="cs2-board-pos">
                {r}
                <span className="suf">{r === 1 ? 'st' : r === 2 ? 'nd' : r === 3 ? 'rd' : 'th'}</span>
              </span>
              <span className="cs2-board-fav" style={{ background: isUs ? null : `linear-gradient(135deg, hsl(${(r * 47) % 360}, 35%, 55%), hsl(${(r * 47 + 60) % 360}, 35%, 35%))` }}>
                {isUs ? (
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l2.4 7.4H22l-6.2 4.5L18 21l-6-4.5L6 21l2.2-7.1L2 9.4h7.6z"/></svg>
                ) : null}
              </span>
              <span className="cs2-board-name">
                {isUs ? <strong>Spec-Ring</strong> : competitor.name}
                <span className="cs2-board-url">
                  {isUs ? 'specring.com' : `${competitor.id}site.com`}
                </span>
              </span>
              <span className="cs2-board-bar">
                <span className="fill" style={{ width: `${Math.max(8, 100 - (r - 1) * 8)}%` }} />
              </span>
            </li>
          );
        })}
      </ul>
      {!includesUs && (
        <div className="cs2-board-overflow">
          <span className="dots">···</span>
          <span>position {live} · page {Math.ceil(live / 10)}</span>
        </div>
      )}
    </div>
  );
}

// ─── Receipt panel ───────────────────────────────────────────────
function Receipt({ idx, milestone }) {
  const smoothMult = useSmoothValue(milestone.revenueIndex, 900);

  // The receipt has line items added per milestone — earlier states show fewer lines.
  const allLines = [
    // dec24 baseline
    { label: 'Brand-name traffic',     amount: 28.4 },
    { label: 'Direct & referral',      amount: 22.1 },
    { label: 'Existing campaigns',     amount: 38.5 },
    // mar25 adds
    { label: 'Site speed lift',        amount: 18.0, milestone: 1 },
    { label: 'New SEO clusters',       amount: 14.6, milestone: 1 },
    // aug25 adds
    { label: 'Email automation',       amount: 38.2, milestone: 2 },
    { label: 'Refined paid funnels',   amount: 47.0, milestone: 2 },
    { label: 'Cart recovery',          amount: 12.4, milestone: 2 },
    // dec25 adds
    { label: 'Authority backlinks',    amount: 36.5, milestone: 3 },
    { label: 'Loyalty + win-back',     amount: 28.2, milestone: 3 },
    { label: 'Black Friday surge',     amount: 56.1, milestone: 3 },
  ];
  const visible = allLines.filter((l) => (l.milestone ?? 0) <= idx);
  const total = visible.reduce((s, l) => s + l.amount, 0);

  return (
    <div className="cs2-receipt">
      <div className="cs2-receipt-tape">
        <div className="cs2-receipt-edge top" />
        <div className="cs2-receipt-body">
          <div className="cs2-receipt-head">
            <span className="logo">SPEC-RING</span>
            <span className="addr">Annual Revenue · Indexed</span>
            <span className="when">{milestone.label}</span>
          </div>
          <div className="cs2-receipt-divider" />
          <ul className="cs2-receipt-lines">
            {visible.map((l, i) => (
              <li key={`${l.label}-${i}`} className="cs2-receipt-line" style={{ '--i': i }}>
                <span className="label">{l.label}</span>
                <span className="dots">{'.'.repeat(40)}</span>
                <span className="val">${l.amount.toFixed(1)}K</span>
              </li>
            ))}
          </ul>
          <div className="cs2-receipt-divider" />
          <div className="cs2-receipt-total">
            <span className="label">YOY MULTIPLIER</span>
            <span className="val">
              <span className="num">{smoothMult.toFixed(1)}</span>
              <span className="x">×</span>
            </span>
          </div>
          <div className="cs2-receipt-meta">
            <span>thank you for choosing</span>
            <span>spec-ring.com</span>
          </div>
        </div>
        <div className="cs2-receipt-edge bottom" />
      </div>
    </div>
  );
}

// ─── Main component ─────────────────────────────────────────────
function SpecRingCase() {
  const ref = useRef(null);
  const seen = useInView(ref);
  const [idx, setIdx] = useState(0);
  const [autoPlaying, setAutoPlaying] = useState(true);
  const userTouchedRef = useRef(false);

  // Autoplay until user interacts; once seen, advance every ~3.4s
  useEffect(() => {
    if (!seen || !autoPlaying || userTouchedRef.current) return;
    const t = setTimeout(() => {
      setIdx((i) => {
        if (i >= MILESTONES.length - 1) {
          setAutoPlaying(false);
          return i;
        }
        return i + 1;
      });
    }, idx === 0 ? 700 : 3400);
    return () => clearTimeout(t);
  }, [seen, idx, autoPlaying]);

  const milestone = MILESTONES[idx];
  const trackProgress = idx / (MILESTONES.length - 1);

  function jumpTo(i) {
    userTouchedRef.current = true;
    setAutoPlaying(false);
    setIdx(i);
  }

  return (
    <article ref={ref} className={seen ? 'cs2-card in-view' : 'cs2-card'}>
      <header className="cs2-head">
        <div className="cs2-tag">
          <span className="cs2-badge">E-commerce · SEO + Paid + Web + Email</span>
          <span className="cs2-client">Spec-Ring</span>
        </div>
        <h3 className="cs2-title">
          From <span className="cs2-strike">page 4 of Google</span> to the front row —
          and <span className="cs2-em">+288% in revenue</span> in a single year.
        </h3>
      </header>

      {/* Timeline scrubber */}
      <div className="cs2-timeline" role="tablist" aria-label="Milestone timeline">
        <div className="cs2-track">
          <div className="cs2-track-fill" style={{ width: `${trackProgress * 100}%` }} />
        </div>
        {MILESTONES.map((m, i) => (
          <button
            key={m.key}
            type="button"
            role="tab"
            aria-selected={i === idx}
            className={
              'cs2-stop' + (i === idx ? ' is-active' : '') + (i < idx ? ' is-passed' : '')
            }
            style={{ left: `${(i / (MILESTONES.length - 1)) * 100}%` }}
            onClick={() => jumpTo(i)}
          >
            <span className="cs2-stop-dot" />
            <span className="cs2-stop-label">
              <span className="full">{m.label}</span>
              <span className="short">{m.short}</span>
            </span>
          </button>
        ))}
      </div>

      {/* Stage */}
      <div className="cs2-stage">
        <Leaderboard rank={milestone.rank} />
        <Receipt idx={idx} milestone={milestone} />
      </div>

      {/* Caption row */}
      <div className="cs2-caption" key={milestone.key}>
        <div className="cs2-caption-main">
          <span className="cs2-caption-when">{milestone.label}</span>
          <h4 className="cs2-caption-headline">{milestone.headline}</h4>
          <p className="cs2-caption-quote">"{milestone.quote}"</p>
        </div>
        <div className="cs2-caption-chips">
          {milestone.chips.map((c) => (
            <span key={c} className="cs2-chip">{c}</span>
          ))}
        </div>
      </div>

      {/* Summary footer */}
      <footer className="cs2-foot">
        <div className="cs2-foot-stat">
          <span className="lbl">Avg position</span>
          <span className="val"><s>38th</s> → <strong>6th</strong></span>
        </div>
        <div className="cs2-foot-stat">
          <span className="lbl">YoY revenue</span>
          <span className="val"><strong>+288%</strong> vs 2024 baseline</span>
        </div>
        <div className="cs2-foot-stat">
          <span className="lbl">Channels engaged</span>
          <span className="val">SEO · Paid · Web · Email</span>
        </div>
        <div className="cs2-cta-group">
          <a href="/contact" className="cs2-link">
            Get results like these <span aria-hidden="true">→</span>
          </a>
          <a href="/plans" className="cs2-link-ghost">
            View plans
          </a>
        </div>
      </footer>
    </article>
  );
}

window.SpecRingCase = SpecRingCase;
