// Animated characters — companion material adapted from the field guide at
// akesha.github.io/aichar (source text: aichar/content/article.md).
// Scene-level pieces (character sheet, test-clip checklist, scene callouts) plus
// the full "Animated characters" section: path cards, workflow recommender,
// low-cost workflow, pipeline, and the course poll.
// Top-level names are prefixed (CH_, Ch, ch) because every text/babel script
// shares one global scope.
const { useState: useStateK, useEffect: useEffectK } = React;

const CH_STORE = {
  get(k) { try { return localStorage.getItem(k); } catch (e) { return null; } },
  set(k, v) { try { localStorage.setItem(k, v); } catch (e) {} },
};

const chExt = (href, children) => <a href={href} target="_blank" rel="noopener">{children}</a>;

/* ============================================================
   SHARED: saved checklist + image hotspots
   ============================================================ */
function useStoredChecks(key, count) {
  const [checks, setChecks] = useStateK(() => {
    try {
      const saved = JSON.parse(CH_STORE.get(key));
      if (Array.isArray(saved) && saved.length === count) return saved;
    } catch (e) {}
    return Array(count).fill(false);
  });
  useEffectK(() => { CH_STORE.set(key, JSON.stringify(checks)); }, [key, checks]);
  const toggle = (i) => setChecks(c => c.map((v, j) => (j === i ? !v : v)));
  return [checks, toggle];
}

