// Hero section with animated voice-to-rubric demo
const { useState, useEffect, useRef } = React;

function Wordmark({ onHero }) {
  return (
    <a href="#" className="wordmark" style={{ color: onHero ? 'var(--hero-ink)' : 'var(--ink)' }}>
      <span className="wordmark-glyph">
        <svg viewBox="0 0 24 24" fill="none">
          <rect x="2" y="5" width="4" height="14" rx="1" fill="currentColor" opacity="0.35"/>
          <rect x="8" y="9" width="4" height="10" rx="1" fill="currentColor" opacity="0.6"/>
          <rect x="14" y="3" width="4" height="16" rx="1" fill="currentColor"/>
          <rect x="20" y="11" width="2" height="6" rx="1" fill="currentColor" opacity="0.5"/>
        </svg>
      </span>
      <span>Markaloud</span>
    </a>
  );
}

function Nav() {
  return (
    <nav className="nav">
      <div className="container nav-inner">
        <Wordmark onHero />
        <div className="nav-links">
          <a href="#how">How it works</a>
          <a href="#why-dictation">Why dictation</a>
          <a href="#features">Features</a>
          <a href="#security">Privacy</a>
          <a href="#pricing">Pricing</a>
        </div>
        <div className="nav-ctas">
          <a href="https://app.markaloud.cloud/login" style={{fontSize: 14, color: 'var(--hero-ink-3)'}}>Sign in</a>
          <a href="https://app.markaloud.cloud/register" className="btn btn-primary on-hero">Get started</a>
        </div>
      </div>
    </nav>
  );
}

// Scripted transcript -> rubric tags
const SCRIPT = [
  { text: "Strong opening argument, but the thesis could be sharper — ", tag: 'thesis' },
  { text: "evidence in paragraph three is excellent, ", tag: 'evidence' },
  { text: "though citations are inconsistent. ", tag: 'citations' },
  { text: "Watch comma splices in the conclusion.", tag: 'mechanics' }
];

const RUBRIC = [
  { id: 'thesis',    label: 'Thesis & argument' },
  { id: 'evidence',  label: 'Use of evidence' },
  { id: 'citations', label: 'Citation accuracy' },
  { id: 'mechanics', label: 'Grammar & mechanics' },
  { id: 'structure', label: 'Structure & flow' },
  { id: 'voice',     label: 'Voice & style' }
];

function AnimatedDemo() {
  const [charIdx, setCharIdx] = useState(0);
  const [assigned, setAssigned] = useState({});
  const fullText = SCRIPT.map(s => s.text).join('');

  useEffect(() => {
    let i = 0;
    let running = true;
    const tick = () => {
      if (!running) return;
      i = (i + 1) % (fullText.length + 60);
      if (i <= fullText.length) {
        setCharIdx(i);
        // compute which script chunks completed
        let acc = 0;
        const newAssigned = {};
        for (const seg of SCRIPT) {
          acc += seg.text.length;
          if (i >= acc) newAssigned[seg.tag] = true;
        }
        setAssigned(newAssigned);
      } else if (i === fullText.length + 59) {
        // reset
        setCharIdx(0);
        setAssigned({});
      }
      setTimeout(tick, i < fullText.length ? 38 : 30);
    };
    const t = setTimeout(tick, 600);
    return () => { running = false; clearTimeout(t); };
  }, []);

  const typed = fullText.slice(0, charIdx);

  return (
    <div className="demo" aria-label="Live demo">
      <div className="demo-header">
        <span><span className="demo-dot" /> recording · session #481</span>
        <span>00:{String(Math.floor(charIdx / 8)).padStart(2, '0')}</span>
      </div>
      <div className="demo-body">
        <div className="demo-wave">
          {Array.from({ length: 44 }).map((_, i) => (
            <span key={i} style={{ animationDelay: `${(i * 0.07) % 1.1}s` }} />
          ))}
        </div>
        <div className="demo-transcript">
          <span className="typed">{typed}</span>
          <span className="caret" />
        </div>
        <div className="demo-tags">
          <div className="demo-tags-label">Auto-organizing by rubric</div>
          <div className="tag-row">
            {RUBRIC.map((r, i) => {
              const isAssigned = !!assigned[r.id];
              const visible = i < 4 || isAssigned;
              return (
                <span
                  key={r.id}
                  className={`tag ${visible ? 'appear' : ''} ${isAssigned ? 'assigned' : ''}`}
                >
                  <span className="dot" />
                  {r.label}
                </span>
              );
            })}
          </div>
        </div>
      </div>
      <div className="demo-footer">
        <span>Emily R. · Essay 3 of 28</span>
        <span>Auto-saved</span>
      </div>
    </div>
  );
}

function SplitDemo() {
  const [tick, setTick] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setTick(t => (t + 1) % 5), 1800);
    return () => clearInterval(id);
  }, []);

  const lines = [
    { t: '00:04', text: 'Thesis could be sharper.' },
    { t: '00:12', text: 'Paragraph three evidence is excellent.' },
    { t: '00:21', text: 'Citations are inconsistent — check Chicago format.' },
    { t: '00:34', text: 'Watch comma splices near the conclusion.' }
  ];

  const counts = [
    { label: 'Thesis & argument',   c: Math.min(tick, 1), total: 4 },
    { label: 'Use of evidence',     c: Math.min(tick, 2), total: 4 },
    { label: 'Citation accuracy',   c: Math.min(tick, 3), total: 4 },
    { label: 'Grammar & mechanics', c: Math.min(tick, 4), total: 4 }
  ];

  return (
    <div className="split">
      <div className="split-col">
        <h4>Voice capture</h4>
        <div className="split-voice">
          {lines.map((l, i) => (
            <div key={i} className={`voice-line ${i < tick ? 'active' : ''}`}>
              <span className="voice-time">{l.t}</span>
              {l.text}
            </div>
          ))}
        </div>
      </div>
      <div className="split-col">
        <h4>Sorted by rubric</h4>
        <div className="split-rubric">
          {counts.map((r, i) => (
            <div key={i} className="rubric-item">
              <div className="rubric-head">
                <span className="rubric-name">{r.label}</span>
                <span className="rubric-count">{r.c}/{r.total}</span>
              </div>
              <div className="rubric-bar">
                <span className="rubric-bar-fill" style={{ width: `${(r.c / r.total) * 100}%` }} />
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function Hero({ headline, variant }) {
  return (
    <section className="hero">
      <div className="container">
        <div className="hero-grid">
          <div>
            <div className="label on-hero">Your judgement · your voice · AI just types</div>
            <h1 dangerouslySetInnerHTML={{ __html: headline.replace(/—(.+)/, '— <em>$1</em>') }} />
            <p className="hero-sub">
              Markaloud doesn't grade your students — you do. Speak your feedback, and AI takes care of transcribing it, matching it to your rubric, and drafting a clean report. Your judgement stays human. Just the typing goes away.
            </p>
            <div className="hero-ctas">
              <a href="https://app.markaloud.cloud/register" className="btn btn-primary on-hero">Start free trial · 60 mins</a>
              <a href="#how" className="btn btn-ghost on-hero">See how it works <span className="btn-arrow">→</span></a>
            </div>
            <div className="hero-meta">
              <div><b>£0.02</b><span>per transcription minute</span></div>
              <div><b>7</b><span>pre-built rubric templates</span></div>
              <div><b>GDPR</b><span>&nbsp;compliant with DPA</span></div>
            </div>
          </div>
          <div>
            {variant === 'split' ? <SplitDemo /> : <AnimatedDemo />}
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Nav, Hero, Wordmark });
