// faqs.jsx — FAQs video library (hub + individual video pages)
//
// VIDEOS is the single source of truth. To add a video:
//   1. Add an entry below (newest first — the first entry is featured on the hub).
//   2. Copy faqs/<any-slug>/index.html to faqs/<new-slug>/index.html and update
//      its <title>, meta description, canonical, og tags, and the slug passed to <VideoPage>.
//   3. Add the URL to sitemap.xml.
//
// Fields:
//   slug        URL segment → /faqs/<slug>/
//   youtubeId   the ID from the YouTube link (youtube.com/watch?v=THIS_PART or youtube.com/shorts/THIS_PART)
//   vertical    true for YouTube Shorts (9:16 player)
//   title       page headline
//   question    short question shown on the hub card
//   summary     1–2 sentences for cards + search engines
//   category    topic tag (Botox, Fillers, AuraLux, Skincare…) — drives the hub filter
//   date        upload date, YYYY-MM-DD (not shown on the page; Google requires it for video search)
//   duration    display length, e.g. "4:12"
//   description array of paragraphs for the video page
//   questions   [{ q, t, a }] — t = start time in seconds (optional), a = short answer
//   transcript  optional full transcript (plain text; blank lines separate paragraphs)
//   related     [{ label, href }] — links to treatment pages

const VIDEOS = [
  {
    slug: 'auralux-cold-fiber-laser',
    youtubeId: 'NWkjQZk-yDs',
    vertical: true,           // YouTube Short (9:16)
    title: 'How AuraLux Cold Fiber Laser Technology Works',
    question: 'What makes the AuraLux "cold fiber" laser different from a traditional laser?',
    summary: 'We explain how the AuraLux 2910 nm cold fiber laser controls heat instead of adding more of it, and why that means a more comfortable, customizable approach to laser resurfacing.',
    category: 'AuraLux',
    date: '2026-10-29',
    duration: '1:07',
    description: [
      'When most people hear “laser,” they picture heat, swelling, downtime, and discomfort. In this short video, we walk through why AuraLux takes a completely different approach — one built around controlling heat rather than adding more of it.',
      'AuraLux uses 2910 nm cold fiber technology to place energy precisely where it’s needed, leaving very little heat behind in the surrounding skin. Because the depth can be customized, it isn’t one single treatment: it ranges from a quick 10–15 minute refresh to deeper, collagen-remodeling resurfacing. It’s FDA cleared and safe for all skin types (Fitzpatrick I–VI).',
    ],
    questions: [
      { q: 'Does laser resurfacing always mean heat, swelling, and downtime?', t: 0,
        a: 'Not with AuraLux. The goal isn’t to add more heat — it’s to control it, which is what makes it a different experience from many traditional lasers.' },
      { q: 'What is “cold fiber” laser technology?', t: 12,
        a: 'AuraLux uses a 2910 nm cold fiber laser that delivers precise energy exactly where it’s needed in the skin.' },
      { q: 'Does “cold” mean there’s no heat at all?', t: 20,
        a: 'No. It means there’s much more control over where the energy goes and how much heat is left behind — AuraLux describes about 95% of the energy going toward the target, leaving very little residual heat.' },
      { q: 'Is AuraLux just one treatment?', t: 37,
        a: 'No. Because the depth is customizable, AuraLux works more like a platform that meets your skin where it’s at — from a light refresh to deeper resurfacing.' },
      { q: 'How does AuraLux help the skin heal?', t: 44,
        a: 'It creates controlled treatment zones while preserving the surrounding healthy tissue, so your skin’s natural healing process can do the rest.' },
    ],
    transcript: 'What if I told you the future of laser resurfacing isn’t about adding more heat — it’s about controlling it? Most people hear “laser” and they think of heat, swelling, downtime, and discomfort. AuraLux takes a completely different approach.\n\nIt uses 2910 nanometer cold fiber technology to deliver extreme precision energy exactly where it is needed. Cold doesn’t mean that there is no heat. It means the energy is delivered in a way that gives much more control over where the energy goes and how much heat is left behind. AuraLux describes 95% of the laser energy being directed towards the target ablation, leaving very little heat.\n\nBecause we can customize the depth, AuraLux isn’t just one treatment. Think of it as a platform that can meet your skin where it is at. The goal isn’t simply to damage the skin and wait for it to heal. The goal is precision. With AuraLux, we’re creating controlled treatment zones while preserving surrounding healthy tissue. This allows your skin’s natural healing process to do the rest.\n\nIt is a completely different way of thinking of energy, heat, depth, comfort, and skin rejuvenation. That is the technology behind the glow.',
    related: [
      { label: 'AuraLux Laser', href: '/treatments/#auralux' },
      { label: 'All Treatments', href: '/treatments/' },
    ],
  },
];

