/* global React, Icons, Badge, Btn, Pill, Meter, Score, Stat, Eyebrow, LastVerified */
const { useState } = React;

/* =========================================================================
   CREATOR TOOLKIT — calculators, checklists, AI prompt packs.
   Featured interactive: data-usage calculator. The rest tile out as a
   grid of tools, each opening its own dedicated calculator in a later
   phase. Keeps the brief's commitment without front-loading every tool.
   ========================================================================= */

const TOOLS = [
  { id: 'data',    icon: Icons.wifi,    t: 'Data usage calculator',     s: 'Bitrate × hours × stream days → GB needed, plan match.', tag: 'Live demo', featured: true },
  { id: 'battery', icon: Icons.battery, t: 'Battery runtime estimator', s: 'Total draw vs. capacity → realistic runtime, swap timing.', tag: 'Calculator' },
  { id: 'bitrate', icon: Icons.zap,     t: 'Upload bitrate calculator', s: 'Resolution + framerate → recommended encode + headroom.',  tag: 'Calculator' },
  { id: 'elig',    icon: Icons.check,   t: 'Platform eligibility tracker', s: 'Follower + watch-hour math for Twitch Affiliate, YT Live, TikTok, Kick.', tag: 'Tracker' },
  { id: 'check',   icon: Icons.tool,    t: 'Stream checklist generator', s: 'Output the pre-flight, in-flight, and recovery checklist for your build.', tag: 'Generator' },
  { id: 'compare', icon: Icons.filter,  t: 'Gear comparison tables',     s: 'Throw any two pieces of gear side-by-side, same six axes.', tag: 'Tool' },
  { id: 'vert',    icon: Icons.play,    t: 'OBS vertical layout checklist', s: 'For Twitch dual-format and TikTok/Reels/Shorts simultaneously.', tag: 'Checklist' },
  { id: 'prompts', icon: Icons.book,    t: 'AI prompt packs',            s: 'Titles, clips, sponsorship outreach, stream planning — pre-tested prompts.', tag: 'Pack' },
  { id: 'sched',   icon: Icons.clock,   t: 'Stream-plan generator',      s: 'Cadence + content-bucket scaffold for a new IRL channel.', tag: 'Generator' },
];

const RES_OPTIONS = [
  { id: '720',   label: '720p · 30',  mbps: 3.5 },
  { id: '1080',  label: '1080p · 30', mbps: 5.5 },
  { id: '1080p60', label: '1080p · 60', mbps: 7.5 },
  { id: '1440',  label: '1440p · 60', mbps: 10.5 },
];