function ChChecklist({ storageKey, heading, items, columns = false, bar = false }) {
  const [checks, toggle] = useStoredChecks(storageKey, items.length);
  const done = checks.filter(Boolean).length;
  return (
    <div className="ch-checklist">
      <div className="ch-checklist-head">
        <span>{heading}</span>
        <span className="ch-count">{done} / {items.length}{bar ? ' checked' : ''}</span>
      </div>
      {bar && <div className="ch-bar"><div className="ch-bar-fill" style={{ width: (done / items.length * 100) + '%' }}></div></div>}
      <div className={`ch-checks ${columns ? 'cols' : ''}`}>
        {items.map((label, i) => (
          <div key={label} className={`ch-check ${checks[i] ? 'on' : ''}`}
               role="checkbox" aria-checked={checks[i]} tabIndex={0}
               onClick={() => toggle(i)}
               onKeyDown={(e) => { if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); toggle(i); } }}>
            <span className="ch-box">{checks[i] && <Icon d={Icons.check} size={12} stroke={2.5}/>}</span>
            <span className="ch-check-label">{label}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function ChHotspots({ src, alt, spots }) {
  const [active, setActive] = useStateK(0);
  const cur = spots[active];
  return (
    <figure className="ch-hotspots">
      <div className="ch-hotspot-frame">
        <img src={src} alt={alt} loading="lazy" />
        {spots.map((sp, i) => (
          <button key={sp.t} type="button" className={`ch-spot ${i === active ? 'active' : ''}`}
                  style={{ left: sp.x, top: sp.y }} aria-pressed={i === active}
                  aria-label={`${i + 1}: ${sp.t.toLowerCase()}`} onClick={() => setActive(i)}>
            {i + 1}
          </button>
        ))}
      </div>
      <figcaption className="ch-detail" aria-live="polite">
        <span className="ch-detail-title">{cur.t}</span>
        <span className="ch-detail-desc">{cur.d}</span>
      </figcaption>
    </figure>
  );
}

/* ============================================================
   SCENE 3 — character-reference sheet
   ============================================================ */
const CH_SHEET_SPOTS = [
  { x: '10%', y: '46%', t: 'FRONT VIEW', d: 'The anchor image. Clear, evenly lit, full outfit visible — most platforms weight this reference heaviest.' },
  { x: '31%', y: '42%', t: 'THREE-QUARTER VIEW', d: 'The most common camera angle in generated video. Locks how the face reads between front and profile.' },
  { x: '48%', y: '42%', t: 'PROFILE', d: 'Defines the nose, jaw, and hairline silhouette — the first thing to drift when a model has not seen one.' },
  { x: '66%', y: '42%', t: 'BACK VIEW', d: 'Establishes hair volume and how the outfit reads from behind, for walking and turning shots.' },
  { x: '88%', y: '40%', t: 'EXPRESSIONS', d: 'Two or three useful expressions keep the face on-model when the character emotes.' },
  { x: '5%', y: '20%', t: 'PALETTE + NOTES', d: 'Skin tone, hair texture, established outfit colors, proportions, and recurring accessories — written down, not remembered.' },
];

const CH_SHEET_ITEMS = [
  'A clear front view', 'A three-quarter view', 'A profile', 'A full-body view',
  'Two or three useful expressions', 'One established outfit', 'Height and body-proportion notes',
  'Hairstyle and hair texture', 'Skin tone', 'Distinguishing facial features', 'Recurring accessories or props',
];

function CharacterSheet() {
  return (
    <div className="ch-block">
      <div className="ch-kicker">For recurring characters</div>
      <h3 className="ch-h3">Lock the look with a character-reference sheet</h3>
      <p>
        Your cast block locks each character in words. For a character who recurs across
        many beats, or who will speak or perform on camera, lock them in pictures too &mdash;
        the animation platform cannot rescue an inconsistent character design. Tap the
        markers to see what each part of a sheet is for.
      </p>
      <ChHotspots
        src="assets/character-sheet.jpg"
        alt="Character-reference sheet: front, three-quarter, profile and back views plus expressions"
        spots={CH_SHEET_SPOTS}
      />
      <div className="ch-sheet-row">
        <ChChecklist storageKey="avg.charsheet.v1" heading="Your sheet · tick what you have" items={CH_SHEET_ITEMS} />
        <div className="ch-notes">
          <div className="ch-note">
            <div className="ch-note-title">Keep it consistent</div>
            <p>
              Keep lighting, proportions, clothing, and visual style consistent across every
              reference image. Google&rsquo;s Nano Banana 2 (in the Gemini app) supports multiple
              reference images and is built to hold a character&rsquo;s appearance. ChatGPT Images
              and Midjourney also work for creating and revising the sheet.
            </p>
          </div>
          <div className="ch-note">
            <div className="ch-note-title">Same idea, different names</div>
            <p>
              Runway calls them <em>references</em>, Kling calls them <em>Elements</em>, LTX Studio
              uses <em>Elements and reference controls</em>, and Google may use <em>ingredients</em> or
              reference images. The idea is identical: give the model approved images to follow
              instead of letting it invent a new face, hairstyle, or outfit per clip.
            </p>
          </div>
        </div>
      </div>
      <p className="ch-foot">
        Keep the sheet and the cast block describing the same person &mdash; same outfit, same
        hair &mdash; and bring the strongest view into Scene 4 as that character&rsquo;s reference image.
      </p>
    </div>
  );
}

/* ============================================================
   SCENE 4 — polish the reference
   ============================================================ */
function ChPolishCallout() {
  return (
    <div className="callout">
      <div className="callout-icon"><Icon d={Icons.sparkle} size={20}/></div>
      <div className="callout-body">
        <div className="callout-label">Polish the reference, don&rsquo;t regenerate it</div>
        <p>
          A weak reference image often produces a weak animation. If your approved character
          image is soft, compressed, or too small, sharpen it with {chExt('https://www.magnific.com', 'Magnific')}&rsquo;s
          Image Upscaler before you upload it. Improving an approved image is often safer than
          creating a new one &mdash; every regeneration from scratch is another chance for the face to change.
        </p>
        <div className="ch-dial">
          <div><span>Creativity &uarr;</span>Invents additional detail.</div>
          <div><span>Resemblance &uarr;</span>Keeps the result closer to the original.</div>
        </div>
        <p>
          For a recurring character &mdash; or especially a real person &mdash; start conservatively.
          An image can look technically sharper while quietly changing the eyes, nose, mouth,
          face shape, hairline, or skin texture.
        </p>
      </div>
    </div>
  );
}

/* ============================================================
   SCENE 6 — test clip + when to reach for a specialist
   ============================================================ */
const CH_TEST_ITEMS = ['Facial identity', 'Skin tone', 'Eyes and mouth', 'Hands', 'Hairstyle', 'Clothing', 'Background', 'Lip-sync', 'Body proportions', 'Camera movement'];

function TestClipCheck() {
  return (
    <div className="ch-block">
      <div className="ch-kicker">Before you animate every beat</div>
      <h3 className="ch-h3">Don&rsquo;t start with 30 seconds</h3>
      <p>
        Generate a three- to five-second test first, and check every item against your
        approved storyboard and reference images. A clip can look impressive at first glance
        and still break continuity once it&rsquo;s placed beside the next shot.
      </p>
      <ChChecklist storageKey="avg.testclip.v1" heading="Test clip · check every item" items={CH_TEST_ITEMS} columns bar />
    </div>
  );
}

function ChAnimatorCallout() {
  return (
    <div className="callout">
      <div className="callout-icon"><Icon d={Icons.motion} size={20}/></div>
      <div className="callout-body">
        <div className="callout-label">When a shot needs a specialist</div>
        <p>This workflow keeps every beat in Runway Agent. Some shots call for a different tool:</p>
        <ul className="ch-ticks">
          <li><strong>Runway Act-Two</strong> when you want your own recorded performance &mdash; expressions, speech, gestures, body movement &mdash; transferred onto the character. Clips up to 30 seconds; requires a Runway Standard plan or higher.</li>
          <li><strong>Kling AI or Google Veo</strong> for strong individual cinematic shots: walking into a room, reacting to another character, establishing shots.</li>
          <li><strong>LTX Studio</strong> when holding one character, environment, lighting style, and voice across several connected shots matters more than any single clip.</li>
        </ul>
        <p>A production can mix them. <a href="#characters">Compare the options in Animated characters &rarr;</a></p>
      </div>
    </div>
  );
}

/* ============================================================
   SCENE 7 — on-camera talking characters
   ============================================================ */
function ChTalkingCallout() {
  return (
    <div className="callout">
      <div className="callout-icon"><Icon d={Icons.face} size={20}/></div>
      <div className="callout-body">
        <div className="callout-label">If your character talks on camera</div>
        <p>
          This scene assumes narration laid over the visuals. If a character speaks directly
          to the camera instead, you need lip-sync, which means a talking-character tool:
        </p>
        <ul className="ch-ticks">
          <li><strong>{chExt('https://www.hedra.com', 'Hedra')}</strong> animates a character image from recorded or generated speech &mdash; strongest for facial performance driven by an existing audio track.</li>
          <li><strong>{chExt('https://elevenlabs.io/avatars', 'ElevenLabs Avatars')}</strong> combines voice generation, a reusable character built from reference images, and lip-sync in one subscription.</li>
          <li><strong>{chExt('https://www.descript.com', 'Descript')}</strong> puts stock or custom AI avatars inside a transcript-based editor, so you generate and edit the talking shot in one project.</li>
        </ul>
        <p>
          Lip-sync works best when the face is clearly visible in a close or medium shot. See
          {' '}<a href="#watch">where it tends to go sideways</a> for what breaks it.
        </p>
      </div>
    </div>
  );
}

/* ============================================================
   SCENE 8 — polish only the keepers
   ============================================================ */
function ChFlow() {
  const steps = ['generate', 'choose the best take', 'fix continuity problems', 'upscale', 'edit / export'];
  return (
    <div className="ch-flow" aria-label="A sensible order">
      {steps.map((s, i) => (
        <React.Fragment key={s}>
          {i > 0 && <span className="ch-flow-arrow">&rarr;</span>}
          <span className={`ch-flow-step ${s === 'upscale' ? 'on' : ''}`}>{s}</span>
        </React.Fragment>
      ))}
    </div>
  );
}

function ChKeepersCallout() {
  return (
    <div className="callout coral">
      <div className="callout-icon"><Icon d={Icons.sparkle} size={20}/></div>
      <div className="callout-body">
        <div className="callout-label">Polish only the keepers</div>
        <p>
          If a clip you&rsquo;re keeping looks soft next to the others, Magnific&rsquo;s Video Upscaler
          can take generated footage up to Ultra HD 4K. Don&rsquo;t upscale every experimental
          generation &mdash; save it for the shots that make the cut.
        </p>
        <ChFlow />
        <p>
          If narration or dialogue drives most of your edit, <strong>Descript</strong> lets you cut
          the video by editing its transcript, and handles captions and audio cleanup.
        </p>
      </div>
    </div>
  );
}

/* ============================================================
   ANIMATED CHARACTERS SECTION — path panels
   ============================================================ */
function ChTool({ name, price, children, best }) {
  return (
    <div className="ch-tool">
      <div className="ch-tool-head">
        <span className="ch-tool-name">{name}</span>
        {price && <span className="ch-price">{price}</span>}
      </div>
      {children}
      {best && <div className="ch-best">Best for · {best}</div>}
    </div>
  );
}

function ChTalkPanel() {
  return (
    <>
      <p>Use a talking-character or avatar tool &mdash; for narrators, interview-style scenes, instructional videos, and characters speaking directly to the camera.</p>
      <div className="ch-tools">
        <ChTool name="Hedra" price="Basic from $15/mo" best="facial performance driven by an existing audio track">
          <p>Animates a character image using recorded or generated speech. Free to start experimenting; review current pricing before subscribing.</p>
        </ChTool>
        <ChTool name="ElevenLabs Avatars" price="from $6/mo" best="voice + reusable character + lip-sync in one subscription">
          <p>Voice generation and lip-sync in one platform. Create a persistent character identity from reference images, select or generate a voice, and produce variations with different angles, clothing, and backgrounds. Available through paid ElevenCreative plans.</p>
        </ChTool>
        <ChTool name="Descript" price="$24/mo · $16 annual" best="a talking avatar + transcript editing in one app">
          <p>Stock and custom AI avatars, text-to-speech, voice cloning, and generated video &mdash; inside a complete transcript-based editor. Generate or import a talking character, then edit dialogue, captions, audio, visuals, and pacing in the same project. Free plan with limited media time and AI features.</p>
        </ChTool>
      </div>
    </>
  );
}

function ChPerformPanel() {
  return (
    <div className="ch-tool ch-tool-wide">
      <div className="ch-tool-head">
        <span className="ch-tool-name">Runway Act-Two</span>
        <span className="ch-price">Standard $15/mo · $12 annual</span>
      </div>
      <p>Record yourself performing the scene, then provide an image or video of the character. Act-Two transfers your expressions, speech, gestures, and body movement onto that character.</p>
      <p>This is different from ordinary image-to-video generation because your recorded performance controls what the character does. Raise your hand, lean forward, pause, or change your expression, and the character can reproduce it.</p>
      <div className="ch-specs">
        <div><span>Clip length</span>up to 30 seconds</div>
        <div><span>Cost</span>5 credits / second · 3s minimum</div>
        <div><span>Requires</span>Runway Standard plan or higher</div>
        <div><span>Free account</span>125 one-time credits for selected tools — not Act-Two</div>
      </div>
    </div>
  );
}

const CH_LTX_ROWS = [
  ['Talking head or narrator', 'Hedra or ElevenLabs remains more specialized', false],
  ['Precise actor-driven performance', 'Runway Act-Two remains the clearer choice', false],
  ['Character moving through scenes', 'LTX competes directly with Runway, Kling, and Veo', true],
  ['Character consistency', 'LTX Elements and reference controls can help preserve characters, locations, and objects', true],
  ['Storyboarding', 'LTX can turn a script or concept into scenes and a dynamic storyboard', true],
  ['Multi-shot sequences', 'LTX-2.5 can generate connected wide, medium, and close-up shots while attempting to maintain character, setting, lighting, and voice', true],
  ['Editing generated shots', 'LTX provides keyframes, camera controls, selective editing, retakes, sound design, and a timeline', true],
  ['Transcript-led editing', 'Descript remains the better specialist', false],
  ['Production planning and review', 'ChatGPT Work remains useful for scripting, shot planning, prompt development, continuity analysis, and coordinating assets', false],
];

function ChMovePanel() {
  return (
    <>
      <p>Use a cinematic image-to-video or scene-building platform: <strong>Runway, Kling AI, Google Veo, or LTX Studio</strong>. They&rsquo;re better for physical action &mdash; but not necessarily best for extended dialogue.</p>
      <div className="ch-chips">
        {['Walking into a room', 'Picking up an object', 'Reacting to another character', 'Moving through an environment', 'Changing camera angles', 'Establishing shots', 'Transitions between scenes', 'Keeping a character across connected shots'].map(c => <span key={c}>{c}</span>)}
      </div>
      <div className="ch-aside">A production may mix models: use Kling, Veo, Runway, or LTX to show a character entering an office, then switch to Hedra, ElevenLabs, or Descript for the dialogue-heavy close-up.</div>

      <h4 className="ch-subhead">Where LTX fits</h4>
      <p>LTX may be one of the strongest middle-ground options between a single-purpose generator and a conventional video editor. It&rsquo;s designed around the <em>scene or sequence</em>, not merely the individual clip &mdash; so it matters most when the challenge is holding one character, environment, lighting style, and voice across several related shots.</p>
      <div className="ch-tools">
        <ChTool name="LTX-2.5" price="the model">
          <p>The underlying video-generation model, available through an API, open weights, or local deployment. Emphasizes native multi-shot generation &mdash; connected wide, medium, and close-up shots &mdash; and synchronized audio-video.</p>
        </ChTool>
        <ChTool name="LTX Studio" price="the app">
          <p>The creator-facing application most filmmakers, educators, and creators would actually use: text-, image-, and video-to-video, reference Elements, dynamic storyboarding, camera control, keyframes, sound design, selective editing, retakes, and a timeline.</p>
        </ChTool>
      </div>
      <div className="ch-table-wrap">
        <table className="ch-table">
          <thead><tr><th>Production need</th><th>Best fit / LTX&rsquo;s role</th></tr></thead>
          <tbody>
            {CH_LTX_ROWS.map(([need, fit, hl]) => (
              <tr key={need} className={hl ? 'hl' : ''}><td>{need}</td><td>{fit}</td></tr>
            ))}
          </tbody>
        </table>
      </div>
      <p className="ch-small"><b>LTX Studio pricing</b> Free plan with 800 one-time credits, personal use only. Lite $15/mo, Standard $35/mo, Pro $125/mo, lower when billed annually. Standard adds commercial-use licensing, consistent Elements, AI storyboards, and more generation models &mdash; check current terms before using it for monetized courses, YouTube channels, client projects, or business content.</p>
      <div className="ch-aside">Also worth knowing: <strong>Magnific</strong> is now a broader creative platform that gives you access to multiple image, video, and audio models &mdash; including tools from Runway, Google, Kling, and others &mdash; plus editing and enhancement. If you&rsquo;d rather work in one interface than juggle several subscriptions, it can act as a multi-model production hub. It doesn&rsquo;t replace Act-Two, Hedra, or LTX&rsquo;s sequence workflow; it gives you one place to experiment and refine assets before they reach your editor.</div>
    </>
  );
}

function ChPolishPanel() {
  return (
    <>
      <p>Use <strong>Magnific</strong> when the problem isn&rsquo;t animation but visual quality. It began as a well-known creative upscaler; Freepik has since been rebranded as Magnific, and the platform now combines image and video generation, image and video editing, audio tools, stock assets, collaborative workflows, and multiple third-party models. (Legacy upscaler subscriptions can remain at magnific.ai; the broader platform lives at magnific.com.)</p>
      <div className="ch-tools">
        <div className="ch-tool">
          <div className="ch-step-n">01 · Before animation</div>
          <div className="ch-tool-name">Prepare the reference image</div>
          <p>A weak reference image often produces a weak animation. The Image Upscaler sharpens and enlarges a reference before you send it to Hedra, Runway, Kling, or another video tool. It helps when the source has:</p>
          <ul className="ch-ticks ch-ticks-sm">
            {['Soft facial detail', 'Compression artifacts', 'Low resolution', 'Weak hair or fabric texture', 'Slightly muddy eyes or skin detail', 'A background that needs cleanup'].map(t => <li key={t}>{t}</li>)}
          </ul>
        </div>
        <div className="ch-tool">
          <div className="ch-step-n">02 · Between generations</div>
          <div className="ch-tool-name">Repair or refine assets</div>
          <p>Editing, retouching, background removal, expansion, and reimagining help when a generated still is almost right. For example:</p>
          <ol className="ch-mini-steps">
            <li>Generate the character in ChatGPT Images, Gemini, or Midjourney.</li>
            <li>Use Magnific to improve resolution and facial detail.</li>
            <li>Approve that polished image as the canonical reference.</li>
            <li>Use the same reference across Runway, Kling, Hedra, or Veo.</li>
          </ol>
          <p>Every regeneration from scratch is another chance for the face to change. Improving an approved image is often safer.</p>
        </div>
        <div className="ch-tool">
          <div className="ch-step-n">03 · After animation</div>
          <div className="ch-tool-name">Upscale the finished clip</div>
          <p>The Video Upscaler can take generated footage up to Ultra HD 4K &mdash; useful once you&rsquo;ve already picked the winning take.</p>
          <p>Don&rsquo;t upscale every experimental generation. Video generation is already expensive, and enhancement adds another processing step. Save it for the shots you&rsquo;ll actually use.</p>
        </div>
      </div>
      <ChFlow />
      <div className="ch-tools">
        <div className="ch-note">
          <div className="ch-note-title">Reach for Magnific when you&rsquo;re asking&hellip;</div>
          <ul className="ch-quotes">
            <li>&ldquo;Can I make this reference image cleaner without rebuilding it?&rdquo;</li>
            <li>&ldquo;Can I get more usable detail from this generated image?&rdquo;</li>
            <li>&ldquo;Can I upscale the final AI clip?&rdquo;</li>
            <li>&ldquo;Can I access several image/video models from one creative platform?&rdquo;</li>
          </ul>
        </div>
        <div className="ch-note">
          <div className="ch-note-title">&hellip;but not first for these</div>
          <p>Performance capture or long talking-character scenes are more direct in Runway Act-Two, Hedra, ElevenLabs Avatars, or Descript. Think of Magnific as a quality-control and multi-model production layer <em>around</em> those tools.</p>
          <p className="ch-small">Premium from $20/mo, lower billed annually. Higher tiers add credits, more upscalers, and unlimited-model allowances.</p>
        </div>
      </div>
    </>
  );
}

const CH_GPT_TASKS = ['Rewrite and time the script', 'Create a storyboard', 'Build a shot list', 'Write prompts for each generated scene', 'Create character-reference images', 'Track clothing, props, locations, and continuity', 'Extract frames from video clips', 'Create contact sheets to compare shots', 'Identify facial, wardrobe, lighting, or continuity problems', 'Compare alternate takes', 'Recommend precise cuts using timestamps', 'Create an edit-decision list', 'Trim, reorder, and combine clips', 'Reframe for 16:9, 9:16, or square', 'Add stills, title cards, captions, simple transitions', 'Replace, extract, sync, or adjust audio', 'Compress and convert video files', 'Render a rough cut when media tools are available'];
const CH_DESCRIPT_EXTRAS = ['Generate and style captions', 'Remove filler words and repeated takes', 'Shorten long pauses', 'Improve audio with Studio Sound', 'Remove backgrounds without a green screen', 'Adjust eye contact', 'Generate or repair short sections of speech', 'Create clips and highlights', 'Add stock footage, images, music, transitions', 'Generate show notes, chapters, summaries, YouTube descriptions', 'Generate images and video with AI tools', 'Create videos with stock or custom AI avatars'];

function ChEditPanel() {
  return (
    <>
      <div className="ch-tools">
        <div className="ch-tool">
          <div className="ch-tool-name">ChatGPT Work</div>
          <div className="ch-step-n">AI producer + assistant editor</div>
          <p>Not a character-animation model like Hedra or Runway. It coordinates the production: upload your script, character images, audio, clips, and music, and it works with those files, creates supporting assets, analyzes results, and &mdash; when the necessary media tools are available &mdash; performs many of the technical editing tasks.</p>
          <details className="ch-more">
            <summary>What it can help with · {CH_GPT_TASKS.length} tasks</summary>
            <ul className="ch-ticks ch-ticks-sm">{CH_GPT_TASKS.map(t => <li key={t}>{t}</li>)}</ul>
          </details>
          <p className="ch-small">In the ChatGPT desktop app, Computer Use can also see and operate approved desktop applications &mdash; which may let it help with repetitive tasks inside video editors, depending on your computer, permissions, and software. It&rsquo;s an AI producer and assistant editor that can sometimes complete the technical edit, not a replacement for every advanced feature in Premiere or DaVinci Resolve.</p>
        </div>
        <div className="ch-tool">
          <div className="ch-tool-name">Descript</div>
          <div className="ch-step-n">Transcript-based editor</div>
          <p>Use it when the spoken words determine most of your editing decisions. Delete a sentence from the transcript and the matching audio and video disappear.</p>
          <div className="ch-chips ch-chips-sm">
            {['YouTube explainers', 'Educational videos', 'Interviews', 'Podcasts', 'Screen-recorded tutorials', 'Narrated presentations', 'Multiple takes', 'Shorts & social clips'].map(c => <span key={c}>{c}</span>)}
          </div>
          <details className="ch-more">
            <summary>Also does · {CH_DESCRIPT_EXTRAS.length} things</summary>
            <ul className="ch-ticks ch-ticks-sm">{CH_DESCRIPT_EXTRAS.map(t => <li key={t}>{t}</li>)}</ul>
          </details>
          <p className="ch-small">Includes <strong>Underlord</strong>, an AI video co-editor that performs editing, design, and repurposing tasks from written instructions.</p>
        </div>
      </div>
      <div className="ch-aside">They overlap, but aren&rsquo;t interchangeable: use <strong>ChatGPT Work</strong> to manage the whole production &mdash; script, reference images, prompts, continuity, footage review, media processing, rough cut. Use <strong>Descript</strong> to edit speech-heavy footage through its transcript inside a dedicated editor.</div>

      <h4 className="ch-subhead">Where LTX fits in end-to-end production</h4>
      <p>LTX Studio lets more of the production happen in one place: develop scenes, build a dynamic storyboard, establish characters and locations with Elements, generate connected shots, adjust camera and keyframes, retake or selectively edit, add sound design, and arrange it all on a timeline.</p>
      <div className="ch-spectrum">
        <div><span>Single-purpose generator</span>Can create an excellent individual clip, but expects you to organize the larger sequence elsewhere.</div>
        <div className="mid"><span>LTX Studio</span>Fills the space between &mdash; fewer handoffs when your project is a narrative sequence, not a pile of unrelated clips.</div>
        <div><span>Conventional editor</span>Detailed timeline control, but usually expects the footage to exist before you begin.</div>
      </div>
      <p>LTX doesn&rsquo;t replace the specialists: Hedra and ElevenLabs stay more direct for talking characters, Act-Two for actor-driven performance, Descript for transcript-led editing, and ChatGPT Work for scripting, prompts, continuity review, and coordination.</p>
      <div className="ch-note">
        <div className="ch-note-title">A combined workflow</div>
        <ol className="ch-mini-steps">
          <li>Develop the script, storyboard, character sheet, and shot list in <strong>ChatGPT Work</strong>.</li>
          <li>If the project is sequence-driven, use <strong>LTX Studio</strong> to turn the script into scenes, a dynamic storyboard, and connected generations.</li>
          <li>Generate specialized character shots in Hedra, ElevenLabs, Descript, Runway Act-Two, Kling, Veo, or LTX as appropriate.</li>
          <li>Bring the clips back to <strong>ChatGPT Work</strong> for continuity review and technical preparation.</li>
          <li>Assemble dialogue-heavy footage in <strong>Descript</strong> by editing the transcript.</li>
          <li>Use Descript for captions, audio cleanup, filler-word removal, and social clips.</li>
          <li>Use <strong>Magnific</strong> for selective image cleanup or final video upscaling when needed.</li>
          <li>Move to CapCut, DaVinci Resolve, Final Cut Pro, or Premiere only for sophisticated effects, color, compositing, or timeline control.</li>
        </ol>
      </div>
    </>
  );
}

const CH_PATHS = [
  { id: 'talk', img: 'assets/talk.jpg', alt: 'Character speaking into a microphone with lip-sync mouth shapes', title: 'My character needs to talk', desc: 'Narration, dialogue to camera, lip-sync', Panel: ChTalkPanel },
  { id: 'perform', img: 'assets/perform.jpg', alt: 'A real person and her animated double mirroring the same gesture', title: 'My character needs to copy a performance', desc: 'Your acting transferred to the character', Panel: ChPerformPanel },
  { id: 'move', img: 'assets/move.jpg', alt: 'Character walking through an office with a camera path', title: 'My character needs cinematic movement', desc: 'Walking, reacting, connected scenes', Panel: ChMovePanel },
  { id: 'polish', art: true, title: 'My image or video needs polishing', desc: 'Clean up references, upscale final clips', Panel: ChPolishPanel },
  { id: 'edit', img: 'assets/edit.jpg', alt: 'An editor assembling character clips on a timeline', title: 'I need to plan and edit the video', desc: 'Production, rough cuts, transcripts, captions', Panel: ChEditPanel },
];

const CH_JOBS = [
  ['Design', 'A consistent character'],
  ['Animate', 'The character itself'],
  ['Voice', 'Speech and lip-sync'],
  ['Polish', 'Enhance, repair, or upscale'],
  ['Edit', 'Clips into a finished video'],
];

/* ============================================================
   WORKFLOW RECOMMENDER
   ============================================================ */
const CH_REC_QUESTIONS = [
  { key: 'dialogue', title: 'How much dialogue?', options: ['Lots of talking', 'A little', 'None'] },
  { key: 'perform', title: 'Transfer your own acting?', options: ['Yes, I will act it out', 'No'] },
  { key: 'move', title: 'Cinematic movement?', options: ['Yes, full scenes', 'No, mostly close-ups'] },
  { key: 'scenes', title: 'How many connected scenes?', options: ['One or two standalone shots', 'Several connected scenes'] },
  { key: 'budget', title: 'Budget?', options: ['Minimal', 'Moderate', 'Flexible'] },
];

// Same rules as the field guide's recommender. `brand` (optional) is the name
// shown in the headline when the tool label is more specific.
function chRecommend(r) {
  const lines = [];
  const connected = r.scenes === 'Several connected scenes';
  const moving = r.move === 'Yes, full scenes';
  lines.push({ role: 'Plan + continuity', tool: 'ChatGPT Work', why: 'script, storyboard, shot list, prompts, continuity review, rough-cut prep.' });
  lines.push({ role: 'Character sheet', tool: r.budget === 'Minimal' ? 'Gemini (Nano Banana 2)' : 'ChatGPT Images or Midjourney', why: 'a consistent reference sheet before any animation.' });
  if (r.budget !== 'Minimal') {
    lines.push({ role: 'Reference polish', tool: 'Magnific Image Upscaler', brand: 'Magnific', why: 'sharpen the approved reference instead of regenerating it — keep Creativity low so the face does not drift.' });
  }
  if (connected) {
    lines.push({
      role: 'Storyboard + sequence', tool: 'LTX Studio',
      why: moving ? 'dynamic storyboard, Elements for your character and locations, and connected multi-shot movement in one workspace.' : 'dynamic storyboard and Elements to hold your character and locations across connected shots.',
    });
  }
  if (r.dialogue !== 'None') {
    const descriptAvatars = r.budget !== 'Minimal' && r.dialogue === 'Lots of talking';
    lines.push({
      role: 'Talking shots',
      brand: descriptAvatars ? 'Descript' : undefined,
      tool: r.budget === 'Minimal' ? 'ElevenLabs Avatars' : (descriptAvatars ? 'Descript AI Avatars' : 'Hedra'),
      why: r.budget === 'Minimal' ? 'voice + lip-sync in one, cheapest entry point.' : (r.dialogue === 'Lots of talking' ? 'talking avatar inside the same editor you will cut in.' : 'strong audio-driven facial performance.'),
    });
  }
  if (r.perform === 'Yes, I will act it out') lines.push({ role: 'Performance', tool: 'Runway Act-Two', why: 'transfers your recorded expressions, gestures, and movement onto the character.' });
  if (moving && !connected) lines.push({ role: 'Movement + scenes', tool: r.budget === 'Flexible' ? 'Runway or Google Veo' : 'Kling AI', why: 'walking, reactions, establishing shots, and transitions.' });
  lines.push({ role: 'Edit + finish', tool: r.dialogue === 'None' ? 'CapCut or DaVinci Resolve' : 'Descript', why: r.dialogue === 'None' ? 'timeline editing for visuals-first footage.' : 'transcript-based editing, captions, filler-word removal, audio cleanup.' });
  if (r.budget === 'Flexible') {
    lines.push({ role: 'Final upscale', tool: 'Magnific Video Upscaler', brand: 'Magnific', why: 'up to 4K — only on the takes you keep, not every test generation.' });
  }
  return lines;
}

function ChRecommender() {
  const [answers, setAnswers] = useStateK({});
  const total = CH_REC_QUESTIONS.length;
  const answered = CH_REC_QUESTIONS.filter(q => answers[q.key]).length;
  const ready = answered === total;
  const lines = ready ? chRecommend(answers) : [];
  const headline = lines
    .map(l => l.brand || l.tool.split(' or ')[0].split(' (')[0])
    .filter((v, i, a) => a.indexOf(v) === i)
    .join(' + ');
  return (
    <div className="ch-rec">
      <div className="ch-kicker">02 · Workflow builder</div>
      <h3>Build your workflow</h3>
      <p className="ch-rec-intro">Answer five questions and get a personalized tool stack.</p>
      <div className="ch-rec-questions">
        {CH_REC_QUESTIONS.map(q => (
          <div key={q.key} role="group" aria-label={q.title}>
            <div className="ch-rec-q">{q.title}</div>
            <div className="ch-rec-opts">
              {q.options.map(opt => (
                <button key={opt} type="button" aria-pressed={answers[q.key] === opt}
                        className={`ch-rec-opt ${answers[q.key] === opt ? 'selected' : ''}`}
                        onClick={() => setAnswers(a => ({ ...a, [q.key]: opt }))}>
                  {opt}
                </button>
              ))}
            </div>
          </div>
        ))}
      </div>
      {!ready && <div className="ch-rec-progress">{answered} of {total} answered — your stack appears here.</div>}
      {ready && (
        // Keyed on the answers so the fade replays whenever the stack changes.
        <div className="ch-rec-result" key={JSON.stringify(answers)} aria-live="polite">
          <div className="ch-rec-label">Your recommended stack</div>
          <div className="ch-rec-headline">{headline}</div>
          <div className="ch-rec-lines">
            {lines.map(l => (
              <div key={l.role} className="ch-rec-line">
                <span className="ch-rec-role">{l.role}</span>
                <span className="ch-rec-why"><strong>{l.tool}</strong> &mdash; {l.why}</span>
              </div>
            ))}
          </div>
          <div className="ch-rec-note">Start with one animation platform and one editing platform. Add another only when your tools can&rsquo;t produce a particular shot or finish.</div>
        </div>
      )}
    </div>
  );
}

/* ============================================================
   LOW-COST WORKFLOW + PIPELINE
   ============================================================ */
const CH_LOW_COST = [
  [false, <>Develop the script and storyboard with <strong>ChatGPT Work, Gemini, or Claude</strong>.</>],
  [false, <>Create the character sheet using <strong>ChatGPT Images, Gemini, or Midjourney</strong>.</>],
  [true, <>the approved character image is soft, compressed, or too small, refine it with <strong>Magnific Image Upscaler</strong> before using it as the animation reference.</>],
  [false, <>Use <strong>ChatGPT Work</strong> to turn the script into a shot list and write a separate animation prompt for each shot.</>],
  [false, <>Test one short scene using the free credits or trial allowance on your chosen video platform.</>],
  [true, <>the character mainly talks, try <strong>Hedra, ElevenLabs Avatars, or Descript</strong>.</>],
  [true, <>it needs to reproduce a physical performance, try <strong>Runway Act-Two</strong>.</>],
  [true, <>it needs cinematic movement, test <strong>Runway, Kling AI, Google Veo, or LTX Studio</strong>. Choose LTX when storyboard-to-sequence continuity matters more than one isolated shot at a time.</>],
  [true, <>the project has several connected scenes, consider building the storyboard, character/location Elements, multi-shot sequences, camera moves, and rough timeline directly in <strong>LTX Studio</strong>.</>],
  [false, <>Bring the clips back into <strong>ChatGPT Work</strong> for continuity review, shot comparison, trimming, reframing, or rough-cut assembly.</>],
  [false, <>Once you&rsquo;ve chosen the shots you&rsquo;ll actually use, consider <strong>Magnific</strong> for image cleanup or final upscaling &mdash; not on every test generation.</>],
  [false, <>For dialogue-heavy editing, captions, audio cleanup, and social clips, use <strong>Descript</strong>.</>],
  [false, <>For advanced effects, color, compositing, or detailed timeline work, use <strong>CapCut, DaVinci Resolve, Camtasia, Final Cut Pro, or Adobe Premiere</strong>.</>],
];

const CH_SHORTHAND = [
  ['Hedra', 'Make one character talk convincingly.'],
  ['ElevenLabs Avatars', 'Combine a reusable character with generated voice and lip-sync.'],
  ['Runway Act-Two', 'Transfer a specific human performance.'],
  ['Kling or Veo', 'Generate strong individual cinematic shots.'],
  ['LTX Studio', 'Develop a storyboard and produce connected, consistent scenes in one workspace.'],
  ['Magnific', 'Clean up references, upscale final clips, and reach several models from one platform.'],
  ['Descript', 'Edit narration, dialogue, captions, audio, and speaking videos through the transcript.'],
  ['ChatGPT Work', 'Coordinate the production, develop prompts, inspect continuity, compare takes, and plan or assemble the edit.'],
];

const CH_PIPELINE = [
  ['Writing, planning, storyboarding', 'ChatGPT Work · Gemini · Claude'],
  ['Character sheets & reference images', 'ChatGPT Images · Gemini · Midjourney'],
  ['Reference-image cleanup & upscaling', 'Magnific Image Upscaler'],
  ['Talking characters', 'Hedra · ElevenLabs Avatars · Descript AI Avatars'],
  ['Performance transfer', 'Runway Act-Two'],
  ['General movement & transitions', 'Runway · Kling AI · Google Veo · LTX Studio'],
  ['Storyboard-to-sequence & multi-shot continuity', 'LTX Studio (powered by LTX-2.5)'],
  ['Multi-model generation hub', 'Magnific — several image/video/audio models + editing in one workspace'],
  ['Voiceovers', 'ElevenLabs · Descript · licensed voice services'],
  ['Original music', 'ElevenLabs Music · Suno · licensed music services'],
  ['Footage analysis, continuity review & prep', 'ChatGPT Work'],
  ['Transcript editing, captions, audio cleanup', 'Descript'],
  ['AI-assisted editing & repurposing', 'Descript Underlord'],
  ['Final image/video enhancement & upscaling', 'Magnific'],
  ['Manual finishing & advanced timelines', 'CapCut · DaVinci Resolve · Camtasia · Final Cut Pro · Premiere'],
];

/* ============================================================
   COURSE POLL — shares the aichar-poll Worker and its per-browser id
   (same akesha.github.io origin, so a visitor who voted on the field
   guide updates the same vote here instead of adding a second one).
   ============================================================ */
const CH_POLL_API = 'https://aichar-poll.akesha.workers.dev';
const CH_TOPICS = ['Creating the initial character', 'Maintaining consistency across scenes', 'Animating dialogue', 'Transferring a physical performance', 'Editing the completed video', 'Building the entire workflow from beginning to end'];
const CH_FORMATS = ['Short live workshop', 'Self-paced mini-course', 'Comprehensive course with templates'];
const CH_RENAMED = { 'The entire workflow, end to end': 'Building the entire workflow from beginning to end' };

function chPollSid() {
  let sid = CH_STORE.get('aichar-sid');
  if (!sid) {
    sid = crypto.randomUUID ? crypto.randomUUID() : Date.now().toString(36) + Math.random().toString(36).slice(2, 12);
    CH_STORE.set('aichar-sid', sid);
  }
  return sid;
}

function ChCoursePoll() {
  const [poll, setPoll] = useStateK(() => {
    let topic = CH_STORE.get('aichar-topic');
    if (CH_RENAMED[topic]) { topic = CH_RENAMED[topic]; CH_STORE.set('aichar-topic', topic); }
    return { topic, format: CH_STORE.get('aichar-format') };
  });
  const [tally, setTally] = useStateK(null);
  const [chip, setChip] = useStateK('');

  // Returning visitors see their earlier answers with current results.
  useEffectK(() => {
    if (!poll.topic && !poll.format) return;
    setChip('✓ Your answer is saved — ' + [poll.topic, poll.format].filter(Boolean).join(' · '));
    fetch(CH_POLL_API + '/results').then(r => (r.ok ? r.json() : null)).then(t => { if (t) setTally(t); }).catch(() => {});
  }, []);

  const vote = async (key, label) => {
    const prev = poll[key];
    const next = { ...poll, [key]: label };
    setPoll(next);
    setChip('Saving…');
    try {
      const res = await fetch(CH_POLL_API + '/vote', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sid: chPollSid(), [key]: label }),
      });
      if (!res.ok) throw new Error(String(res.status));
      const t = await res.json();
      setTally(t);
      CH_STORE.set('aichar-' + key, label);
      const others = t.total - 1;
      setChip('✓ Saved — ' + [next.topic, next.format].filter(Boolean).join(' · ') +
        (others > 0 ? ` (you and ${others} other${others === 1 ? '' : 's'} have answered)` : ''));
    } catch (e) {
      setPoll(p => ({ ...p, [key]: prev }));
      setChip("Couldn't save your answer — please try again.");
    }
  };

  // Everyone's split shows only after this visitor has answered the question.
  const pct = (key, label) => {
    const counts = tally && tally[key];
    const sum = counts ? Object.values(counts).reduce((a, b) => a + b, 0) : 0;
    return poll[key] && sum ? ' · ' + Math.round((counts[label] || 0) / sum * 100) + '%' : '';
  };

  const pills = (key, labels) => (
    <div className="ch-pills">
      {labels.map(label => (
        <button key={label} type="button" aria-pressed={poll[key] === label}
                className={`ch-pill ${poll[key] === label ? 'selected' : ''}`}
                onClick={() => vote(key, label)}>
          {label}<span className="ch-pill-pct">{pct(key, label)}</span>
        </button>
      ))}
    </div>
  );

  return (
    <div className="ch-poll">
      <div className="ch-kicker">A course in the works</div>
      <h3>Which part would you most want help with?</h3>
      <p className="ch-poll-intro">
        A practical course walking the whole process &mdash; from designing a consistent character
        to producing and editing a finished scene. Character-sheet templates, reusable prompts, a
        continuity checklist, a shot-planning worksheet, animation demonstrations, and a complete
        production workflow using ChatGPT Work, LTX Studio, specialized animation tools, Magnific, and Descript.
      </p>
      {pills('topic', CH_TOPICS)}
      <div className="ch-poll-label">Preferred format</div>
      {pills('format', CH_FORMATS)}
      {chip && <div className="ch-poll-chip" role="status">{chip}</div>}
    </div>
  );
}