// ── helpers ───────────────────────────────────────────────────────
const fmtTime = (s) => `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
// Cards use the 16:9 thumbnail (YouTube pads Shorts with a blurred background);
// the vertical player uses YouTube's 9:16 Shorts thumbnail.
const thumbFor = (v) => v.poster || (v.youtubeId ? `https://i.ytimg.com/vi/${v.youtubeId}/maxresdefault.jpg` : '/assets/studio-lounge.jpg');
const playerThumbFor = (v) => v.vertical && v.youtubeId ? `https://i.ytimg.com/vi/${v.youtubeId}/oar2.jpg` : thumbFor(v);

function PlayIcon({ size = 76 }) {
  return (
    <span aria-hidden="true" style={{
      width: size, height: size, borderRadius: '50%',
      background: 'rgba(246,242,236,0.92)', boxShadow: '0 8px 30px rgba(26,15,8,0.35)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'transform .25s ease',
    }} className="play-icon">
      <svg width={size * 0.32} height={size * 0.32} viewBox="0 0 24 24" style={{ marginLeft: size * 0.05 }}>
        <path d="M6 4l14 8-14 8z" fill="var(--color-deep-brown)" />
      </svg>
    </span>
  );
}

// ── Lite YouTube player ───────────────────────────────────────────
// Shows a thumbnail until clicked; only then loads YouTube (privacy-enhanced
// youtube-nocookie.com domain). Keeps pages fast and cookie-free until play.
function VideoPlayer({ video, startAt, playKey }) {
  const [playing, setPlaying] = useState(false);
  useEffect(() => { if (playKey) setPlaying(true); }, [playKey]);

  const frame = { position: 'relative', aspectRatio: video.vertical ? '9 / 16' : '16 / 9', ...(video.vertical ? { maxWidth: 380, margin: '0 auto' } : {}), borderRadius: 'var(--radius-xl)', overflow: 'hidden', boxShadow: 'var(--shadow-lg)', background: 'var(--color-deep-brown)' };

  if (!video.youtubeId) {
    return (
      <div style={{ ...frame, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ textAlign: 'center', color: 'var(--color-tan)', display: 'flex', flexDirection: 'column', gap: 14, alignItems: 'center' }}>
          <PlayIcon />
          <div className="eyebrow" style={{ color: 'var(--color-tan)' }}>YouTube video goes here</div>
        </div>
      </div>
    );
  }

  if (playing) return <EmbeddedPlayer video={video} frame={frame} startAt={startAt} playKey={playKey} />;

  return (
    <button onClick={() => setPlaying(true)} aria-label={`Play video: ${video.title}`} className="video-thumb"
      style={{ ...frame, display: 'block', width: '100%', padding: 0, border: 0, cursor: 'pointer' }}>
      <img src={playerThumbFor(video)} alt="" onError={e => { if (e.currentTarget.src !== thumbFor(video)) e.currentTarget.src = thumbFor(video); }} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
      <span style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(26,15,8,0.05) 40%, rgba(26,15,8,0.45) 100%)' }} />
      <span style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><PlayIcon size={88} /></span>
    </button>
  );
}

