// Phase 2: Task Audit + Impact Matrix classifier

const SEED_TASKS = [
  { name: 'Inbox management', hours: 5, impact: 'low', expertise: 'low' },
  { name: 'Social media scheduling', hours: 3, impact: 'medium', expertise: 'low' },
  { name: 'Client calls', hours: 6, impact: 'high', expertise: 'high' },
  { name: 'Expense & bookkeeping', hours: 2, impact: 'medium', expertise: 'medium' },
  { name: 'Content writing', hours: 4, impact: 'high', expertise: 'medium' },
];

// Classification rule from the playbook:
// Only High Impact + High Expertise → KEEP
// High Impact + Low/Medium Expertise → DELEGATE to VA (Give)
// Anything requiring specialist → FIND (we mark medium expertise w/ specialized tone as FIND when tagged)
// Low impact → always DELEGATE
function classifyTask(t) {
  if (t.impact === 'high' && t.expertise === 'high') return 'keep';
  if (t.expertise === 'specialist') return 'find';
  if (t.impact === 'high' && t.expertise === 'medium') return 'find';
  return 'delegate';
}

function zoneMeta(z) {
  if (z === 'keep') return { label: 'Keep', tone: 'ink', bg: 'var(--paper-deep)', border: 'var(--line)', icon: '👤', blurb: 'Only you can do this well' };
  if (z === 'delegate') return { label: 'Delegate', tone: 'blue', bg: 'var(--blue-soft)', border: 'rgba(8,120,216,0.2)', icon: '✓', blurb: 'A VA can handle this' };
  return { label: 'Find specialist', tone: 'amber', bg: '#FEF6E7', border: 'rgba(183,110,0,0.2)', icon: '⚲', blurb: 'Hire a pro or use a tool' };
}

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

  const addTask = (t = { name: '', hours: 1, impact: 'medium', expertise: 'low' }) => {
    setState(s => ({ ...s, tasks: [...s.tasks, { ...t, id: Date.now() + Math.random() }] }));
  };

  const addAllSeeds = () => {
    setState(s => {
      const existingNames = new Set(s.tasks.map(t => t.name.toLowerCase()));
      const toAdd = SEED_TASKS.filter(t => !existingNames.has(t.name.toLowerCase()))
        .map(t => ({ ...t, id: Date.now() + Math.random() + Math.random() }));
      return { ...s, tasks: [...s.tasks, ...toAdd] };
    });
  };

  const updateTask = (id, patch) => {
    setState(s => ({ ...s, tasks: s.tasks.map(t => t.id === id ? { ...t, ...patch } : t) }));
  };

  const removeTask = (id) => {
    setState(s => ({ ...s, tasks: s.tasks.filter(t => t.id !== id) }));
  };

  // Totals
  const totals = React.useMemo(() => {
    const totalHours = tasks.reduce((a, t) => a + (Number(t.hours) || 0), 0);
    const delegateHours = tasks.filter(t => classifyTask(t) === 'delegate').reduce((a, t) => a + (Number(t.hours) || 0), 0);
    const findHours = tasks.filter(t => classifyTask(t) === 'find').reduce((a, t) => a + (Number(t.hours) || 0), 0);
    const keepHours = tasks.filter(t => classifyTask(t) === 'keep').reduce((a, t) => a + (Number(t.hours) || 0), 0);
    const offloadHours = delegateHours + findHours;
    // Hours reclaimed across the year, 50 working weeks. The number that actually matters.
    const annualHoursReclaimed = offloadHours * 50;
    return { totalHours, delegateHours, findHours, keepHours, offloadHours, annualHoursReclaimed };
  }, [tasks]);

  const canContinue = tasks.length >= 3 && tasks.every(t => t.name.trim());
  const taskCardRef = React.useRef(null);
  const [nudge, setNudge] = React.useState(false);

  const tryContinue = () => {
    if (canContinue) {
      setState(s => ({ ...s, completedPhases: { ...s.completedPhases, p2: true } }));
      onComplete();
      return;
    }
    // Feedback for blocked state: scroll back to task card + nudge animation + focus first empty
    if (taskCardRef.current) {
      const top = taskCardRef.current.getBoundingClientRect().top + window.pageYOffset - 100;
      window.scrollTo({ top, behavior: 'smooth' });
      setNudge(true);
      setTimeout(() => setNudge(false), 800);
      setTimeout(() => {
        const inputs = taskCardRef.current.querySelectorAll('input[type="text"]');
        const empty = [...inputs].find(i => !i.value.trim());
        if (empty) empty.focus();
        else if (tasks.length < 3) {
          // Auto-add a row to push them forward
          addTask();
        }
      }, 350);
    }
  };

  return (
    <PbSection id="phase2">
      <PhaseHeader
        num="2"
        kicker="Audit your reality"
        title="List your tasks,"
        italic="see where your time goes."
        subtitle="Log your recurring weekly tasks. We'll sort them into Keep, Delegate, or Find automatically using the Impact × Expertise matrix. Aim for 5–10 tasks."
      />

      {/* Impact matrix legend */}
      <div style={{ display: 'grid', gridTemplateColumns: '260px 1fr', gap: 40, alignItems: 'start', marginBottom: 48 }} className="bm-pb-matrix-row">
        <div>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', marginBottom: 14 }}>The Impact Matrix</div>
          <div style={{ fontSize: 13, lineHeight: 1.55, color: 'var(--ink-muted)', marginBottom: 20 }}>
            Only jobs that are <strong style={{ color: 'var(--ink)' }}>high-impact</strong> <em>and</em> in your <strong style={{ color: 'var(--ink)' }}>zone of genius</strong> stay on your plate. Everything else is a delegation candidate.
          </div>
          <button onClick={addAllSeeds} style={{
            fontSize: 13, color: 'var(--blue)', fontWeight: 500,
            display: 'inline-flex', alignItems: 'center', gap: 6,
          }}>
            <span>+</span> Start with common examples
          </button>
        </div>

        <div style={{
          display: 'grid',
          gridTemplateColumns: '72px 1fr 1fr',
          gridTemplateRows: 'auto 1fr 1fr',
          gap: 1,
          background: 'var(--line-soft)',
          borderRadius: 14,
          overflow: 'hidden',
          border: '1px solid var(--line-soft)',
        }}>
          <div style={matrixCell({ bg: 'var(--paper-deep)' })} />
          <div style={matrixCell({ bg: 'var(--paper-deep)', fs: 11, color: 'var(--ink-muted)', pad: '10px 14px' })}>Low Expertise</div>
          <div style={matrixCell({ bg: 'var(--paper-deep)', fs: 11, color: 'var(--ink-muted)', pad: '10px 14px' })}>High Expertise</div>

          <div style={matrixCell({ bg: 'var(--paper-deep)', fs: 11, color: 'var(--ink-muted)', pad: '14px 10px', rotate: true })}>High Impact</div>
          <div style={matrixCell({ bg: 'var(--blue-soft)', fs: 14 })}><strong style={{ color: 'var(--blue)' }}>✓ Delegate</strong><div style={{ fontSize: 11, color: 'var(--ink-muted)', marginTop: 2 }}>Give to VA</div></div>
          <div style={matrixCell({ bg: '#fff', fs: 14 })}><strong>👤 Keep</strong><div style={{ fontSize: 11, color: 'var(--ink-muted)', marginTop: 2 }}>Your zone of genius</div></div>

          <div style={matrixCell({ bg: 'var(--paper-deep)', fs: 11, color: 'var(--ink-muted)', pad: '14px 10px', rotate: true })}>Low Impact</div>
          <div style={matrixCell({ bg: 'var(--blue-soft)', fs: 14 })}><strong style={{ color: 'var(--blue)' }}>✓ Delegate</strong><div style={{ fontSize: 11, color: 'var(--ink-muted)', marginTop: 2 }}>Easy wins</div></div>
          <div style={matrixCell({ bg: 'var(--blue-soft)', fs: 14 })}><strong style={{ color: 'var(--blue)' }}>✓ Delegate</strong><div style={{ fontSize: 11, color: 'var(--ink-muted)', marginTop: 2 }}>Not worth your rate</div></div>
        </div>
      </div>

      {/* Task table */}
      <div ref={taskCardRef} className={nudge ? 'bm-pb-nudge' : ''}>
      <Card style={{ padding: 0, overflow: 'hidden' }}>
        {/* Header row */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: '1.8fr 0.7fr 1fr 1fr 1.1fr 32px',
          gap: 16,
          padding: '16px 24px',
          background: 'var(--paper-deep)',
          borderBottom: '1px solid var(--line-soft)',
          fontSize: 11, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-muted)',
        }} className="bm-pb-task-row bm-pb-task-header">
          <div>Task</div>
          <div>Hrs / wk</div>
          <div>Impact</div>
          <div>Expertise</div>
          <div>Verdict</div>
          <div />
        </div>

        {/* Rows */}
        {tasks.length === 0 && (
          <div style={{ padding: '48px 24px', textAlign: 'center', color: 'var(--ink-muted)' }}>
            <div style={{ fontSize: 14, marginBottom: 16 }}>No tasks yet, add your first one.</div>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
              <PrimaryBtn onClick={() => addTask()} style={{ padding: '10px 18px', fontSize: 13 }}>+ Add task</PrimaryBtn>
              <GhostBtn onClick={addAllSeeds} style={{ padding: '10px 18px', fontSize: 13 }}>Use examples</GhostBtn>
            </div>
          </div>
        )}

        {tasks.map((t, i) => (
          <TaskRow key={t.id} task={t} index={i} onUpdate={(p) => updateTask(t.id, p)} onRemove={() => removeTask(t.id)} />
        ))}

        {tasks.length > 0 && (
          <div style={{ padding: '14px 24px', borderTop: '1px solid var(--line-soft)' }}>
            <button onClick={() => addTask()} style={{
              fontSize: 13, color: 'var(--blue)', fontWeight: 500,
              padding: '8px 12px', borderRadius: 8,
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              <span>+</span> Add another task
            </button>
          </div>
        )}
      </Card>
      </div>

      {/* Live summary */}
      {tasks.length > 0 && (
        <div style={{
          marginTop: 32,
          padding: 32, borderRadius: 16,
          background: 'var(--ink)', color: '#fff',
        }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 24 }} className="bm-pb-summary">
            <SummaryStat label="Tasks tracked" value={tasks.length} sub={`${totals.totalHours.toFixed(1)} hrs / wk total`} />
            <SummaryStat label="To delegate" value={`${totals.delegateHours.toFixed(1)} hrs`} sub="VA-ready work" tone="blue" />
            <SummaryStat label="To specialist" value={`${totals.findHours.toFixed(1)} hrs`} sub="Pros or tools" tone="amber" />
            <SummaryStat label="Hours reclaimed" value={`${Math.round(totals.annualHoursReclaimed).toLocaleString()} hrs`} sub="per year, off your plate" tone="green" />
          </div>
        </div>
      )}

      <div style={{ marginTop: 40, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }} className="bm-pb-footer-row">
        <GhostBtn onClick={onBack}>← Phase 1</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 plan your delegations' : tasks.length < 3 ? `Add ${3 - tasks.length} more task${3 - tasks.length === 1 ? '' : 's'} to continue` : 'Name all tasks to continue'}
          </div>
          <PrimaryBtn onClick={tryContinue} style={{ opacity: canContinue ? 1 : 0.55 }}>
            Continue to Phase 3
            <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>
  );
}