/* ============================================================
   THE SECTION
   ============================================================ */
function CharactersSection() {
  const [path, setPath] = useStateK('talk');
  const Panel = CH_PATHS.find(p => p.id === path).Panel;
  return (
    <section id="characters" className="ch-section">
      <div className="ch-head">
        <div className="ch-kicker">Companion guide</div>
        <h2>Animated characters: picking tools by job</h2>
        <p className="ch-intro">
          The eight scenes use one stack &mdash; Runway, ElevenLabs, CapCut &mdash; for an illustrated
          argument with narration over the top. When your character needs to talk on camera, copy
          a performance, or move through connected scenes, you probably won&rsquo;t use one tool for
          everything. Adapted from the {chExt('https://akesha.github.io/aichar/', 'animated-characters field guide')}.
        </p>
      </div>

      <div className="ch-part">
        <div className="ch-kicker">01 · Pick your path</div>
        <h3>What does your character need to do?</h3>
        <p>Creating an animated character usually involves five separate jobs. The right workflow depends mostly on whether your character needs to talk, physically perform, or move through a cinematic scene.</p>
        <div className="ch-jobs">
          {CH_JOBS.map(([t, d], i) => (
            <div key={t} className="ch-job">
              <div className="ch-job-n">Job {String(i + 1).padStart(2, '0')}</div>
              <div className="ch-job-t">{t}</div>
              <div className="ch-job-d">{d}</div>
            </div>
          ))}
        </div>
        <p className="ch-select-hint">Select a card:</p>
        <div className="ch-cards">
          {CH_PATHS.map(c => (
            <button key={c.id} type="button" aria-pressed={path === c.id}
                    className={`ch-card ${path === c.id ? 'active' : ''}`} onClick={() => setPath(c.id)}>
              {c.art ? (
                <div className="ch-card-art" aria-hidden="true">
                  <div className="big">4K<b>&uarr;</b></div>
                  <div className="tag">UPSCALE · CLEAN · REPAIR</div>
                </div>
              ) : (
                <img src={c.img} alt={c.alt} loading="lazy" />
              )}
              <div className="ch-card-body">
                <div className="ch-card-title">{c.title}</div>
                <div className="ch-card-desc">{c.desc}</div>
              </div>
            </button>
          ))}
        </div>
        <div className="ch-panel" key={path}><Panel /></div>
      </div>

      <ChRecommender />

      <div className="ch-part">
        <div className="ch-kicker">03 · Start small</div>
        <h3>A practical low-cost workflow</h3>
        <p>You don&rsquo;t need to subscribe to every platform at once. Work down the list &mdash; the <span className="ch-if">IF</span> steps only apply when they match your project.</p>
        <ol className="ch-path">
          {CH_LOW_COST.map(([isIf, body], i) => (
            <li key={i}>
              <span className="n">{String(i + 1).padStart(2, '0')}</span>
              <span>{isIf && <span className="ch-if">IF</span>}{body}</span>
            </li>
          ))}
        </ol>
        <p className="ch-small">Start with one animation platform and one editing platform. Add another only when your existing tools cannot produce a particular kind of shot or finish.</p>
      </div>

      <div className="ch-part">
        <div className="ch-kicker">04 · The pipeline</div>
        <h3>Recommended production pipeline</h3>
        <p>First, the shorthand &mdash; what each tool is actually for:</p>
        <div className="ch-shorthand">
          {CH_SHORTHAND.map(([t, d]) => (
            <div key={t}><div className="ch-sh-t">{t}</div><p>{d}</p></div>
          ))}
        </div>
        <p>Then the full pipeline, stage by stage. Prices, credit systems, and model names change frequently &mdash; always check current pricing before committing to a stack.</p>
        <div className="ch-pipeline">
          {CH_PIPELINE.map(([stage, tools], i) => (
            <div key={stage} className="ch-pipe-row">
              <span className="ch-pipe-n">{String(i + 1).padStart(2, '0')}</span>
              <span className="ch-pipe-stage">{stage}</span>
              <span className="ch-pipe-tools">{tools}</span>
            </div>
          ))}
        </div>
        <div className="ch-note ch-combo">
          <div className="ch-note-title">For many narrated YouTube or educational videos, the most practical combination may be:</div>
          <ul className="ch-ticks">
            <li><strong>ChatGPT Work</strong> for planning, visual development, continuity, and rough-cut preparation</li>
            <li><strong>One character-animation tool</strong> for specialized dialogue or performance shots</li>
            <li><strong>LTX Studio</strong> when you want to move from storyboard to several connected, consistent scenes without leaving one production environment</li>
            <li><strong>Magnific</strong> when a reference image or selected final clip needs cleanup or upscaling</li>
            <li><strong>Descript</strong> for dialogue editing, captions, and audio cleanup</li>
            <li><strong>A traditional editor</strong> only when the project needs more advanced finishing</li>
          </ul>
        </div>
        <div className="ch-aside">The practical takeaway: LTX may reduce how many separate tools a narrative-video creator needs, especially when storyboard-to-sequence continuity is the priority. It doesn&rsquo;t eliminate the specialists &mdash; it fills the space between them.</div>
      </div>

      <ChCoursePoll />

      <p className="ch-disclaimer">
        Prices, credit systems, model names, features, and free allowances change frequently.
        Always check current pricing and product pages before building a production workflow
        around a particular tool. Illustrations are original artwork from the field guide.
      </p>
    </section>
  );
}

Object.assign(window, {
  CharacterSheet, ChPolishCallout, TestClipCheck, ChAnimatorCallout,
  ChTalkingCallout, ChKeepersCallout, CharactersSection,
});