// ── Embedded player with our own controls ─────────────────────────
// YouTube's built-in overlay (title bar, big pause button, "Shorts" logo)
// stays up whenever the mouse is over the video or it's paused, and there's
// no embed setting to turn it off. So we load YouTube with controls=0, put a
// transparent layer over the iframe (so YouTube never sees the mouse), and
// drive it through YouTube's postMessage API with a small custom control bar.
function EmbeddedPlayer({ video, frame, startAt, playKey }) {
  const wrapRef = React.useRef(null);
  const iframeRef = React.useRef(null);
  const idleTimer = React.useRef(null);
  const [state, setState] = useState(-1);        // YouTube playerState: 1 playing, 2 paused, 0 ended, 3 buffering
  const [time, setTime] = useState({ cur: startAt || 0, dur: 0 });
  const [muted, setMuted] = useState(false);
  const [active, setActive] = useState(true);    // show our controls while the mouse is moving

  // Only built once; later timestamp clicks seek instead of reloading.
  const [src] = useState(() => `https://www.youtube-nocookie.com/embed/${video.youtubeId}?autoplay=1&controls=0&disablekb=1&fs=0&rel=0&modestbranding=1&playsinline=1&iv_load_policy=3&enablejsapi=1&origin=${encodeURIComponent(location.origin)}${startAt ? `&start=${startAt}` : ''}`);

  const send = (func, args = []) => {
    const w = iframeRef.current && iframeRef.current.contentWindow;
    if (w) w.postMessage(JSON.stringify({ event: 'command', func, args }), '*');
  };

  useEffect(() => {
    const onMsg = (e) => {
      if (!/youtube(-nocookie)?\.com$/.test(new URL(e.origin).hostname)) return;
      let d; try { d = JSON.parse(e.data); } catch { return; }
      const info = d.info || {};
      if (typeof info.playerState === 'number') setState(info.playerState);
      if (typeof info.currentTime === 'number' || typeof info.duration === 'number') {
        setTime(t => ({ cur: info.currentTime ?? t.cur, dur: info.duration || t.dur }));
      }
      if (typeof info.muted === 'boolean') setMuted(info.muted);
    };
    window.addEventListener('message', onMsg);
    return () => window.removeEventListener('message', onMsg);
  }, []);

  // Timestamp buttons after the player is already loaded → seek in place.
  const firstKey = React.useRef(playKey);
  useEffect(() => {
    if (playKey === firstKey.current) return;
    send('seekTo', [startAt, true]); send('playVideo');
  }, [playKey]);

  const listen = () => {
    const w = iframeRef.current && iframeRef.current.contentWindow;
    if (w) w.postMessage(JSON.stringify({ event: 'listening', id: video.youtubeId, channel: 'widget' }), '*');
  };

  const wake = () => {
    setActive(true);
    clearTimeout(idleTimer.current);
    idleTimer.current = setTimeout(() => setActive(false), 2200);
  };
  useEffect(() => { wake(); return () => clearTimeout(idleTimer.current); }, []);

  const isPlaying = state === 1 || state === 3;
  const toggle = () => {
    if (state === 0) { send('seekTo', [0, true]); send('playVideo'); }
    else if (isPlaying) send('pauseVideo');
    else send('playVideo');
    wake();
  };
  const toggleMute = (e) => { e.stopPropagation(); send(muted ? 'unMute' : 'mute'); setMuted(!muted); wake(); };
  const fullscreen = (e) => {
    e.stopPropagation();
    const el = wrapRef.current;
    if (document.fullscreenElement) document.exitFullscreen();
    else if (el.requestFullscreen) el.requestFullscreen();
    else if (el.webkitRequestFullscreen) el.webkitRequestFullscreen();
    else if (iframeRef.current.webkitEnterFullscreen) iframeRef.current.webkitEnterFullscreen();
  };
  const seekBar = (e) => {
    e.stopPropagation();
    if (!time.dur) return;
    const r = e.currentTarget.getBoundingClientRect();
    const t = Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)) * time.dur;
    send('seekTo', [t, true]); setTime(x => ({ ...x, cur: t })); wake();
  };

  const showChrome = !isPlaying || active;
  const pct = time.dur ? (time.cur / time.dur) * 100 : 0;
  const iconBtn = { width: 34, height: 34, borderRadius: '50%', border: 0, background: 'rgba(26,15,8,0.55)', color: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0 };

  return (
    <div ref={wrapRef} className="yt-wrap" style={frame} onMouseMove={wake} onMouseLeave={() => setActive(false)}>
      <iframe ref={iframeRef} src={src} title={video.title} onLoad={listen} tabIndex={-1}
        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
        style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', border: 0, pointerEvents: 'none' }} />

      {/* Click layer: sits over YouTube so its own overlay never appears. */}
      <button onClick={toggle} aria-label={isPlaying ? 'Pause video' : 'Play video'}
        style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', border: 0, padding: 0, cursor: 'pointer',
                 background: !isPlaying && state !== -1 ? 'rgba(26,15,8,0.28)' : 'transparent', transition: 'background .25s',
                 display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {!isPlaying && state !== -1 && <PlayIcon size={80} />}
      </button>

      {/* Our control bar — fades away while playing and the mouse is still. */}
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '28px 14px 12px',
                    background: 'linear-gradient(180deg, transparent, rgba(26,15,8,0.6))',
                    opacity: showChrome ? 1 : 0, transition: 'opacity .35s', pointerEvents: showChrome ? 'auto' : 'none' }}>
        <div onClick={seekBar} role="slider" aria-label="Seek" aria-valuemin={0} aria-valuemax={Math.round(time.dur)} aria-valuenow={Math.round(time.cur)}
          style={{ height: 14, display: 'flex', alignItems: 'center', cursor: 'pointer', marginBottom: 6 }}>
          <div style={{ position: 'relative', height: 3, width: '100%', background: 'rgba(255,255,255,0.35)', borderRadius: 2 }}>
            <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: `${pct}%`, background: 'var(--color-ivory)', borderRadius: 2 }} />
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <button onClick={(e) => { e.stopPropagation(); toggle(); }} aria-label={isPlaying ? 'Pause' : 'Play'} style={iconBtn}>
            {isPlaying
              ? <svg width="12" height="12" viewBox="0 0 24 24"><path d="M6 4h4v16H6zM14 4h4v16h-4z" fill="currentColor" /></svg>
              : <svg width="12" height="12" viewBox="0 0 24 24"><path d="M7 4l13 8-13 8z" fill="currentColor" /></svg>}
          </button>
          <button onClick={toggleMute} aria-label={muted ? 'Unmute' : 'Mute'} style={iconBtn}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M11 5L6 9H2v6h4l5 4z" fill="currentColor" />
              {muted ? <><line x1="22" y1="9" x2="16" y2="15" /><line x1="16" y1="9" x2="22" y2="15" /></> : <path d="M15.5 8.5a5 5 0 0 1 0 7M18.5 5.5a9 9 0 0 1 0 13" />}
            </svg>
          </button>
          <span style={{ color: '#fff', fontSize: 12, fontWeight: 500, letterSpacing: '0.04em', marginLeft: 4 }}>
            {fmtTime(Math.floor(time.cur))}{time.dur ? ` / ${fmtTime(Math.round(time.dur))}` : ''}
          </span>
          <span style={{ flex: 1 }} />
          <button onClick={fullscreen} aria-label="Full screen" style={iconBtn}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" /></svg>
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Hub card thumbnail ────────────────────────────────────────────
function VideoThumb({ video, ratio = '16 / 9' }) {
  return (
    <div style={{ position: 'relative', aspectRatio: ratio, overflow: 'hidden', background: 'var(--color-deep-brown)' }}>
      <img src={thumbFor(video)} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', filter: 'contrast(0.97) saturate(0.92)', opacity: video.youtubeId || video.poster ? 1 : 0.55 }} />
      <span style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><PlayIcon size={64} /></span>
      {video.duration && video.duration !== '0:00' && (
        <span style={{ position: 'absolute', right: 12, bottom: 12, background: 'rgba(26,15,8,0.78)', color: 'var(--color-ivory)', fontSize: 11, fontWeight: 600, letterSpacing: '0.08em', padding: '4px 8px', borderRadius: 4 }}>{video.duration}</span>
      )}
    </div>
  );
}

