// Phase 1: Hero + Mindset + Hourly Rate Calculator

function Hero({ onStart }) {
  return (
    <section className="bm-pb-hero" style={{
      position: 'relative',
      padding: '90px 32px 80px',
      overflow: 'hidden',
      borderBottom: '1px solid var(--line-soft)',
    }}>
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'radial-gradient(60% 50% at 80% 20%, rgba(8,120,216,0.07) 0%, transparent 60%), radial-gradient(40% 40% at 10% 80%, rgba(214,230,245,0.6) 0%, transparent 70%)',
      }} />
      <div style={{
        position: 'relative',
        maxWidth: 900, margin: '0 auto', textAlign: 'center',
      }}>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          fontSize: 13, color: 'var(--blue)', fontWeight: 500,
          padding: '6px 14px', borderRadius: 999,
          background: 'var(--blue-soft)', border: '1px solid rgba(8,120,216,0.12)',
          marginBottom: 28,
        }}>
          <span style={{ width: 6, height: 6, borderRadius: 3, background: 'var(--blue)' }} />
          The free delegation playbook from BlueMoso
        </div>
        <h1 className="serif bm-pb-hero-title" style={{
          fontSize: 88, lineHeight: 1.05, letterSpacing: '-0.035em',
          color: 'var(--ink)', marginBottom: 28, fontWeight: 400,
        }}>
          The Delegation <em style={{ fontWeight: 700, color: 'var(--blue)' }}>Playbook.</em>
        </h1>
        <p className="bm-pb-hero-sub" style={{
          fontSize: 21, lineHeight: 1.45, color: 'var(--ink-muted)',
          maxWidth: 620, margin: '0 auto 40px',
        }}>
          A step-by-step guide to getting more done by doing less. Find the tasks that cost you most, and plan what to offload first, in about 12 minutes.
        </p>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 40 }}>
          <PrimaryBtn onClick={onStart}>
            Start the playbook
            <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>
        <div className="bm-pb-hero-trust" style={{
          display: 'flex', justifyContent: 'center', gap: 40,
          fontSize: 13, color: 'var(--ink-muted)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ width: 6, height: 6, borderRadius: 3, background: 'var(--green-ok)' }} />
            No signup to start
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ width: 6, height: 6, borderRadius: 3, background: 'var(--green-ok)' }} />
            Auto-saves as you go
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ width: 6, height: 6, borderRadius: 3, background: 'var(--green-ok)' }} />
            Export as PDF when done
          </div>
        </div>
      </div>
    </section>
  );
}

// ====== PHASE 1 ======

