/* =========================================================================
   SCREENS  —  Intro, Quiz, Capture, Analyzing, Results
   ========================================================================= */
const { useState, useEffect, useRef } = React;

/* ---------- INTRO : cinematic reveal ------------------------------------ */
function Intro({ onBegin }) {
  return (
    <div className="screen intro">
      <div className="intro-mark reveal-pop">
        {React.createElement(window.Mark, { size: 96 })}
      </div>
      <div className="eyebrow reveal-up d1">PR New-Business Health Check</div>
      <h1 className="display reveal-up d2">
        How healthy is your<br /><span className="metal">new-business pipeline?</span>
      </h1>
      <p className="lede reveal-up d3">
        Ten quick questions about how new business really works at your firm. In about
        two minutes you will see what your pipeline runs on today, exactly where it is
        leaking, and the specific steps to fix each leak. Free, and yours to keep.
      </p>
      <button className="btn btn-primary reveal-up d4" onClick={onBegin}>Begin the assessment</button>
      <div className="meta-line reveal-up d5">
        <span>10 questions</span><i /><span>About 2 minutes</span><i /><span>No email needed to see your result</span>
      </div>
    </div>
  );
}

/* ---------- QUIZ : one question at a time ------------------------------- */
function Quiz({ index, total, answers, onAnswer, onBack, liveValue }) {
  const q = window.QUESTIONS[index];
  const selected = answers[q.id];
  const [pending, setPending] = useState(null);

  useEffect(() => { setPending(null); }, [index]);

  function choose(i) {
    if (pending != null) return;
    setPending(i);
    setTimeout(() => onAnswer(q.id, i), 320);
  }

  const num = String(index + 1).padStart(2, '0');
  const tot = String(total).padStart(2, '0');

  return (
    <div className="screen quiz">
      <aside className="rail">
        <div className="rail-top">
          {React.createElement(window.Lockup, { height: 22 })}
        </div>
        <div className="rail-gauge">
          {React.createElement(window.PipelineGauge, { value: liveValue, reveal: false, size: 240 })}
          <p className="rail-caption">We update this reading as you answer. It is just a signal, not your score.</p>
        </div>
        <div className="rail-progress">
          <div className="rail-count"><span className="metal">{num}</span><em>/ {tot}</em></div>
          <div className="rail-area">{q.area}</div>
        </div>
      </aside>

      <main className="stage">
        <div className="bar"><div className="bar-fill" style={{ width: ((index) / total) * 100 + '%' }} /></div>
        <div className="q-wrap" key={q.id}>
          <div className="q-index">Question {num}<span> / {tot}</span></div>
          <h2 className="q-title">{q.question}</h2>
          <div className="q-help">{q.help}</div>
          <div className="options">
            {q.options.map((o, i) => {
              const isSel = (pending != null ? pending === i : selected === i);
              return (
                <button key={i}
                  className={'opt' + (isSel ? ' opt-sel' : '') + (pending != null && pending !== i ? ' opt-dim' : '')}
                  style={{ animationDelay: (0.05 + i * 0.06) + 's' }}
                  onClick={() => choose(i)}>
                  <span className="opt-key">{String.fromCharCode(65 + i)}</span>
                  <span className="opt-label">{o.label}</span>
                  <span className="opt-check" aria-hidden="true">
                    <svg viewBox="0 0 24 24" width="18" height="18"><path d="M5 13l4 4L19 7" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" /></svg>
                  </span>
                </button>
              );
            })}
          </div>
          <div className="q-foot">
            {index > 0
              ? <button className="link-back" onClick={onBack}>&larr; Previous</button>
              : <span className="q-foot-note">Choose the answer that is most true today.</span>}
          </div>
        </div>
      </main>
    </div>
  );
}

/* ---------- CAPTURE : email gate after Q9 ------------------------------- */
function Capture({ band, liveValue, onSubmit, onSkip }) {
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [email, setEmail] = useState('');
  const [hp, setHp] = useState(''); // honeypot
  const [touched, setTouched] = useState(false);
  const [busy, setBusy] = useState(false);
  const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
  const nameOk = name.trim().length >= 2;
  const phoneOk = phone.replace(/[^0-9]/g, '').length >= 7;
  const valid = emailOk && nameOk && phoneOk;

  function submit(e) {
    e.preventDefault();
    setTouched(true);
    if (!valid || busy) return;
    setBusy(true);
    onSubmit({ name: name.trim(), phone: phone.trim(), email: email.trim().toLowerCase(), website: hp });
  }

  return (
    <div className="screen capture">
      <div className="capture-inner reveal-up d1">
        <div className="capture-gauge">
          {React.createElement(window.PipelineGauge, { value: liveValue, reveal: false, size: 180 })}
        </div>
        <div className="eyebrow">Your assessment</div>
        <div className="capture-taste">
          Your pipeline reads as <span className="metal">{band}</span>.
        </div>
        <h2 className="capture-h">Where should we send your full read?</h2>
        <p className="capture-sub">
          We will email you your results and the first things we would suggest putting in
          place. No follow up you did not ask for.
        </p>
        <form className="capture-form" onSubmit={submit} noValidate>
          {/* honeypot, visually hidden */}
          <input type="text" name="website" tabIndex="-1" autoComplete="off" value={hp}
                 onChange={(e) => setHp(e.target.value)} className="hp" aria-hidden="true" />
          <input type="text" className={'field' + (touched && !nameOk ? ' field-err' : '')}
                 placeholder="Full name" value={name}
                 onChange={(e) => setName(e.target.value)} autoComplete="name" />
          <input type="tel" className={'field' + (touched && !phoneOk ? ' field-err' : '')}
                 placeholder="Phone number" value={phone}
                 onChange={(e) => setPhone(e.target.value)} autoComplete="tel" />
          <input type="email" className={'field' + (touched && !emailOk ? ' field-err' : '')}
                 placeholder="Work email" value={email}
                 onChange={(e) => setEmail(e.target.value)} autoComplete="email" />
          {touched && !valid && (
            <div className="field-msg">
              {!nameOk ? 'Please enter your name.' : !phoneOk ? 'Please enter a valid phone number.' : 'Please enter a valid email so we can send your read.'}
            </div>
          )}
          <button type="submit" className="btn btn-primary btn-block" disabled={busy}>
            {busy ? 'Sending\u2026' : 'Show my full results'}
          </button>
          <div className="reassure">One email with your results. Nothing else unless you ask.</div>
          <button type="button" className="link-skip" onClick={onSkip}>Just show my results</button>
        </form>
      </div>
    </div>
  );
}

