// Shared utilities and shell components for the Delegation Playbook

const STORAGE_KEY = 'bluemoso_playbook_v3';

function loadState() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return null;
    return JSON.parse(raw);
  } catch (e) { return null; }
}

function saveState(state) {
  try { localStorage.setItem(STORAGE_KEY, JSON.stringify(state)); } catch (e) {}
}

function usePlaybookState() {
  const [state, setState] = React.useState(() => loadState() || {
    hoursPerWeek: 0,
    annualIncome: 0,
    tasks: [],
    blueprintPicks: [], // array of task ids (up to 3) with {taskId, doneLooksLike, tool}
    email: '',
    emailSubmitted: false,
    completedPhases: { p1: false, p2: false, p3: false },
    startedAt: Date.now(),
  });

  React.useEffect(() => { saveState(state); }, [state]);

  return [state, setState];
}

// Shared layout components
function PlaybookNav({ currentPhase, onJump, completed }) {
  const phases = [
    { id: 'p1', label: 'Mindset', n: 1 },
    { id: 'p2', label: 'Audit', n: 2 },
    { id: 'p3', label: 'Blueprint', n: 3 },
    { id: 'p4', label: 'Results', n: 4 },
  ];
  // Hide on scroll-down, show on scroll-up (mirrors main Nav)
  const [hidden, setHidden] = React.useState(false);
  React.useEffect(() => {
    let lastY = window.scrollY;
    let ticking = false;
    const onScroll = () => {
      if (ticking) return;
      ticking = true;
      window.requestAnimationFrame(() => {
        const y = window.scrollY;
        const delta = y - lastY;
        if (y < 80) setHidden(false);
        else if (delta > 6) setHidden(true);
        else if (delta < -6) setHidden(false);
        lastY = y;
        ticking = false;
      });
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav className="playbook-nav no-print" style={{ ...pbNavStyles.wrap, transform: hidden ? 'translateY(-200%)' : 'translateY(0)' }}>
      <div style={pbNavStyles.inner}>
        <a href="index.html" style={pbNavStyles.back}>
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M10 4 6 8l4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
          BlueMoso
        </a>
        <div style={pbNavStyles.phases}>
          {phases.map((p, i) => {
            const done = completed[p.id];
            const active = currentPhase === p.id;
            return (
              <React.Fragment key={p.id}>
                <button onClick={() => onJump(p.id)}
                  aria-current={active ? 'step' : undefined}
                  aria-label={`Phase ${p.n} ${p.label}${active ? ' (current)' : (done ? ' (completed)' : '')}`}
                  style={{
                  ...pbNavStyles.phaseBtn,
                  color: active ? 'var(--ink)' : (done ? 'var(--blue)' : 'var(--ink-muted)'),
                  fontWeight: active ? 600 : 500,
                }}>
                  <span style={{
                    ...pbNavStyles.phaseNum,
                    background: active ? 'var(--ink)' : (done ? 'var(--blue)' : 'transparent'),
                    color: (active || done) ? '#fff' : 'var(--ink-muted)',
                    border: (active || done) ? 'none' : '1px solid var(--line)',
                  }}>
                    {done && !active ? '✓' : p.n}
                  </span>
                  <span className="bm-pb-nav-phase-label">{p.label}</span>
                </button>
                {i < phases.length - 1 && <div style={pbNavStyles.spacer} />}
              </React.Fragment>
            );
          })}
        </div>
        <button className="bm-pb-nav-reset" onClick={() => { if (confirm('Clear all playbook progress?')) { localStorage.removeItem(STORAGE_KEY); location.reload(); } }} style={pbNavStyles.reset}>Reset</button>
      </div>
    </nav>
  );
}

const pbNavStyles = {
  wrap: {
    position: 'sticky', top: 57, zIndex: 40,
    background: 'rgba(255,255,255,0.92)',
    backdropFilter: 'blur(10px)',
    WebkitBackdropFilter: 'blur(10px)',
    borderBottom: '1px solid var(--line-soft)',
    transition: 'transform .28s ease',
    willChange: 'transform',
  },
  inner: {
    maxWidth: 1180, margin: '0 auto',
    padding: '14px 32px',
    display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 24,
  },
  back: {
    fontSize: 13, fontWeight: 500, color: 'var(--ink-muted)',
    display: 'inline-flex', alignItems: 'center', gap: 6,
    transition: 'color .15s',
  },
  phases: { display: 'flex', alignItems: 'center', gap: 6 },
  phaseBtn: {
    display: 'inline-flex', alignItems: 'center', gap: 8,
    fontSize: 13, padding: '6px 10px', borderRadius: 8,
    transition: 'color .15s, background .15s',
  },
  phaseNum: {
    width: 22, height: 22, borderRadius: 11,
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    fontSize: 11, fontWeight: 600,
  },
  spacer: { width: 14, height: 1, background: 'var(--line)' },
  reset: { fontSize: 12, color: 'var(--ink-muted)', padding: '6px 10px' },
};

// Phase header
function PhaseHeader({ num, kicker, title, italic, subtitle }) {
  return (
    <div style={phaseHeaderStyles.wrap}>
      <div style={phaseHeaderStyles.kicker}>
        <span style={phaseHeaderStyles.phaseNum}>Phase 0{num}</span>
        <span style={phaseHeaderStyles.dot} />
        <span>{kicker}</span>
      </div>
      <h2 className="serif bm-pb-phase-title" style={phaseHeaderStyles.title}>
        {title} {italic && <em style={{ color: 'var(--blue)', fontWeight: 700 }}>{italic}</em>}
      </h2>
      {subtitle && <p className="bm-pb-phase-sub" style={phaseHeaderStyles.sub}>{subtitle}</p>}
    </div>
  );
}

const phaseHeaderStyles = {
  wrap: { marginBottom: 40 },
  kicker: {
    display: 'inline-flex', alignItems: 'center', gap: 10,
    fontSize: 12, color: 'var(--blue)', fontWeight: 500,
    padding: '6px 12px', borderRadius: 999,
    background: 'var(--blue-soft)',
    marginBottom: 20,
    letterSpacing: '0.02em',
    whiteSpace: 'nowrap',
  },
  phaseNum: { fontFamily: "'Outfit', system-ui, sans-serif", fontVariantNumeric: 'tabular-nums', fontSize: 11, letterSpacing: '0.08em' },
  dot: { width: 4, height: 4, borderRadius: 2, background: 'var(--blue)' },
  title: {
    fontSize: 48, lineHeight: 1.02, letterSpacing: '-0.03em',
    color: 'var(--ink)', marginBottom: 16,
  },
  sub: {
    fontSize: 17, lineHeight: 1.55, color: 'var(--ink-muted)',
    maxWidth: 640,
  },
};

// Section wrapper
function PbSection({ children, id, bg, narrow }) {
  return (
    <section id={id} className="bm-pb-section" style={{
      padding: '80px 32px',
      background: bg || 'transparent',
      borderBottom: bg ? 'none' : '1px solid var(--line-soft)',
    }}>
      <div style={{ maxWidth: narrow ? 820 : 1080, margin: '0 auto' }}>
        {children}
      </div>
    </section>
  );
}

// Button primitives
function PrimaryBtn({ children, onClick, full, style }) {
  return (
    <button onClick={onClick} style={{
      background: 'var(--ink)', color: '#fff',
      padding: '14px 24px', borderRadius: 12,
      fontSize: 14, fontWeight: 500,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      transition: 'background .2s, transform .1s',
      width: full ? '100%' : 'auto',
      ...style,
    }} onMouseEnter={(e) => e.currentTarget.style.background = 'var(--blue-deep)'} onMouseLeave={(e) => e.currentTarget.style.background = 'var(--ink)'}>
      {children}
    </button>
  );
}

function GhostBtn({ children, onClick, full, style }) {
  return (
    <button onClick={onClick} style={{
      background: 'transparent', color: 'var(--ink)',
      padding: '14px 22px', borderRadius: 12,
      fontSize: 14, fontWeight: 500,
      border: '1px solid var(--line)',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      transition: 'background .15s, border-color .15s',
      width: full ? '100%' : 'auto',
      ...style,
    }} onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--paper-deep)'; }} onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}>
      {children}
    </button>
  );
}

// Card
function Card({ children, style }) {
  return (
    <div className="pdf-card" style={{
      background: '#fff',
      border: '1px solid var(--line-soft)',
      borderRadius: 16,
      padding: 32,
      boxShadow: 'var(--shadow-md)',
      ...style,
    }}>{children}</div>
  );
}

Object.assign(window, {
  STORAGE_KEY, loadState, saveState, usePlaybookState,
  PlaybookNav, PhaseHeader, PbSection, PrimaryBtn, GhostBtn, Card,
});
