// Phase 4: Results + Email capture + PDF export

function Phase4({ state, setState, onBack }) {
  const { tasks, blueprintPicks, email, emailSubmitted } = state;

  const picks = blueprintPicks.map(p => ({ ...p, task: tasks.find(t => t.id === p.taskId) })).filter(p => p.task);
  const totalPickHours = picks.reduce((a, p) => a + (Number(p.task.hours) || 0), 0);
  // Annual hours reclaimed. The playbook lives in hours, not dollars.
  const annualHoursBack = Math.round(totalPickHours * 50);
  // Equivalent full work weeks (40 hr) makes the number tangible.
  const weeksBack = Math.round(annualHoursBack / 40);

  const [emailDraft, setEmailDraft] = React.useState(email || '');
  const [status, setStatus] = React.useState('idle'); // idle | sending | sent

  // The booking modal (overlay + lazy-loaded /booking-widget.html) lives in
  // components/BookingModal.jsx as a singleton mounted to <body>. Phase4 just
  // opens it via the global; the modal handles its own state, scroll lock,
  // and Esc-to-close.

  // Build the summary payload that gets sent to the Worker alongside the PDF.
  // Worker uses it to enrich the HubSpot contact + team notification email.
  const buildSummary = () => ({
    totalPickHours,
    annualHoursBack,
    weeksBack,
    blueprintPicks: picks.map(p => ({
      name: p.task.name,
      hours: p.task.hours,
      doneLooksLike: p.doneLooksLike || null,
      tool: p.tool || null,
    })),
  });

  // Submit the email and PDF to the Worker.
  // PDF generation + the network call live in window.bluemoso (see /website/lib/).
  // This component just manages UI state and orchestrates.
  const submitEmail = async () => {
    const trimmed = emailDraft.trim();
    if (!/^\S+@\S+\.\S+$/.test(trimmed)) { alert('Please enter a valid email.'); return; }
    setStatus('sending');
    try {
      const pdfBase64 = await window.bluemoso.pdf.generateBase64FromElement('playbook-pdf-content');
      // turnstileMount tells the lib to render the CAPTCHA inline within
      // this form (above the helper text) instead of as a floating overlay.
      await window.bluemoso.api.submitPlaybook({
        email: trimmed,
        summary: buildSummary(),
        pdfBase64,
        turnstileMount: '#cf-turnstile-playbook',
      });
      setState(s => ({ ...s, email: trimmed, emailSubmitted: true }));
      setStatus('sent');
      // Track conversion: lead captured via playbook funnel.
      // email_domain (not full email) keeps GA free of PII while still
      // letting us segment by business vs. consumer email providers.
      window.bluemoso.analytics.track('playbook_email_submitted', {
        email_domain: trimmed.split('@')[1] || null,
        picks_count: picks.length,
        annual_hours_back: annualHoursBack,
      });
    } catch (err) {
      console.error('Playbook submit failed:', err);
      window.bluemoso.analytics.track('playbook_email_submit_failed', {
        error_message: err && err.message ? err.message : 'unknown',
      });
      alert(`Couldn't send: ${err.message || 'unknown error'}. You can use the "Save as PDF now" button below instead.`);
      setStatus('idle');
    }
  };

  // (Direct PDF download removed — PDF delivery is email-only so we capture
  // a real address for the lead. lib/bluemoso.js still exposes
  // saveLocallyFromElement if we ever want to re-introduce a download path.)

  // Let the user fix a typo and re-submit. Returns the form to the email
  // input state with the previous draft pre-filled so they can edit it.
  const resendToDifferentEmail = () => {
    setState(s => ({ ...s, emailSubmitted: false }));
    setStatus('idle');
    // emailDraft stays — user edits the typo or clears it.
    window.bluemoso.analytics.track('playbook_email_resent', {
      prior_email_domain: emailDraft && emailDraft.includes('@')
        ? emailDraft.split('@')[1]
        : null,
    });
  };

  return (
    <PbSection id="phase4">
      <PhaseHeader
        num="4"
        kicker="Equip & act"
        title="Your delegation plan,"
        italic="ready to run."
      />

      {/* Headline stats */}
      <div style={{
        padding: 40, borderRadius: 20,
        background: 'var(--ink)', color: '#fff',
        marginBottom: 40,
      }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 32 }} className="bm-pb-bigstats">
          <BigStat label="Hours back per week" value={`${totalPickHours.toFixed(1)}`} unit="hrs/wk" />
          <BigStat label="Hours back per year" value={`${annualHoursBack.toLocaleString()}`} unit="hrs/yr" tone="blue" />
          <BigStat label="That's roughly" value={`${weeksBack}`} unit="full work weeks" />
        </div>
      </div>

      {/* Action plan */}
      <Card style={{ marginBottom: 32 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', marginBottom: 20, letterSpacing: '-0.01em' }}>Your top delegation moves</div>
        <div style={{ display: 'grid', gap: 14 }}>
          {picks.map((p, i) => (
            <div key={p.taskId} style={{
              display: 'grid', gridTemplateColumns: '44px 1fr 140px', gap: 20,
              padding: '18px 20px',
              border: '1px solid var(--line-soft)', borderRadius: 12,              background: 'var(--paper-deep)',
            }} className="bm-pb-action-row">
              <div className="serif" style={{ fontSize: 32, color: 'var(--blue)', lineHeight: 1 }}>0{i + 1}</div>
              <div>
                <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 4 }}>{p.task.name}</div>
                <div style={{ fontSize: 13, color: 'var(--ink-muted)', lineHeight: 1.5 }}>
                  {p.doneLooksLike || <em style={{ color: 'var(--ink-muted)' }}>No "done" defined yet, go back and add it.</em>}
                </div>
                {p.tool && <div style={{ fontSize: 11, color: 'var(--blue)', fontWeight: 500, marginTop: 8 }}>Assigned in: {p.tool}</div>}
              </div>
              <div style={{ textAlign: 'right' }}>
                <div className="serif" style={{ fontSize: 26, letterSpacing: '-0.02em' }}>{p.task.hours} hrs</div>
                <div style={{ fontSize: 11, color: 'var(--ink-muted)', marginTop: 2 }}>per week back</div>
              </div>
            </div>
          ))}
        </div>
      </Card>

      {/* Checklist */}
      <Card style={{ marginBottom: 40 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', marginBottom: 16 }}>Before you hand off, the 5-point checklist</div>
        <div style={{ display: 'grid', gap: 10 }}>
          {[
            'I tracked my recurring tasks honestly',
            'I picked 3 things to delegate first',
            'I gave clear instructions, what "done" looks like',
            'I scheduled a follow-up in week one',
            "I'll give feedback early, not hold it until it's festering",
          ].map((item, i) => (
            <label key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: 14, cursor: 'pointer' }}>
              <input type="checkbox" style={{ width: 18, height: 18, accentColor: 'var(--blue)' }} />
              <span style={{ color: 'var(--ink-soft)' }}>{item}</span>
            </label>
          ))}
        </div>
      </Card>

      {/* Email capture + PDF */}
      <div style={{
        padding: 40, borderRadius: 20,
        background: 'linear-gradient(135deg, var(--blue-soft) 0%, #fff 70%)',
        border: '1px solid var(--line-soft)',
        marginBottom: 40,
      }} className="no-print">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 48, alignItems: 'center' }} className="bm-pb-email-grid">
          <div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--blue)', letterSpacing: '0.08em', marginBottom: 12 }}>TAKE IT WITH YOU</div>
            <h3 className="serif" style={{ fontSize: 34, letterSpacing: '-0.02em', lineHeight: 1.05, marginBottom: 14 }}>
              Get your plan <em style={{ color: 'var(--blue)', fontStyle: 'italic' }}>in your inbox.</em>
            </h3>
            <p style={{ fontSize: 15, lineHeight: 1.55, color: 'var(--ink-muted)', marginBottom: 20 }}>
              Drop your email and we'll send a formatted PDF of this plan straight to you. You'll also get occasional notes on delegation, VAs, and scaling without burnout.
            </p>
            <div style={{ fontSize: 12, color: 'var(--ink-muted)' }}>
              No spam. Unsubscribe any time.
            </div>
          </div>
          <div>
            {!emailSubmitted ? (
              <div>
                <label htmlFor="playbook-email-input" style={{ display: 'block', fontSize: 12, fontWeight: 500, color: 'var(--ink-soft)', marginBottom: 8, letterSpacing: '-0.01em' }}>Email address</label>
                <input
                  id="playbook-email-input"
                  type="email"
                  value={emailDraft}
                  onChange={(e) => setEmailDraft(e.target.value)}
                  placeholder="you@company.com"
                  required
                  autoComplete="email"
                  style={{
                    width: '100%', padding: '14px 16px',
                    fontSize: 15, border: '1px solid var(--line)',
                    borderRadius: 12, background: '#fff', marginBottom: 12,
                  }}
                />
                <button
                  type="button"
                  onClick={submitEmail}
                  disabled={status === 'sending'}
                  style={{
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                    width: '100%', padding: '14px 24px',
                    background: status === 'sending' ? 'var(--ink-muted)' : 'var(--ink)',
                    color: '#fff',
                    border: 'none',
                    borderRadius: 12, fontSize: 14, fontWeight: 500,
                    transition: 'background .2s',
                    cursor: status === 'sending' ? 'wait' : 'pointer',
                  }}>
                  {status === 'sending' ? 'Generating your PDF…' : 'Email me my plan'}
                  {status !== 'sending' && (
                    <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M4 8h8m0 0L8 4m4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
                  )}
                </button>
                {/* Inline Turnstile mount. Collapses to 0×0 when no challenge
                    is needed; grows in-flow above the helper text when a
                    challenge is required. size:'flexible' lets the widget
                    adapt to the column width on mobile, tablet, and desktop. */}
                <div id="cf-turnstile-playbook" style={{
                  display: 'flex', justifyContent: 'center',
                  marginTop: 12,
                  minHeight: 0,
                }}></div>
                <div style={{ fontSize: 12, color: 'var(--ink-muted)', marginTop: 12, textAlign: 'center', lineHeight: 1.5 }}>
                  We'll send a formatted PDF you can save or print.
                </div>
              </div>
            ) : (
              <div style={{
                padding: 24, borderRadius: 14,
                background: '#fff', border: '1px solid var(--blue-soft)',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
                  <div style={{
                    width: 24, height: 24, borderRadius: 12,
                    background: 'var(--blue)', color: '#fff',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 13, fontWeight: 700,
                  }}>✓</div>
                  <div style={{ fontSize: 15, fontWeight: 600 }}>We'll send it to {email}</div>
                </div>
                <div style={{ fontSize: 13, color: 'var(--ink-muted)', lineHeight: 1.5 }}>
                  Check your inbox in the next few minutes. If you don't see it, check your spam or promotions folder.
                </div>
                <button
                  type="button"
                  onClick={resendToDifferentEmail}
                  style={{
                    marginTop: 14,
                    fontSize: 12,
                    color: 'var(--blue)',
                    background: 'transparent',
                    border: 'none',
                    padding: 0,
                    cursor: 'pointer',
                    textDecoration: 'underline',
                  }}>
                  Typed the wrong email? Send to a different address
                </button>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Book a call CTA */}
      <div style={{
        padding: '48px 40px', borderRadius: 20,
        background: 'var(--paper-deep)',
        border: '1px solid var(--line-soft)',
        textAlign: 'center',
        marginBottom: 32,
      }} className="no-print">
        <div className="mono" style={{ fontSize: 11, color: 'var(--blue)', letterSpacing: '0.08em', marginBottom: 14 }}>NEXT STEP</div>
        <h3 className="serif" style={{ fontSize: 38, letterSpacing: '-0.025em', lineHeight: 1.05, marginBottom: 16, maxWidth: 640, margin: '0 auto 16px' }}>
          Don't want to do the delegating yourself? <em style={{ color: 'var(--blue)', fontStyle: 'italic' }}>That's what we do.</em>
        </h3>
        <p style={{ fontSize: 16, color: 'var(--ink-muted)', lineHeight: 1.55, maxWidth: 560, margin: '0 auto 28px' }}>
          BlueMoso matches you with a virtual assistant trained to own these exact tasks. Bring your plan to a 20-minute call and we'll tell you who we'd pair you with.
        </p>
        <PrimaryBtn onClick={() => {
          // Open the modal FIRST, track AFTER — so a tracking failure
          // (e.g. window.bluemoso.analytics undefined) can't block the user.
          if (window.bluemoso && window.bluemoso.bookingModal) {
            window.bluemoso.bookingModal.open('playbook_phase4_cta');
          }
          try {
            if (window.bluemoso && window.bluemoso.analytics) {
              window.bluemoso.analytics.track('playbook_book_call_clicked', {
                email_submitted: !!emailSubmitted,
                picks_count: picks.length,
                annual_hours_back: annualHoursBack,
              });
            }
          } catch (e) {
            if (window.console && console.warn) console.warn('[analytics] book_call track failed:', e);
          }
        }}>
          Book a call with BlueMoso
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M4 8h8m0 0L8 4m4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
        </PrimaryBtn>
      </div>

      {/* Booking modal lives in components/BookingModal.jsx as a body-mounted
          singleton. The button above calls window.bluemoso.bookingModal.open() */}

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }} className="bm-pb-footer-row no-print">
        <GhostBtn onClick={onBack}>← Edit plan</GhostBtn>
        <a href="index.html" style={{ fontSize: 13, color: 'var(--ink-muted)', fontWeight: 500 }}>Back to bluemoso.com →</a>
      </div>

      {/* Off-screen PDF template, captured by the PDF generation flow via #playbook-pdf-content */}
      {typeof PlaybookPdfTemplate === 'function' && (
        <PlaybookPdfTemplate state={state} />
      )}
    </PbSection>
  );
}

function BigStat({ label, value, unit, tone = 'light' }) {
  const color = tone === 'blue' ? '#9FCCF5' : '#fff';
  return (
    <div>
      <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'rgba(255,255,255,0.88)', marginBottom: 14, fontWeight: 500 }}>{label}</div>
      <div className="serif" style={{ fontSize: 60, lineHeight: 1, letterSpacing: '-0.035em', color, marginBottom: 8 }}>{value}</div>
      <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.85)' }}>{unit}</div>
    </div>
  );
}

// BookingModal + BookingWidgetMount live in components/BookingModal.jsx now —
// shared with the hub pages (virtual-assistants.html, services.html,
// who-we-serve.html). Phase4 opens it via window.bluemoso.bookingModal.open().

Object.assign(window, { Phase4 });