function Phase1({ state, setState, onComplete }) {
  const { hoursPerWeek, annualIncome, delegatableHours = 10 } = state;
  const workHoursPerYear = (hoursPerWeek || 50) * 50; // approximate working weeks
  const hourly = annualIncome > 0 && workHoursPerYear > 0 ? Math.round(annualIncome / workHoursPerYear) : 0;
  // Cap delegatable hours at total hours worked, can't delegate more than you do
  const effectiveDelegatable = Math.min(delegatableHours, hoursPerWeek || 0);
  // Frame as hours back, not dollar upside, matches the ICP page calculators
  const annualHoursBack = effectiveDelegatable * 50;
  // Work-week equivalent (40 hr weeks) makes the number tangible at a glance
  const weeksBack = Math.round(annualHoursBack / 40);
  const dailyBack = (effectiveDelegatable / 5).toFixed(1); // hrs/day across a 5-day week

  const updateHours = (v) => setState(s => ({ ...s, hoursPerWeek: v }));
  const updateIncome = (v) => setState(s => ({ ...s, annualIncome: v }));
  const updateDelegatable = (v) => setState(s => ({ ...s, delegatableHours: v }));

  return (
    <PbSection id="phase1" narrow>
      <PhaseHeader
        num="1"
        kicker="Reset your mindset & focus"
        title="What's your time"
        italic="actually worth?"
        subtitle="Calculate your hourly rate, then count up the hours below it. The dollar value is a gut‑check. The real win is the hours you reclaim."
      />

      {/* Mindset cards */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16,
        marginBottom: 48,
      }} className="bm-pb-mindset-grid">
        {[
          { n: '01', t: "You don't need to do everything yourself.", s: 'Excellence isn\'t measured in hours spent, it\'s measured in outcomes.' },
          { n: '02', t: 'Delegation isn\'t giving up control.', s: 'It\'s gaining capacity. The best operators own outcomes, not keystrokes.' },
          { n: '03', t: 'Progress beats perfection.', s: 'Clarity creates momentum. Start messy, then refine.' },
        ].map(c => (
          <div key={c.n} style={{
            padding: 24, borderRadius: 14,
            background: 'var(--paper-deep)',
            border: '1px solid var(--line-soft)',
          }}>
            <div className="mono" style={{ fontSize: 11, color: 'var(--blue)', letterSpacing: '0.08em', marginBottom: 14 }}>{c.n}</div>
            <div style={{ fontSize: 16, fontWeight: 600, lineHeight: 1.35, marginBottom: 8 }}>{c.t}</div>
            <div style={{ fontSize: 14, lineHeight: 1.5, color: 'var(--ink-muted)' }}>{c.s}</div>
          </div>
        ))}
      </div>

      {/* Calculator */}
      <Card style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{
          padding: '28px 36px 24px',
          borderBottom: '1px solid var(--line-soft)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
        }}>
          <div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--blue)', letterSpacing: '0.08em', marginBottom: 6 }}>CALCULATOR</div>
            <div className="serif" style={{ fontSize: 26, letterSpacing: '-0.02em' }}>Your hourly rate</div>
          </div>
          <div style={{ fontSize: 13, color: 'var(--ink-muted)', maxWidth: 260, textAlign: 'right' }}>
            Round numbers. A gut-check, not accounting.
          </div>
        </div>

        <div style={{ padding: 36, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32 }} className="bm-pb-calc-grid">
          <NumberField
            label="Hours you work per week"
            suffix="hrs / week"
            value={hoursPerWeek}
            onChange={updateHours}
            placeholder="50"
            max={168}
            hint="Including evenings and weekends if that's real."
          />
          <CurrencyField
            label="Annual income"
            value={annualIncome}
            onChange={updateIncome}
            placeholder="250,000"
            hint="Your take, not company revenue. Type any number. No cap."
          />
        </div>

        {/* Hourly rate result */}
        <div style={{
          padding: '32px 36px 28px',
          background: 'linear-gradient(180deg, var(--paper-deep) 0%, #fff 100%)',
          borderTop: '1px solid var(--line-soft)',
        }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1px 1fr', gap: 24, alignItems: 'center' }} className="bm-pb-stat-row">
            <Stat label="Your hourly rate" value={`$${hourly}`} big tone="ink" />
            <div style={{ width: 1, background: 'var(--line-soft)', height: 60 }} />
            <Stat label="Delegate anything under" value={`$${Math.round(hourly * 0.5)}/hr`} tone="blue" hint="Rule of thumb: ~50% of your rate" />
          </div>
        </div>

        {/* Promoted: delegatable hours slider */}
        <div style={{
          padding: '28px 36px 28px',
          borderTop: '1px solid var(--line-soft)',
          background: '#fff',
        }}>
          <div className="serif" style={{
            fontSize: 22, letterSpacing: '-0.02em', color: 'var(--ink)',
            marginBottom: 20, textAlign: 'center',
          }}>
            Now, how many hours a week could a VA <em style={{ fontWeight: 700, color: 'var(--blue)' }}>take off your plate?</em>
          </div>
          <div style={{ maxWidth: 520, margin: '0 auto' }}>
            <NumberField
              label="Hours you could delegate"
              suffix="hrs / week"
              value={delegatableHours}
              onChange={updateDelegatable}
              placeholder="10"
              max={168}
              hint="Inbox, scheduling, research, follow-ups, data entry. The small stuff that adds up."
            />
          </div>
        </div>

        {/* HERO: the cost. Midnight indigo, matching the homepage TimeBackCalculator */}
        <div style={{
          padding: '44px 36px 40px',
          background: 'linear-gradient(160deg, #161B3D 0%, #0A1028 100%)',
          color: '#fff',
          position: 'relative',
          overflow: 'hidden',
          textAlign: 'center',
        }}>
          <div style={{
            position: 'absolute', bottom: -100, left: -60, width: 320, height: 320,
            borderRadius: '50%',
            background: 'radial-gradient(circle, rgba(85,166,229,0.28) 0%, transparent 70%)',
            pointerEvents: 'none',
          }} />
          <div className="mono" style={{
            fontSize: 11.5, color: 'rgba(255,255,255,0.92)', letterSpacing: '0.14em',
            textTransform: 'uppercase', fontWeight: 500,
            marginBottom: 14, position: 'relative',
          }}>
            Hours you'd get back by delegating
          </div>
          <div className="serif" style={{
            fontSize: 96, lineHeight: 0.95, letterSpacing: '-0.035em',
            fontVariantNumeric: 'tabular-nums',
            color: '#fff', position: 'relative',
            whiteSpace: 'nowrap',
          }}>
            {annualHoursBack.toLocaleString()}<span style={{ fontSize: 32, color: 'rgba(255,255,255,0.88)', marginLeft: 8 }}>hrs/yr</span>
          </div>
          <div style={{
            fontSize: 15, color: 'rgba(255,255,255,0.92)',
            lineHeight: 1.55,
            marginTop: 14, position: 'relative',
          }}>
            That's about <strong style={{ color: '#fff', fontWeight: 600 }}>{weeksBack} full work weeks</strong> back, or roughly <strong style={{ color: '#fff', fontWeight: 600 }}>{dailyBack} hours a day</strong> for family, focus, or higher-leverage work.
          </div>
        </div>

        {/* Three questions */}
        <div style={{ padding: '28px 36px 36px', borderTop: '1px solid var(--line-soft)' }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', marginBottom: 16, letterSpacing: '-0.01em' }}>
            As you look at your week, ask three questions:
          </div>
          <div style={{ display: 'grid', gap: 10 }}>
            {[
              `Is this task worth my time at $${hourly}/hr?`,
              'Could someone else do this just as well, or better?',
              'Is this task helping me grow, or keeping me stuck?',
            ].map((q, i) => (
              <div key={i} style={{
                display: 'flex', gap: 12,
                padding: '12px 16px',
                background: 'var(--paper-deep)',
                borderRadius: 10,
                fontSize: 14,
                color: 'var(--ink-soft)',
              }}>
                <span className="mono" style={{ fontSize: 11, color: 'var(--blue)', fontWeight: 600, paddingTop: 2 }}>Q{i + 1}</span>
                <span>{q}</span>
              </div>
            ))}
          </div>
        </div>
      </Card>

      <div style={{ marginTop: 40, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }} className="bm-pb-footer-row">
        <div style={{ fontSize: 13, color: 'var(--ink-muted)' }}>
          Auto-saved · Your progress stays on this device
        </div>
        <PrimaryBtn onClick={() => { setState(s => ({ ...s, completedPhases: { ...s.completedPhases, p1: true } })); onComplete(); }}>
          Continue to Phase 2
          <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>
    </PbSection>
  );
}