const ToolkitPage = ({ onNav }) => {
  const [res, setRes] = useState('1080');
  const [hours, setHours] = useState(3);
  const [days, setDays] = useState(20);
  const [copied, setCopied] = useState(false);
  const r = RES_OPTIONS.find(o => o.id === res);
  const perStream = (r.mbps * 0.45 * hours);     // GB per stream
  const perMonth  = perStream * days;             // GB per month

  const promptText = `You are titling a Twitch IRL VOD clip for maximum clip-discovery surface on
TikTok and YouTube Shorts simultaneously. The clip is {clip-summary}.

Constraints:
- 60 characters max
- One concrete noun in the first three words
- No emoji, no "POV:", no all-caps clickbait
- Avoid words flagged by TikTok community guidelines: {list}
- Match the platform tone (TikTok: punchy verb / YT Shorts: question or stat)

Return 5 candidates, ranked by predicted click-through, with a one-line
rationale per option grounded in {clip-summary}.`;

  const copyPrompt = async () => {
    try {
      await navigator.clipboard.writeText(promptText);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {/* clipboard unavailable; user can select-and-copy from the pre */}
  };

  return (
    <div className="page-fade">
      {/* HEADER ========================================================== */}
      <section style={{ padding: '40px 0 32px', borderBottom: '1px solid var(--line)' }}>
        <div className="container">
          <div className="row between" style={{ alignItems: 'flex-end' }}>
            <div style={{ maxWidth: '70%' }}>
              <Eyebrow>Phase 3 · Creator Toolkit · 9 tools</Eyebrow>
              <h1 className="mt-4" style={{ fontSize: 56 }}>
                The Toolkit.
              </h1>
              <p className="lede mt-3" style={{ maxWidth: '60ch' }}>
                Calculators and checklists for every decision that should be math, not vibes.
                Open-source where possible. Affiliate-free by design.
              </p>
            </div>
            <div className="col gap-2" style={{ alignItems: 'flex-end' }}>
              <div className="row gap-2">
                <Badge kind="independent">Non-affiliated</Badge>
                <Badge kind="updated" dot>Live</Badge>
              </div>
              <LastVerified date="2026-05-15" prefix="Refreshed" />
            </div>
          </div>
        </div>
      </section>

      {/* FEATURED CALCULATOR ============================================== */}
      <section className="section">
        <div className="container">
          <div className="section-head">
            <div>
              <Eyebrow>01 · Featured</Eyebrow>
              <h2 className="mt-3">Data usage calculator.</h2>
              <p className="text-fg2 mt-3" style={{ maxWidth: '54ch' }}>
                How much data does your stream actually need per month? Move the controls;
                we match a plan from the data hub.
              </p>
            </div>
            <Btn kind="line">Open all calculators<Icons.arrow size={14} /></Btn>
          </div>

          <div className="card" style={{ overflow: 'hidden' }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr' }}>
              {/* controls */}
              <div style={{ padding: 32, borderRight: '1px solid var(--line)' }}>
                <Eyebrow>Inputs</Eyebrow>
                <div className="mt-5 col gap-6">
                  <div>
                    <div className="row between mb-2">
                      <span className="mono fs-12 text-fg3" style={{ letterSpacing: '0.1em', textTransform: 'uppercase' }}>Resolution / fps</span>
                      <span className="mono fs-13 text-accent">{r.label} · {r.mbps} Mbps</span>
                    </div>
                    <div className="row gap-2 wrap">
                      {RES_OPTIONS.map(o => (
                        <Pill key={o.id} on={res === o.id} onClick={() => setRes(o.id)}>{o.label}</Pill>
                      ))}
                    </div>
                  </div>
                  <div>
                    <div className="row between mb-2">
                      <span className="mono fs-12 text-fg3" style={{ letterSpacing: '0.1em', textTransform: 'uppercase' }}>Hours per stream</span>
                      <span className="mono fs-13 text-accent">{hours} h</span>
                    </div>
                    <input type="range" className="slider"
                           min={1} max={12} step={0.5} value={hours}
                           onChange={e => setHours(parseFloat(e.target.value))} />
                  </div>
                  <div>
                    <div className="row between mb-2">
                      <span className="mono fs-12 text-fg3" style={{ letterSpacing: '0.1em', textTransform: 'uppercase' }}>Streams per month</span>
                      <span className="mono fs-13 text-accent">{days}</span>
                    </div>
                    <input type="range" className="slider"
                           min={1} max={31} step={1} value={days}
                           onChange={e => setDays(parseFloat(e.target.value))} />
                  </div>
                </div>
              </div>

              {/* output */}
              <div style={{ padding: 32, background: 'var(--bg-1)' }}>
                <Eyebrow>Output</Eyebrow>
                <div className="mt-5">
                  <div className="stat-label">Per stream</div>
                  <div className="mono mt-1" style={{ fontSize: 28, color: 'var(--fg)' }}>{perStream.toFixed(1)} GB</div>
                </div>
                <div className="mt-5">
                  <div className="stat-label">Per month</div>
                  <div className="mono mt-1" style={{ fontSize: 44, color: 'var(--accent)', letterSpacing: '-0.02em' }}>{perMonth.toFixed(0)} GB</div>
                </div>
                <div className="mt-4" style={{ paddingTop: 16, borderTop: '1px solid var(--line)' }}>
                  <div className="stat-label mb-2">Recommended plan tier</div>
                  <div style={{ fontSize: 16, fontWeight: 500 }}>
                    {perMonth >= 250 ? 'Calyx Sprout (unlimited, no deprio)' :
                     perMonth >= 100 ? 'T-Mobile Business 5G Unlimited Advanced' :
                                       'US Mobile Premium (Warp)'}
                  </div>
                  <div className="text-fg3 fs-13 mt-1">Headroom included. Open Data hub for live plan comparison.</div>
                  <Btn kind="primary" size="sm" onClick={() => onNav?.('data')} iconRight={<Icons.arrow size={12} />}>Open Data hub</Btn>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* TOOL GRID ======================================================= */}
      <section className="section" style={{ background: 'var(--bg-1)', borderTop: '1px solid var(--line)' }}>
        <div className="container">
          <div className="section-head">
            <div>
              <Eyebrow>02 · All tools</Eyebrow>
              <h2 className="mt-3">Nine tools.<br/>None of them in your way.</h2>
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
            {TOOLS.map(t => {
              // Featured tool (data calc) is the live demo above — clicking
              // scrolls back to it. Everything else is Phase 3/4.
              const isFeatured = t.featured;
              const onClick = isFeatured
                ? () => document.querySelector('.section')?.scrollIntoView({ behavior: 'smooth' })
                : undefined;
              const Tag = isFeatured ? 'button' : 'div';
              return (
                <Tag key={t.id} className={`card ${isFeatured ? 'hover' : ''}`}
                     onClick={onClick}
                     style={{ display: 'block', cursor: isFeatured ? 'pointer' : 'default', padding: '24px 24px', textAlign: 'left', width: '100%' }}>
                  <div className="row between mb-4">
                    <div style={{
                      width: 36, height: 36, borderRadius: 6,
                      display: 'grid', placeItems: 'center',
                      background: 'var(--bg-3)',
                      color: isFeatured ? 'var(--accent)' : 'var(--fg-2)',
                      border: '1px solid var(--line-2)',
                    }}><t.icon size={16} /></div>
                    {isFeatured
                      ? <Badge kind="tested" dot>Live demo above</Badge>
                      : <Badge kind="beginner">Soon</Badge>}
                  </div>
                  <div style={{ fontSize: 17, fontWeight: 600, letterSpacing: '-0.015em' }}>{t.t}</div>
                  <p className="text-fg3 fs-13 mt-2" style={{ maxWidth: '32ch' }}>{t.s}</p>
                  <div className="row between mt-5">
                    <span className="mono fs-12 text-fg4">{isFeatured ? 'TRY ABOVE' : 'PHASE 3/4'}</span>
                    {isFeatured && <Icons.arrow size={14} style={{ color: 'var(--fg-3)' }} className="arrow" />}
                  </div>
                </Tag>
              );
            })}
          </div>
        </div>
      </section>

      {/* PROMPT PACK PEEK ================================================ */}
      <section className="section">
        <div className="container">
          <div className="section-head">
            <div>
              <Eyebrow>03 · AI prompt pack · sneak peek</Eyebrow>
              <h2 className="mt-3">Pre-tested prompts.<br/>Built for IRL workflows.</h2>
              <p className="text-fg2 mt-3" style={{ maxWidth: '54ch' }}>
                Title generation, clip selection, sponsorship outreach, stream-plan
                scaffolding — each prompt is run against the major models and
                hand-validated. No "act as a..." slop.
              </p>
            </div>
          </div>

          <div className="card card-pad-lg">
            <div className="row between mb-4">
              <Eyebrow>EXAMPLE · TITLE GENERATION</Eyebrow>
              <span className="mono fs-12 text-fg4">VALIDATED · MAY 2026 · CLAUDE 4.7 · GPT-5 · GEMINI 3</span>
            </div>
            <pre style={{
              background: 'var(--bg-2)',
              border: '1px solid var(--line-2)',
              borderRadius: 6,
              padding: 18,
              fontFamily: 'var(--font-mono)',
              fontSize: 12.5,
              color: 'var(--fg-2)',
              lineHeight: 1.55,
              overflow: 'auto',
              whiteSpace: 'pre-wrap',
            }}>
{`You are titling a Twitch IRL VOD clip for maximum clip-discovery surface on
TikTok and YouTube Shorts simultaneously. The clip is {clip-summary}.

Constraints:
- 60 characters max
- One concrete noun in the first three words
- No emoji, no "POV:", no all-caps clickbait
- Avoid words flagged by TikTok community guidelines: {list}
- Match the platform tone (TikTok: punchy verb / YT Shorts: question or stat)

Return 5 candidates, ranked by predicted click-through, with a one-line
rationale per option grounded in {clip-summary}.`}
            </pre>
            <div className="row gap-2 mt-4">
              <Btn kind="primary" size="sm" onClick={copyPrompt}>
                {copied ? 'Copied to clipboard' : 'Copy prompt'}<Icons.share size={12} />
              </Btn>
              <Btn kind="line" size="sm" href="mailto:hello@livestreamers.org?subject=AI%20prompt%20pack%20early%20access">
                Get the full pack (32 prompts)<Icons.arrow size={12} />
              </Btn>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
};

window.ToolkitPage = ToolkitPage;