// ── HUB PAGE (/faqs/) ─────────────────────────────────────────────
function FaqsPage() {
  const categories = ['All', ...Array.from(new Set(VIDEOS.map(v => v.category)))];
  const [filter, setFilter] = useState('All');
  const list = filter === 'All' ? VIDEOS : VIDEOS.filter(v => v.category === filter);
  const [featured, ...rest] = list;

  return (
    <div>
      <Header active="Learn" />
      <PageHeader
        eyebrow="FAQs · Ask Us"
        title="Your questions,"
        accent="answered."
        body="Short videos answering the questions we hear most in the chair — about treatments, results, recovery, and caring for your skin."
      />

      {categories.length > 2 && (
        <div className="container" style={{ paddingTop: 56, display: 'flex', gap: 10, flexWrap: 'wrap', justifyContent: 'center' }}>
          {categories.map(c => (
            <button key={c} onClick={() => setFilter(c)} className="faq-filter" aria-pressed={filter === c}
              style={{
                fontSize: 11, fontWeight: 600, letterSpacing: '0.2em', textTransform: 'uppercase',
                padding: '10px 18px', borderRadius: 999, cursor: 'pointer',
                border: '1px solid ' + (filter === c ? 'var(--color-deep-brown)' : 'var(--color-border)'),
                background: filter === c ? 'var(--color-deep-brown)' : 'transparent',
                color: filter === c ? 'var(--color-ivory)' : 'var(--color-taupe)',
              }}>{c}</button>
          ))}
        </div>
      )}

      {featured && (
        <section style={{ padding: '80px 0 70px' }}>
          <div className="container">
            <a href={`/faqs/${featured.slug}/`} className="hero-grid video-card" style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 56, alignItems: 'center' }}>
              <div style={{ borderRadius: 'var(--radius-xl)', overflow: 'hidden', boxShadow: 'var(--shadow-lg)' }}>
                <VideoThumb video={featured} />
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
                <div style={{ display: 'flex', gap: 14, alignItems: 'center', flexWrap: 'wrap' }}>
                  <span className="badge badge-tan">{featured.category}</span>
                  <span className="eyebrow">Latest video</span>
                </div>
                <h2 className="h-section" style={{ fontSize: 'clamp(30px, 3.2vw, 44px)' }}>{featured.title}</h2>
                <div className="burgundy-rule" />
                <p className="body-lg" style={{ color: 'var(--color-taupe)' }}>{featured.summary}</p>
                <div className="link-arrow" style={{ marginTop: 6 }}>Watch the video →</div>
              </div>
            </a>
          </div>
        </section>
      )}

      {rest.length > 0 && (
        <section style={{ padding: '0 0 110px' }}>
          <div className="container">
            <div className="eyebrow" style={{ marginBottom: 30 }}>More answers</div>
            <div className="grid-3" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 28 }}>
              {rest.map(v => <VideoCard key={v.slug} video={v} />)}
            </div>
          </div>
        </section>
      )}

      <AskQuestion />
      <BookCTA />
      <Footer />
      <VideoStyles />
    </div>
  );
}