function SliderField({ label, value, min, max, step, onChange, prefix, suffix, hint }) {
  const pct = ((value - min) / (max - min)) * 100;
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
        <label style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink-soft)', letterSpacing: '-0.01em' }}>{label}</label>
        <div className="mono" style={{ fontSize: 22, fontWeight: 500, color: 'var(--ink)', letterSpacing: '-0.02em' }}>
          {prefix}{value.toLocaleString()}{suffix ? ' ' + suffix : ''}
        </div>
      </div>
      <div style={{ position: 'relative', padding: '6px 0' }}>
        <div style={{ height: 4, background: 'var(--line-soft)', borderRadius: 2, position: 'relative' }}>
          <div style={{ position: 'absolute', left: 0, top: 0, height: '100%', width: `${pct}%`, background: 'var(--blue)', borderRadius: 2 }} />
        </div>
        <input
          type="range"
          min={min} max={max} step={step} value={value}
          onChange={(e) => onChange(Number(e.target.value))}
          style={{
            position: 'absolute', top: 0, left: 0, width: '100%', height: 16,
            opacity: 0, cursor: 'pointer', margin: 0,
          }}
        />
        <div style={{
          position: 'absolute',
          left: `calc(${pct}% - 8px)`,
          top: 2,
          width: 16, height: 16, borderRadius: 8,
          background: '#fff', border: '2px solid var(--blue)',
          boxShadow: '0 1px 3px rgba(0,0,0,0.15)',
          pointerEvents: 'none',
        }} />
      </div>
      {hint && <div style={{ fontSize: 12, color: 'var(--ink-muted)', marginTop: 10 }}>{hint}</div>}
    </div>
  );
}

