// Sparky and the Lightning Within — interactive storybook for siblings

const SPARKY_PAGES = [
  { alt: 'Cover page: Sparky and the Lightning Within. Sparky the blue superhero puppy runs across a grassy field under a bright sky.', text: null },
  { alt: 'Introduction page: a colouring activity prompt with Sparky sitting beside crayons, inviting families to colour the book together and talk about SCN2A.', text: 'Colour me in! Talk about the story with someone you love.' },
  { alt: 'Sparky the superhero puppy runs through a park with trees, wearing his cape and lightning bolt collar. He is on a mission to help families.', text: 'Meet Sparky!\nHe wears a cape and has a star on his chest.\nSparky helps families feel brave.' },
  { alt: 'Sparky arrives at a living room where Zoe kneels beside her little brother Leo. They are both smiling.', altV2: 'Sparky arrives at a living room where Zoe kneels beside her little brother Leo, who is in a wheelchair. They are both smiling.', text: 'Sparky visits Zoe and her little brother Leo.\nLeo has something called SCN2A.\nSometimes his body shakes.\nSometimes he is very quiet.\nZoe loves Leo and wants to help.' },
  { alt: 'Zoe sits cross-legged talking to Sparky while Leo watches. They are in a cosy room with bookshelves and a window.', altV2: 'Zoe sits cross-legged talking to Sparky while Leo watches from his wheelchair. They are in a cosy room with bookshelves and a window.', text: "Zoe asks: 'Why is Leo different to me?'\nSparky sits close.\n'Everyone's brain sends messages,' he says.\n'Like waves in the sea.'" },
  { alt: 'Zoe, Leo, and Sparky sit together in a sunny park. A thought bubble above them shows a brain with a lightning bolt, explaining how brain messages work differently.', altV2: 'Zoe, Leo in his wheelchair, and Sparky sit together in a sunny park. A thought bubble shows a brain with a lightning bolt, explaining how brain messages work differently.', text: "'Leo's messages sometimes go too fast, or too slow.\nThat is why he might shake, or feel very tired.\nEvery brain is different, and that is okay.'" },
  { alt: 'Zoe sits under a tree hugging her knees, looking thoughtful. Sparky sits beside her, comforting her with a gentle presence. The sun sets behind them.', text: "'Can we help Leo?' Zoe asks.\n'Yes!' says Sparky.\n'Doctors and scientists are working hard.\nAnd you are never, ever alone.'" },
  { alt: 'Zoe and Leo wave goodbye outside their house as Sparky zooms away with a trail of sparkles. Both children are smiling.', altV2: 'Zoe stands beside Leo in his wheelchair as they wave goodbye outside their house. Sparky zooms away with a trail of sparkles.', text: "'Sometimes I feel left out,' says Zoe.\nSparky gives her a nudge.\n'You matter too.\nYour hugs help Leo feel safe.\nYou are a hero, just like me!'\nZoe smiles. 'We are a team!'\n'Yes,' says Sparky. 'And teams need hope.\nThat is why I am here!'" },
  { alt: 'Back cover with a message of hope for families living with SCN2A, and the SCN2A Australia logo with a QR code.', text: null },
];