function VideoCard({ video }) {
  return (
    <a href={`/faqs/${video.slug}/`} className="video-card" style={{ display: 'flex', flexDirection: 'column', background: 'var(--color-surface-raised)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-xl)', overflow: 'hidden', boxShadow: 'var(--shadow-sm)', transition: 'all .3s ease' }}>
      <VideoThumb video={video} />
      <div style={{ padding: '22px 24px 26px', display: 'flex', flexDirection: 'column', gap: 10, flex: 1 }}>
        <span className="eyebrow">{video.category}</span>
        <h3 className="h-sub" style={{ fontSize: 23 }}>{video.title}</h3>
        <p className="body-sm" style={{ color: 'var(--color-taupe)', flex: 1 }}>{video.question}</p>
        <div style={{ marginTop: 4, fontSize: 11, fontWeight: 500, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--color-deep-brown)' }}>Watch →</div>
      </div>
    </a>
  );
}

function AskQuestion() {
  return (
    <section className="bg-linen" style={{ padding: '90px 0', borderTop: '1px solid var(--color-border-subtle)' }}>
      <div className="container-narrow" style={{ textAlign: 'center', display: 'flex', flexDirection: 'column', gap: 20, alignItems: 'center' }}>
        <Eyebrow>Ask Us</Eyebrow>
        <h2 className="h-section" style={{ fontSize: 'clamp(30px, 3.4vw, 44px)' }}>Have a question you&rsquo;d like <Accent>answered?</Accent></h2>
        <p className="body-md" style={{ maxWidth: 560, color: 'var(--color-taupe)' }}>
          Send it our way — your question could be the topic of our next video. Or book a consultation and ask us in person.
        </p>
        <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', justifyContent: 'center', marginTop: 8 }}>
          <Button variant="primary" href="/contact-us/">Send a Question</Button>
          <Button variant="ghost" href="#book-now">Book a Consultation</Button>
        </div>
      </div>
    </section>
  );
}

// ── VIDEO PAGE (/faqs/<slug>/) ────────────────────────────────────
function VideoPage({ slug }) {
  const video = VIDEOS.find(v => v.slug === slug);
  const [jump, setJump] = useState({ t: 0, key: 0 });
  const [showTranscript, setShowTranscript] = useState(false);
  const playerRef = React.useRef(null);

  useEffect(() => {
    if (!video || !video.youtubeId) return;
    const url = `https://racheldahlen.com/faqs/${video.slug}/`;
    const ld = {
      '@context': 'https://schema.org',
      '@type': 'VideoObject',
      name: video.title,
      description: video.summary,
      thumbnailUrl: [`https://i.ytimg.com/vi/${video.youtubeId}/maxresdefault.jpg`, `https://i.ytimg.com/vi/${video.youtubeId}/hqdefault.jpg`],
      uploadDate: video.date,
      embedUrl: `https://www.youtube-nocookie.com/embed/${video.youtubeId}`,
      contentUrl: `https://www.youtube.com/watch?v=${video.youtubeId}`,
      publisher: { '@type': 'Organization', name: 'Rachel Dahlen Aesthetics', logo: { '@type': 'ImageObject', url: 'https://racheldahlen.com/assets/logo-text-only.png' } },
      mainEntityOfPage: url,
    };
    const timed = video.questions.filter(q => typeof q.t === 'number');
    if (timed.length) {
      ld.hasPart = timed.map((q, i) => ({
        '@type': 'Clip', name: q.q, startOffset: q.t,
        ...(timed[i + 1] ? { endOffset: timed[i + 1].t } : {}),
        url: `https://www.youtube.com/watch?v=${video.youtubeId}&t=${q.t}`,
      }));
    }
    const el = document.createElement('script');
    el.type = 'application/ld+json';
    el.text = JSON.stringify(ld);
    document.head.appendChild(el);
    return () => el.remove();
  }, [slug]);

  if (!video) return <div><Header active="Learn" /><div className="container" style={{ padding: '120px 32px' }}>Video not found. <a href="/faqs/" className="link-arrow">← All FAQs</a></div><Footer /></div>;

  const others = VIDEOS.filter(v => v.slug !== slug).slice(0, 3);
  const seek = (t) => {
    setJump(j => ({ t, key: j.key + 1 }));
    if (playerRef.current) playerRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' });
  };

  return (
    <div>
      <Header active="Learn" />
      <article>
        <section className="bg-linen" style={{ padding: '64px 0 150px' }}>
          <div className="container-narrow" style={{ textAlign: 'center', display: 'flex', flexDirection: 'column', gap: 20, alignItems: 'center' }}>
            <a href="/faqs/" className="link-arrow" style={{ textDecoration: 'none' }}>← All FAQs</a>
            <Eyebrow>{video.category}</Eyebrow>
            <h1 className="h-display" style={{ fontSize: 'clamp(34px, 4.4vw, 56px)', maxWidth: 860 }}>{video.title}</h1>
          </div>
        </section>

        <div className="container" style={{ maxWidth: 1040, marginTop: -110 }} ref={playerRef}>
          <VideoPlayer video={video} startAt={jump.t} playKey={jump.key} />
        </div>

        <section style={{ padding: '64px 0 100px' }}>
          <div className="container video-layout" style={{ maxWidth: 1040, display: 'grid', gridTemplateColumns: '1fr 300px', gap: 64, alignItems: 'start' }}>
            <div className="blog-prose" style={{ maxWidth: 'none', margin: 0 }}>
              {video.description.map((p, i) => <p key={i}>{p}</p>)}

              {video.questions.length > 0 && (
                <>
                  <h2>Questions answered in this video</h2>
                  <div style={{ display: 'flex', flexDirection: 'column', borderTop: '1px solid var(--color-border-subtle)', marginBottom: 32 }}>
                    {video.questions.map((q, i) => (
                      <div key={i} style={{ padding: '22px 0', borderBottom: '1px solid var(--color-border-subtle)', display: 'flex', gap: 20, alignItems: 'flex-start' }}>
                        {typeof q.t === 'number' && video.youtubeId ? (
                          <button onClick={() => seek(q.t)} className="ts-btn" aria-label={`Play from ${fmtTime(q.t)}`}
                            style={{ flexShrink: 0, minWidth: 64, padding: '6px 10px', borderRadius: 999, border: '1px solid var(--color-border)', background: 'var(--color-surface-raised)', color: 'var(--color-burgundy)', fontSize: 12, fontWeight: 600, letterSpacing: '0.06em', cursor: 'pointer', marginTop: 3 }}>
                            ▶ {fmtTime(q.t)}
                          </button>
                        ) : typeof q.t === 'number' ? (
                          <span style={{ flexShrink: 0, minWidth: 64, padding: '6px 10px', borderRadius: 999, border: '1px solid var(--color-border)', color: 'var(--color-text-muted)', fontSize: 12, fontWeight: 600, textAlign: 'center', marginTop: 3 }}>{fmtTime(q.t)}</span>
                        ) : null}
                        <div>
                          <h3 style={{ margin: '0 0 8px', fontSize: 22 }}>{q.q}</h3>
                          {q.a && <p style={{ margin: 0, fontSize: 17, lineHeight: 1.75, color: 'var(--color-taupe)' }}>{q.a}</p>}
                        </div>
                      </div>
                    ))}
                  </div>
                </>
              )}

              {video.transcript && (
                <div style={{ border: '1px solid var(--color-border)', borderRadius: 'var(--radius-lg)', background: 'var(--color-surface-raised)' }}>
                  <button onClick={() => setShowTranscript(s => !s)} aria-expanded={showTranscript}
                    style={{ width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '18px 22px', background: 'none', border: 0, cursor: 'pointer', fontSize: 11, fontWeight: 600, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--color-deep-brown)' }}>
                    Read the transcript
                    <span style={{ fontSize: 8, transform: showTranscript ? 'rotate(180deg)' : 'none', transition: 'transform .25s' }}>▼</span>
                  </button>
                  <div style={{ display: showTranscript ? 'block' : 'none', padding: '0 22px 8px' }}>
                    {video.transcript.split(/\n\s*\n/).map((p, i) => <p key={i} style={{ fontSize: 16, lineHeight: 1.8, color: 'var(--color-taupe)' }}>{p}</p>)}
                  </div>
                </div>
              )}
            </div>

            <aside className="video-aside" style={{ position: 'sticky', top: 110, display: 'flex', flexDirection: 'column', gap: 24, padding: 28, border: '1px solid var(--color-border)', borderRadius: 'var(--radius-xl)', background: 'var(--color-surface-raised)' }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                <div className="eyebrow">About this video</div>
                <div style={{ fontSize: 14, color: 'var(--color-taupe)', lineHeight: 1.7 }}>
                  {video.vertical ? 'Short video' : 'Video'}
                  {video.duration && video.duration !== '0:00' && <> · {video.duration}</>}
                </div>
              </div>
              {video.related && video.related.length > 0 && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10, paddingTop: 20, borderTop: '1px solid var(--color-border-subtle)' }}>
                  <div className="eyebrow">Related treatments</div>
                  {video.related.map(r => <a key={r.href} href={r.href} className="link-arrow">{r.label} →</a>)}
                </div>
              )}
              <div style={{ paddingTop: 20, borderTop: '1px solid var(--color-border-subtle)', display: 'flex', flexDirection: 'column', gap: 12 }}>
                <Button variant="primary" href="#book-now" style={{ textAlign: 'center' }}>Book a Consultation</Button>
                {video.youtubeId && (
                  <a href={`https://www.youtube.com/watch?v=${video.youtubeId}`} target="_blank" rel="noopener noreferrer"
                    style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--color-taupe)', textAlign: 'center' }}>Watch on YouTube ↗</a>
                )}
              </div>
            </aside>
          </div>
        </section>
      </article>

      {others.length > 0 && (
        <section className="bg-linen" style={{ padding: '90px 0 100px', borderTop: '1px solid var(--color-border-subtle)' }}>
          <div className="container">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 30, gap: 16, flexWrap: 'wrap' }}>
              <div className="eyebrow">More answers</div>
              <a href="/faqs/" className="link-arrow">All FAQs →</a>
            </div>
            <div className="grid-3" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 28 }}>
              {others.map(v => <VideoCard key={v.slug} video={v} />)}
            </div>
          </div>
        </section>
      )}

      <AskQuestion />
      <BookCTA />
      <Footer />
      <VideoStyles />
    </div>
  );
}

function VideoStyles() {
  return <style>{`
    .video-card:hover .play-icon, .video-thumb:hover .play-icon { transform: scale(1.08); }
    a.video-card[style*="flex-direction: column"]:hover { transform: translateY(-5px); box-shadow: var(--shadow-lg) !important; }
    .ts-btn:hover { background: var(--color-burgundy) !important; color: var(--color-ivory) !important; border-color: var(--color-burgundy) !important; }
    .faq-filter:hover { border-color: var(--color-deep-brown) !important; }
    @media (max-width: 900px) {
      .video-layout { grid-template-columns: 1fr !important; gap: 40px !important; }
      .video-aside { position: static !important; }
    }
  `}</style>;
}

Object.assign(window, { VIDEOS, FaqsPage, VideoPage });