/* ---------- ANALYZING : building your diagnosis ------------------------- */
const ANALYZE_LINES = [
  'Reading through your answers',
  'Mapping where your pipeline leaks',
  'Comparing against agencies we have rebuilt',
  'Writing your prescription',
];
function Analyzing({ onDone }) {
  const [step, setStep] = useState(0);
  useEffect(() => {
    const timers = [];
    ANALYZE_LINES.forEach((_, i) => timers.push(setTimeout(() => setStep(i + 1), 650 * (i + 1))));
    timers.push(setTimeout(onDone, 650 * ANALYZE_LINES.length + 800));
    return () => timers.forEach(clearTimeout);
  }, []);
  return (
    <div className="screen analyzing">
      <div className="analyze-mark"><div className="spin-ring" />{React.createElement(window.Mark, { size: 56, glow: false })}</div>
      <div className="analyze-lines">
        {ANALYZE_LINES.map((l, i) => (
          <div key={i} className={'analyze-line' + (i < step ? ' on' : '')}>
            <span className="analyze-dot" />{l}
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- RESULTS ----------------------------------------------------- */
function Results({ dx, lead, onRetake, bookingUrl }) {
  const band = window.BANDS[dx.band];
  const email = lead && lead.email;
  return (
    <div className="screen results">
      <div className="results-inner">
        {email && <div className="sent-note reveal-up">Your results are on the way to <strong>{email}</strong>.</div>}

        <div className="result-head reveal-up d1">
          <div className="result-headcol">
            <div className="eyebrow">Your diagnosis</div>
            <h2 className="result-h metal">{band.headline}</h2>
            <p className="result-summary">{band.summary}</p>
          </div>
          <div className="result-gauge">
            {React.createElement(window.PipelineGauge, { value: dx.pct / 100, reveal: true, size: 230 })}
            <div className="band-chip">{dx.band}</div>
          </div>
        </div>

        <div className="rx reveal-up d2">
          <div className="rx-head">
            <span className="rx-kicker">The prescription</span>
            <h3 className="rx-title">Your steps to fix the leaks, based on what you told us</h3>
          </div>
          <div className="rx-list">
            {dx.weak.map((w, i) => {
              const rx = window.PRESCRIPTIONS[w.id];
              return (
                <div className="rx-card" key={w.id} style={{ animationDelay: (0.1 + i * 0.1) + 's' }}>
                  <div className="rx-top">
                    <div className="rx-num">{String(i + 1).padStart(2, '0')}</div>
                    <div className="rx-area">{w.area}</div>
                    <div className="rx-system">{rx.system}</div>
                  </div>
                  <div className="rx-you">You told us: &ldquo;{w.label}&rdquo;</div>
                  <div className="rx-block">
                    <div className="rx-tag rx-tag-pain">The cost</div>
                    <p className="rx-pain">{rx.pain}</p>
                  </div>
                  <div className="rx-block">
                    <div className="rx-tag rx-tag-fix">How to fix it</div>
                    <p className="rx-fix">{rx.fix}</p>
                    {rx.channels && (
                      <div className="rx-channels">
                        {['Email', 'LinkedIn', 'Phone', 'Direct Mail'].map((c) => (
                          <span className="chan" key={c}>{c}</span>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        <div className="cta reveal-up d3">
          <div className="cta-proof">
            <div className="cta-proof-label">{window.CASE_STUDY.label}</div>
            <div className="cta-proof-client">{window.CASE_STUDY.client}</div>
            <p className="cta-proof-text">{window.CASE_STUDY.text}</p>
            <div className="cta-stats">
              {window.CASE_STUDY.stats.map((s, i) => (
                <div className="cta-stat" key={i}>
                  <div className="cta-stat-val metal">{s.value}</div>
                  <div className="cta-stat-label">{s.label}</div>
                </div>
              ))}
            </div>
          </div>
          <div className="cta-main">
            <h3 className="cta-h">Want this built for your agency?</h3>
            <p className="cta-sub">
              We will walk you through exactly how we would put these in place for an agency
              like yours, using the same playbook above. No pitch, a working session on your
              pipeline.
            </p>
            <div className="cta-actions">
              <a className="btn btn-primary" href={bookingUrl} target="_blank" rel="noopener noreferrer"
                 onClick={(e) => window.openCalendly(e, lead)}>Show me how to fix this</a>
              <button className="link-skip" onClick={onRetake}>Retake the assessment</button>
            </div>
          </div>
        </div>

        <div className="results-foot">{React.createElement(window.Lockup, { height: 20 })}</div>
      </div>
    </div>
  );
}

Object.assign(window, { Intro, Quiz, Capture, Analyzing, Results });
