// Phase 3: The Delegation Blueprint

const TOOL_OPTIONS = [
  'Slack / Loom',
  'ClickUp',
  'Asana',
  'Notion',
  'Google Drive',
  'Email / doc',
  'Something else',
];

function Phase3({ state, setState, onComplete, onBack }) {
  const { tasks, blueprintPicks } = state;

  // Only tasks classified delegate or find are eligible
  const eligible = tasks.filter(t => classifyTask(t) !== 'keep');

  const toggleTask = (taskId) => {
    setState(s => {
      const existing = s.blueprintPicks.find(p => p.taskId === taskId);
      if (existing) {
        return { ...s, blueprintPicks: s.blueprintPicks.filter(p => p.taskId !== taskId) };
      }
      if (s.blueprintPicks.length >= 3) return s;
      return { ...s, blueprintPicks: [...s.blueprintPicks, { taskId, doneLooksLike: '', tool: '' }] };
    });
  };

  const updatePick = (taskId, patch) => {
    setState(s => ({
      ...s,
      blueprintPicks: s.blueprintPicks.map(p => p.taskId === taskId ? { ...p, ...patch } : p),
    }));
  };

  const canContinue = blueprintPicks.length > 0;
  const candidatesRef = React.useRef(null);
  const [nudge, setNudge] = React.useState(false);

  const tryContinue = () => {
    if (canContinue) {
      setState(s => ({ ...s, completedPhases: { ...s.completedPhases, p3: true } }));
      onComplete();
      return;
    }
    if (candidatesRef.current) {
      const top = candidatesRef.current.getBoundingClientRect().top + window.pageYOffset - 100;
      window.scrollTo({ top, behavior: 'smooth' });
      setNudge(true);
      setTimeout(() => setNudge(false), 800);
    }
  };

  return (
    <PbSection id="phase3" narrow>
      <PhaseHeader
        num="3"
        kicker="Make your delegation plan"
        title="Pick your top 3."
        italic="Define done."
        subtitle="Tick up to three delegation candidates from your audit. For each, sketch what 'done' looks like and where you'll hand it off. This is the difference between 'I should delegate this' and actually delegating."
      />

      {/* The 5-step blueprint */}
      <div style={{
        padding: '24px 28px',
        background: 'var(--paper-deep)',
        border: '1px solid var(--line-soft)',
        borderRadius: 14,
        marginBottom: 40,
      }}>
        <div className="mono" style={{ fontSize: 11, color: 'var(--blue)', letterSpacing: '0.08em', marginBottom: 12 }}>THE BLUEPRINT</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12 }} className="bm-pb-blueprint-5">
          {[
            { n: 1, t: 'Inventory', s: 'List what you do' },
            { n: 2, t: 'Sort', s: 'Do, delegate, delete' },
            { n: 3, t: 'Prep', s: "Define 'done'" },
            { n: 4, t: 'Assign', s: 'Hand off in a tool' },
            { n: 5, t: 'Review', s: 'Follow up, feedback' },
          ].map(s => (
            <div key={s.n}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                <div style={{
                  width: 18, height: 18, borderRadius: 9,
                  background: 'var(--ink)', color: '#fff',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 10, fontWeight: 600,
                }}>{s.n}</div>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{s.t}</div>
              </div>
              <div style={{ fontSize: 12, color: 'var(--ink-muted)', lineHeight: 1.4 }}>{s.s}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Task picker */}
      <div ref={candidatesRef} className={nudge ? 'bm-pb-nudge' : ''} style={{ marginBottom: 32 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>Select up to 3 tasks to delegate first</div>
          <div style={{ fontSize: 12, color: 'var(--ink-muted)' }}>{blueprintPicks.length} / 3 selected</div>
        </div>

        {eligible.length === 0 ? (
          <div style={{
            padding: 32, textAlign: 'center',
            background: 'var(--paper-deep)', borderRadius: 12,
            color: 'var(--ink-muted)', fontSize: 14,
          }}>
            No delegation candidates in your audit yet. <button onClick={onBack} style={{ color: 'var(--blue)', fontWeight: 500 }}>Go back</button> and add more tasks.
          </div>
        ) : (
          <div style={{ display: 'grid', gap: 8 }}>
            {eligible.map(t => {
              const picked = blueprintPicks.some(p => p.taskId === t.id);
              const zone = classifyTask(t);
              const meta = zoneMeta(zone);
              const disabled = !picked && blueprintPicks.length >= 3;
              return (
                <button
                  key={t.id}
                  onClick={() => toggleTask(t.id)}
                  disabled={disabled}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 16,
                    padding: '14px 18px',
                    border: `1px solid ${picked ? 'var(--blue)' : 'var(--line)'}`,
                    background: picked ? 'var(--blue-soft)' : '#fff',
                    borderRadius: 12,
                    textAlign: 'left',
                    opacity: disabled ? 0.4 : 1,
                    cursor: disabled ? 'not-allowed' : 'pointer',
                    transition: 'all .15s',
                  }}>
                  <div style={{
                    width: 22, height: 22, borderRadius: 6,
                    border: `1.5px solid ${picked ? 'var(--blue)' : 'var(--line)'}`,
                    background: picked ? 'var(--blue)' : '#fff',
                    color: '#fff',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 12, fontWeight: 700,
                    flexShrink: 0,
                  }}>{picked && '✓'}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 15, fontWeight: 500, color: 'var(--ink)' }}>{t.name || 'Untitled task'}</div>
                    <div style={{ fontSize: 12, color: 'var(--ink-muted)', marginTop: 2 }}>{t.hours} hrs/wk · {t.impact} impact · {t.expertise} expertise</div>
                  </div>
                  <div style={{
                    display: 'inline-flex', alignItems: 'center', gap: 6,
                    padding: '4px 10px', borderRadius: 999,
                    background: meta.bg, border: `1px solid ${meta.border}`,
                    fontSize: 11, fontWeight: 500,
                    color: meta.tone === 'blue' ? 'var(--blue)' : meta.tone === 'amber' ? 'var(--amber)' : 'var(--ink)',
                  }}>{meta.label}</div>
                </button>
              );
            })}
          </div>
        )}
      </div>

      {/* Prep cards for picked tasks */}
      {blueprintPicks.length > 0 && (
        <div style={{ marginBottom: 40 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)', marginBottom: 14 }}>Define what 'done' looks like</div>
          <div style={{ display: 'grid', gap: 14 }}>
            {blueprintPicks.map((p, i) => {
              const task = tasks.find(t => t.id === p.taskId);
              if (!task) return null;
              return (
                <Card key={p.taskId} style={{ padding: 0 }}>
                  <div style={{
                    display: 'flex', alignItems: 'center', gap: 12,
                    padding: '16px 24px',
                    borderBottom: '1px solid var(--line-soft)',
                    background: 'var(--paper-deep)',
                  }}>
                    <div className="mono" style={{
                      fontSize: 11, color: 'var(--blue)', fontWeight: 600, letterSpacing: '0.08em',
                    }}>PICK {i + 1}</div>
                    <div style={{ fontSize: 15, fontWeight: 600 }}>{task.name}</div>
                    <div style={{ marginLeft: 'auto', fontSize: 12, color: 'var(--ink-muted)' }}>{task.hours} hrs/wk</div>
                  </div>
                  <div style={{ padding: 24, display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 20 }} className="bm-pb-prep-grid">
                    <div>
                      <label style={prepLabel}>What "done" looks like</label>
                      <textarea
                        value={p.doneLooksLike}
                        onChange={(e) => updatePick(p.taskId, { doneLooksLike: e.target.value })}
                        placeholder="e.g. Inbox triaged by 9am and 3pm daily. VIPs flagged. Canned replies for FAQs. Unread count below 10 at end of day."
                        rows={3}
                        style={prepInput}
                      />
                      <div style={{ fontSize: 11, color: 'var(--ink-muted)', marginTop: 6 }}>
                        Be specific. Cadence, quality bar, what "good" looks like.
                      </div>
                    </div>
                    <div>
                      <label style={prepLabel}>Where you'll assign it</label>
                      <select value={p.tool} onChange={(e) => updatePick(p.taskId, { tool: e.target.value })} style={{ ...prepInput, appearance: 'menulist-button' }}>
                        <option value="">Pick a tool…</option>
                        {TOOL_OPTIONS.map(o => <option key={o} value={o}>{o}</option>)}
                      </select>
                      <div style={{ fontSize: 11, color: 'var(--ink-muted)', marginTop: 6 }}>
                        Pick one. Don't spread handoff across channels.
                      </div>
                    </div>
                  </div>
                </Card>
              );
            })}
          </div>
        </div>
      )}

      {/* Tips */}
      <div style={{
        padding: '24px 28px',
        background: '#fff',
        border: '1px solid var(--line-soft)',
        borderRadius: 14,
        marginBottom: 40,
      }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', marginBottom: 12 }}>Five rules that make delegation stick</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 10 }} className="bm-pb-rules">
          {[
            { t: 'Start small', s: 'One task at a time' },
            { t: 'Batch similar work', s: 'Group by context' },
            { t: 'Record walkthroughs', s: 'Loom > written SOP' },
            { t: 'Give feedback', s: 'In the first week' },
            { t: 'Be patient', s: 'It gets easier' },
          ].map((tip, i) => (
            <div key={i} style={{ fontSize: 12, lineHeight: 1.45 }}>
              <div style={{ fontWeight: 600, color: 'var(--ink)', marginBottom: 2 }}>{tip.t}</div>
              <div style={{ color: 'var(--ink-muted)' }}>{tip.s}</div>
            </div>
          ))}
        </div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }} className="bm-pb-footer-row">
        <GhostBtn onClick={onBack}>← Phase 2</GhostBtn>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <div className="bm-pb-footer-hint" style={{ fontSize: 13, color: canContinue ? 'var(--ink-muted)' : 'var(--amber)', fontWeight: canContinue ? 400 : 500 }}>
            {canContinue ? 'Ready to see your results' : 'Pick at least one task above to continue'}
          </div>
          <PrimaryBtn onClick={tryContinue} style={{ opacity: canContinue ? 1 : 0.55 }}>
            See your results
            <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>
    </PbSection>
  );
}

const prepLabel = {
  display: 'block',
  fontSize: 12, fontWeight: 500, color: 'var(--ink-soft)',
  marginBottom: 8, letterSpacing: '-0.01em',
};

const prepInput = {
  width: '100%',
  padding: '10px 12px',
  fontSize: 14,
  border: '1px solid var(--line)',
  borderRadius: 8,
  background: '#fff',
  resize: 'vertical',
  fontFamily: 'inherit',
};

Object.assign(window, { Phase3 });