function TaskRow({ task, index, onUpdate, onRemove }) {
  const zone = classifyTask(task);
  const meta = zoneMeta(zone);

  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: '1.8fr 0.7fr 1fr 1fr 1.1fr 32px',
      gap: 16,
      padding: '14px 24px',
      borderBottom: '1px solid var(--line-soft)',
      alignItems: 'center',
    }} className="bm-pb-task-row">
      <input
        type="text"
        value={task.name}
        placeholder="e.g. Inbox management"
        onChange={(e) => onUpdate({ name: e.target.value })}
        style={taskInput}
      />
      <input
        type="number"
        value={task.hours}
        min={0} step={0.5}
        onChange={(e) => onUpdate({ hours: Number(e.target.value) })}
        style={{ ...taskInput, textAlign: 'right' }}
      />
      <Segmented
        value={task.impact}
        options={[{ v: 'low', l: 'Low' }, { v: 'medium', l: 'Med' }, { v: 'high', l: 'High' }]}
        onChange={(v) => onUpdate({ impact: v })}
      />
      <Segmented
        value={task.expertise}
        options={[{ v: 'low', l: 'Low' }, { v: 'medium', l: 'Med' }, { v: 'high', l: 'High' }, { v: 'specialist', l: 'Spec' }]}
        onChange={(v) => onUpdate({ expertise: v })}
      />
      <div style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        padding: '5px 10px', borderRadius: 999,
        background: meta.bg, border: `1px solid ${meta.border}`,
        fontSize: 12, fontWeight: 500,
        color: meta.tone === 'blue' ? 'var(--blue)' : meta.tone === 'amber' ? 'var(--amber)' : 'var(--ink)',
        width: 'fit-content',
      }}>
        <span>{meta.icon}</span>
        {meta.label}
      </div>
      <button onClick={onRemove} title="Remove" style={{
        width: 24, height: 24, borderRadius: 6,
        color: 'var(--ink-muted)', fontSize: 18, lineHeight: 1,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }} onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--paper-deep)'; e.currentTarget.style.color = 'var(--red)'; }} onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--ink-muted)'; }}>
        ×
      </button>
    </div>
  );
}