function Stat({ label, value, hint, tone = 'ink', big }) {
  const toneColor = tone === 'blue' ? 'var(--blue)' : tone === 'amber' ? 'var(--amber)' : 'var(--ink)';
  return (
    <div>
      <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-muted)', marginBottom: 8, fontWeight: 500 }}>{label}</div>
      <div className="serif" style={{ fontSize: big ? 52 : 38, lineHeight: 1, letterSpacing: '-0.03em', color: toneColor, marginBottom: hint ? 6 : 0 }}>
        {value}
      </div>
      {hint && <div style={{ fontSize: 12, color: 'var(--ink-muted)', lineHeight: 1.4 }}>{hint}</div>}
    </div>
  );
}

function NumberField({ label, value, onChange, placeholder, suffix, max = 9999, hint }) {
  const [focused, setFocused] = React.useState(false);
  const display = value > 0 ? String(value) : '';

  const handleChange = (e) => {
    const digits = e.target.value.replace(/[^0-9]/g, '');
    let n = digits === '' ? 0 : parseInt(digits, 10);
    if (Number.isFinite(max) && n > max) n = max;
    onChange(Number.isFinite(n) ? n : 0);
  };

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
        <label style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink-soft)', letterSpacing: '-0.01em' }}>{label}</label>
        <div className="mono" style={{ fontSize: 11, color: 'var(--ink-muted)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>{suffix}</div>
      </div>
      <div style={{
        position: 'relative',
        display: 'flex', alignItems: 'center',
        background: '#fff',
        border: `1px solid ${focused ? 'var(--blue)' : 'var(--line)'}`,
        borderRadius: 10,
        padding: '12px 14px',
        boxShadow: focused ? '0 0 0 3px rgba(8,120,216,0.12)' : 'none',
        transition: 'border-color 120ms, box-shadow 120ms',
      }}>
        <input
          type="text"
          inputMode="numeric"
          autoComplete="off"
          value={display}
          onChange={handleChange}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          placeholder={placeholder}
          aria-label={label}
          className="mono"
          style={{
            flex: 1, minWidth: 0,
            border: 'none', outline: 'none', background: 'transparent',
            fontSize: 22, fontWeight: 500, color: 'var(--ink)',
            letterSpacing: '-0.02em',
            padding: 0, margin: 0,
            fontVariantNumeric: 'tabular-nums',
          }}
        />
      </div>
      {hint && <div style={{ fontSize: 12, color: 'var(--ink-muted)', marginTop: 10 }}>{hint}</div>}
    </div>
  );
}

Object.assign(window, { Hero, Phase1, SliderField, NumberField, CurrencyField, Stat });

function CurrencyField({ label, value, onChange, placeholder, hint }) {
  // Format with comma separators so big numbers stay readable as the user types.
  const [focused, setFocused] = React.useState(false);
  const display = focused
    ? (value > 0 ? String(value) : '')
    : (value > 0 ? value.toLocaleString() : '');

  const handleChange = (e) => {
    // Strip everything that isn't a digit, then parse. No cap.
    const digits = e.target.value.replace(/[^0-9]/g, '');
    const n = digits === '' ? 0 : parseInt(digits, 10);
    onChange(Number.isFinite(n) ? n : 0);
  };

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
        <label style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink-soft)', letterSpacing: '-0.01em' }}>{label}</label>
        <div className="mono" style={{ fontSize: 11, color: 'var(--ink-muted)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>USD / year</div>
      </div>
      <div style={{
        position: 'relative',
        display: 'flex', alignItems: 'center',
        background: '#fff',
        border: `1px solid ${focused ? 'var(--blue)' : 'var(--line)'}`,
        borderRadius: 10,
        padding: '12px 14px',
        boxShadow: focused ? '0 0 0 3px rgba(8,120,216,0.12)' : 'none',
        transition: 'border-color 120ms, box-shadow 120ms',
      }}>
        <span className="mono" style={{
          fontSize: 22, fontWeight: 500, color: 'var(--ink-muted)',
          marginRight: 6, letterSpacing: '-0.02em',
        }}>$</span>
        <input
          type="text"
          inputMode="numeric"
          autoComplete="off"
          value={display}
          onChange={handleChange}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          placeholder={placeholder}
          className="mono"
          style={{
            flex: 1, minWidth: 0,
            border: 'none', outline: 'none', background: 'transparent',
            fontSize: 22, fontWeight: 500, color: 'var(--ink)',
            letterSpacing: '-0.02em',
            padding: 0, margin: 0,
            fontVariantNumeric: 'tabular-nums',
          }}
        />
      </div>
      {hint && <div style={{ fontSize: 12, color: 'var(--ink-muted)', marginTop: 10 }}>{hint}</div>}
    </div>
  );
}