function SparkyStorybookPage({ navigate }) {
  const [page, setPage] = React.useState(0);
  const [version, setVersion] = React.useState('v2');
  const [showText, setShowText] = React.useState(true);
  const touchRef = React.useRef(null);
  const totalPages = SPARKY_PAGES.length;
  const prefersReducedMotion = typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  const transition = prefersReducedMotion ? 'none' : 'all 0.2s';

  const prev = () => setPage(p => Math.max(0, p - 1));
  const next = () => setPage(p => Math.min(totalPages - 1, p + 1));

  React.useEffect(() => {
    if (window.lucide && window.lucide.createIcons) window.lucide.createIcons();
  });

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'ArrowLeft') prev();
      if (e.key === 'ArrowRight') next();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  const onTouchStart = (e) => { touchRef.current = e.touches[0].clientX; };
  const onTouchEnd = (e) => {
    if (touchRef.current === null) return;
    const diff = touchRef.current - e.changedTouches[0].clientX;
    if (Math.abs(diff) > 50) { diff > 0 ? next() : prev(); }
    touchRef.current = null;
  };

  const currentData = SPARKY_PAGES[page];
  const currentAlt = (version === 'v2' && currentData.altV2) ? currentData.altV2 : currentData.alt;
  const imgSrc = `assets/sparky/${version}/page-0${page + 1}.png`;

  const NK = {
    navy: '#1E3A6E', ink: '#0D1B2A', canvas: '#F7F4F0', sand: '#E8E3DA',
    mulberry: '#8E3B5E', white: '#FFFFFF', muted: '#6B6659', cobalt: '#4A7EC7',
  };

  return (
    <div data-screen-label="Sparky's Storybook">
      {/* Hero */}
      <PageHero
        eyebrow="For siblings"
        title="Sparky and the Lightning Within"
        body="A colouring storybook to help brothers and sisters understand SCN2A, and to know they matter too."
        primaryCta={{ label: 'Start reading', onClick: () => document.getElementById('sparky-viewer').scrollIntoView({ behavior: 'smooth' }) }}
        navigate={navigate}
      />
      <Breadcrumbs items={[
        { label: 'Support', to: 'support' },
        { label: "Sparky's Storybook" },
      ]} navigate={navigate} />

      {/* Intro */}
      <section style={{ background: NK.canvas, padding: '56px 0 0' }}>
        <div className="container" style={{ maxWidth: 760, textAlign: 'center' }}>
          <p style={{ fontSize: 18, lineHeight: 1.7, color: NK.ink, margin: '0 auto', maxWidth: 620 }}>
            Sparky is a superhero puppy on a mission to spark hope. In this colouring storybook, he visits Zoe and her brother Leo to explain SCN2A in a way young children can understand, and to remind siblings that they are heroes too.
          </p>
          <p style={{ fontSize: 14, color: NK.muted, marginTop: 12 }}>
            Recommended for ages 4 to 6. Print it out and colour it in together.
          </p>
        </div>
      </section>

      {/* Version toggle */}
      <section style={{ background: NK.canvas, padding: '32px 0 16px' }}>
        <div className="container" style={{ display: 'flex', justifyContent: 'center', gap: 0 }}>
          {[
            { key: 'v1', label: 'Version 1' },
            { key: 'v2', label: 'Version 2' },
          ].map(v => (
            <button
              key={v.key}
              onClick={() => { setVersion(v.key); setPage(0); }}
              aria-pressed={version === v.key}
              style={{
                padding: '10px 28px',
                fontSize: 14,
                fontWeight: version === v.key ? 700 : 500,
                fontFamily: 'var(--font-sans, "Plus Jakarta Sans", sans-serif)',
                color: version === v.key ? NK.white : NK.ink,
                background: version === v.key ? NK.navy : NK.sand,
                border: 'none',
                borderRadius: v.key === 'v1' ? '5px 0 0 5px' : '0 5px 5px 0',
                cursor: 'pointer',
                transition: prefersReducedMotion ? 'none' : 'background 0.2s, color 0.2s',
              }}
              onFocus={(e) => { e.target.style.outline = `2px solid ${NK.mulberry}`; e.target.style.outlineOffset = '2px'; }}
              onBlur={(e) => { e.target.style.outline = ''; }}
            >
              {v.label}
            </button>
          ))}
        </div>
        <p style={{ textAlign: 'center', fontSize: 13, color: NK.muted, marginTop: 10 }}>
          {version === 'v1' ? 'Leo is shown sitting independently.' : 'Leo is shown using a wheelchair.'}
        </p>
      </section>

      {/* Storybook viewer */}
      <section id="sparky-viewer" style={{ background: NK.canvas, padding: '16px 0 56px' }}>
        <div
          className="container"
          style={{ maxWidth: 780, position: 'relative' }}
          role="region"
          aria-label="Interactive storybook viewer"
          onTouchStart={onTouchStart}
          onTouchEnd={onTouchEnd}
        >
          {/* Image */}
          <div style={{
            background: NK.white,
            borderRadius: 5,
            border: `1px solid ${NK.sand}`,
            overflow: 'hidden',
            boxShadow: '0 2px 12px rgba(0,0,0,0.06)',
          }}>
            <img
              src={imgSrc}
              alt={currentAlt}
              style={{ width: '100%', height: 'auto', display: 'block' }}
            />
          </div>

          {/* Navigation arrows */}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 20 }}>
            <button
              onClick={prev}
              disabled={page === 0}
              aria-label="Previous page"
              style={{
                width: 44, height: 44,
                borderRadius: 5,
                border: `1px solid ${NK.sand}`,
                background: page === 0 ? NK.sand : NK.white,
                color: page === 0 ? NK.muted : NK.ink,
                cursor: page === 0 ? 'default' : 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 20, fontWeight: 700,
              }}
              onFocus={(e) => { e.target.style.outline = `2px solid ${NK.mulberry}`; e.target.style.outlineOffset = '2px'; }}
              onBlur={(e) => { e.target.style.outline = ''; }}
            >
              <i data-lucide="chevron-left" style={{ width: 20, height: 20 }} />
            </button>

            {/* Page dots */}
            <div style={{ display: 'flex', gap: 8, alignItems: 'center' }} role="tablist" aria-label="Page navigation">
              {SPARKY_PAGES.map((_, i) => (
                <button
                  key={i}
                  role="tab"
                  aria-selected={i === page}
                  aria-label={`Page ${i + 1}`}
                  onClick={() => setPage(i)}
                  style={{
                    width: i === page ? 12 : 8,
                    height: i === page ? 12 : 8,
                    borderRadius: '50%',
                    background: i === page ? NK.navy : NK.sand,
                    border: 'none',
                    padding: 0,
                    cursor: 'pointer',
                    transition,
                  }}
                  onFocus={(e) => { e.target.style.outline = `2px solid ${NK.mulberry}`; e.target.style.outlineOffset = '2px'; }}
                  onBlur={(e) => { e.target.style.outline = ''; }}
                />
              ))}
            </div>

            <button
              onClick={next}
              disabled={page === totalPages - 1}
              aria-label="Next page"
              style={{
                width: 44, height: 44,
                borderRadius: 5,
                border: `1px solid ${NK.sand}`,
                background: page === totalPages - 1 ? NK.sand : NK.white,
                color: page === totalPages - 1 ? NK.muted : NK.ink,
                cursor: page === totalPages - 1 ? 'default' : 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 20, fontWeight: 700,
              }}
              onFocus={(e) => { e.target.style.outline = `2px solid ${NK.mulberry}`; e.target.style.outlineOffset = '2px'; }}
              onBlur={(e) => { e.target.style.outline = ''; }}
            >
              <i data-lucide="chevron-right" style={{ width: 20, height: 20 }} />
            </button>
          </div>

          {/* Page counter (aria-live) */}
          <div aria-live="polite" style={{ textAlign: 'center', fontSize: 13, color: NK.muted, marginTop: 8 }}>
            Page {page + 1} of {totalPages}
          </div>

          {/* Read-along text toggle & panel */}
          {currentData.text && (
            <div style={{ marginTop: 20 }}>
              <button
                onClick={() => setShowText(s => !s)}
                style={{
                  background: 'none', border: 'none', padding: '6px 0',
                  fontSize: 14, color: NK.navy, fontWeight: 600, cursor: 'pointer',
                  fontFamily: 'var(--font-sans, "Plus Jakarta Sans", sans-serif)',
                  display: 'flex', alignItems: 'center', gap: 6,
                }}
                onFocus={(e) => { e.target.style.outline = `2px solid ${NK.mulberry}`; e.target.style.outlineOffset = '2px'; }}
                onBlur={(e) => { e.target.style.outline = ''; }}
                aria-expanded={showText}
              >
                <i data-lucide={showText ? 'eye-off' : 'eye'} style={{ width: 16, height: 16 }} />
                {showText ? 'Hide read-along text' : 'Show read-along text'}
              </button>
              {showText && (
                <div style={{
                  marginTop: 12,
                  padding: '24px 28px',
                  background: NK.white,
                  borderRadius: 5,
                  border: `1px solid ${NK.sand}`,
                  fontSize: 18,
                  lineHeight: 1.8,
                  color: NK.ink,
                  fontFamily: 'var(--font-sans, "Plus Jakarta Sans", sans-serif)',
                  whiteSpace: 'pre-line',
                }}>
                  {currentData.text}
                </div>
              )}
            </div>
          )}
        </div>
      </section>

      {/* Download section */}
      <CTABlock
        eyebrow="Print & colour"
        title="Download Sparky's storybook"
        body="Print the book at home so your child can colour it in. Available in two versions."
        ctaLabel="Download Version 2"
        onCta={() => {
          const a = document.createElement('a');
          a.href = 'assets/sparky/sparky-storybook-v2.zip';
          a.download = 'Sparky-and-the-Lightning-Within-V2.zip';
          a.click();
        }}
        secondaryLabel="Download Version 1"
        onSecondary={() => {
          const a = document.createElement('a');
          a.href = 'assets/sparky/sparky-storybook-v1.zip';
          a.download = 'Sparky-and-the-Lightning-Within-V1.zip';
          a.click();
        }}
      />

      {/* About Sparky */}
      <section style={{ background: NK.white, padding: '72px 0' }}>
        <div className="container" style={{ maxWidth: 760 }}>
          <div className="eyebrow" style={{ color: NK.ink }}>About Sparky</div>
          <h2 className="h2-mobile" style={{ fontSize: 'clamp(28px, 3.4vw, 40px)', fontWeight: 700, color: NK.ink, margin: '14px 0 20px', lineHeight: 1.15 }}>
            Everyone has a spark
          </h2>
          <hr style={{ border: 'none', height: 3, width: 48, background: NK.cobalt, margin: '0 0 24px', borderRadius: 2 }} />
          <p style={{ fontSize: 17, lineHeight: 1.7, color: NK.muted, maxWidth: 620 }}>
            Sparky is the SCN2A Australia mascot, a superhero puppy who reminds every family member that they matter. Whether you are a sibling, a parent, or a carer, Sparky is here to spark hope, understanding, and connection.
          </p>
          <p style={{ fontSize: 17, lineHeight: 1.7, color: NK.muted, maxWidth: 620, marginTop: 16 }}>
            This storybook was created to help young siblings understand what SCN2A means for their brother or sister, and to feel seen and valued in their own right.
          </p>
          <div style={{ marginTop: 28 }}>
            <Button variant="navy" onClick={() => navigate('families')}>
              Resources for families <i data-lucide="arrow-right" style={{ width: 14, height: 14, marginLeft: 4, verticalAlign: '-2px' }} />
            </Button>
          </div>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { SparkyStorybookPage });