const taskInput = {
  width: '100%',
  padding: '8px 10px',
  fontSize: 14,
  border: '1px solid transparent',
  borderRadius: 8,
  background: 'transparent',
  transition: 'background .12s, border-color .12s',
};

function Segmented({ value, options, onChange }) {
  return (
    <div style={{
      display: 'inline-flex',
      padding: 2,
      background: 'var(--paper-deep)',
      borderRadius: 8,
      gap: 2,
    }}>
      {options.map(o => (
        <button key={o.v} onClick={() => onChange(o.v)} style={{
          padding: '5px 9px',
          fontSize: 11, fontWeight: 500,
          borderRadius: 6,
          background: value === o.v ? '#fff' : 'transparent',
          color: value === o.v ? 'var(--ink)' : 'var(--ink-muted)',
          boxShadow: value === o.v ? 'var(--shadow-sm)' : 'none',
          transition: 'all .12s',
        }}>{o.l}</button>
      ))}
    </div>
  );
}

function SummaryStat({ label, value, sub, tone = 'light' }) {
  const colors = {
    light: { v: '#fff', s: 'rgba(255,255,255,0.82)' },
    blue: { v: 'var(--blue-mid)', s: 'rgba(255,255,255,0.82)' },
    amber: { v: '#FFC670', s: 'rgba(255,255,255,0.82)' },
    green: { v: '#9FE0AC', s: 'rgba(255,255,255,0.85)' },
  }[tone];
  return (
    <div>
      <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'rgba(255,255,255,0.85)', marginBottom: 10, fontWeight: 500 }}>{label}</div>
      <div className="serif" style={{ fontSize: 38, lineHeight: 1, letterSpacing: '-0.03em', color: colors.v, marginBottom: 6 }}>{value}</div>
      <div style={{ fontSize: 12, color: colors.s }}>{sub}</div>
    </div>
  );
}

function matrixCell({ bg, fs = 12, color, pad = '18px 16px', rotate }) {
  return {
    background: bg,
    padding: pad,
    fontSize: fs,
    color: color || 'var(--ink)',
    lineHeight: 1.4,
    display: 'flex',
    alignItems: 'center',
    justifyContent: rotate ? 'center' : 'flex-start',
    textAlign: rotate ? 'center' : 'left',
    writingMode: 'horizontal-tb',
  };
}

Object.assign(window, { Phase2, classifyTask, zoneMeta });
