// Tracker (game-style roadmap) screen + Step detail overlay + Agent execution

function TrackerScreen({ pathTitle, milestones, currentIdx, completedActions, onSelectMilestone, onRestart, avatarFace }) {
  const totalActions = milestones.reduce((s, m) => s + m.actions.length, 0);
  const doneCount = Object.values(completedActions).filter(Boolean).length;
  const pct = Math.round((doneCount / totalActions) * 100);

  return (
    <div className="stage stage-wide">
      {/* Header row */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 24, marginBottom: 32 }}>
        <div className="fade-up">
          <div className="h-eyebrow">Your roadmap</div>
          <h1 className="h1 serif" style={{ fontSize: 44, marginBottom: 6 }}>
            From <span style={{ color: 'var(--muted)' }}>Software Engineer</span>
            <br/>to <span className="accent">{pathTitle}</span>
          </h1>
          <p style={{ fontSize: 14, color: 'var(--muted)' }}>
            {milestones.length} milestones · {totalActions} actions · est. 12–16 weeks · agent re-plans as you progress
          </p>
        </div>

        <div className="fade-up delay-1" style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
          <ProgressPill icon={<Icon.Bolt />} label="Plan progress" value={`${pct}%`} subvalue={`${doneCount}/${totalActions} actions`} />
          <ProgressPill icon={<Icon.Flag />} label="Current milestone" value={`${currentIdx + 1} of ${milestones.length}`} subvalue={milestones[currentIdx]?.phase} />
        </div>
      </div>

      {/* Cartoon tracker + side panels */}
      <div className="fade-up delay-2" style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 28, alignItems: 'start' }}>
        {/* The cartoon scene */}
        <Tracker
          milestones={milestones}
          currentIdx={currentIdx}
          avatarFace={avatarFace}
          onSelectMilestone={onSelectMilestone}
          pathTitle={pathTitle}
        />

        {/* Right column: next up + agent activity stacked */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <NextUpCard milestone={milestones[currentIdx]} currentIdx={currentIdx} onOpen={() => onSelectMilestone(currentIdx)} completedActions={completedActions} />
          <AgentActivityCard />
        </div>
      </div>
    </div>
  );
}

function ProgressPill({ icon, label, value, subvalue }) {
  return (
    <div style={{
      padding: '14px 20px',
      background: 'rgba(10, 17, 36, 0.6)',
      border: '1px solid var(--border)',
      borderRadius: 14,
      minWidth: 160,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--dim)', letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 4 }}>
        <span style={{ color: 'var(--cyan)' }}>{icon}</span> {label}
      </div>
      <div className="serif" style={{ fontSize: 22, fontWeight: 600, color: 'var(--cyan)', lineHeight: 1 }}>{value}</div>
      <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 4 }}>{subvalue}</div>
    </div>
  );
}

function NextUpCard({ milestone, currentIdx, completedActions, onOpen }) {
  const total = milestone.actions.length;
  const done = milestone.actions.filter((a) => completedActions[a.id]).length;
  return (
    <button
      onClick={onOpen}
      className="card"
      style={{ padding: 22, textAlign: 'left', cursor: 'pointer', transition: 'all 0.2s' }}
      onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--cyan)'}
      onMouseLeave={(e) => e.currentTarget.style.borderColor = ''}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
        <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--cyan)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>
          Next up · Milestone {currentIdx + 1}
        </div>
        <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--dim)' }}>· {milestone.phase}</div>
      </div>
      <div className="serif" style={{ fontSize: 22, fontWeight: 500, marginBottom: 8 }}>{milestone.title}</div>
      <div style={{ fontSize: 13, color: 'var(--muted)', lineHeight: 1.5, marginBottom: 14 }}>{milestone.summary}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{ flex: 1, height: 4, background: 'rgba(94, 234, 212, 0.12)', borderRadius: 4, overflow: 'hidden' }}>
          <div style={{ height: '100%', width: `${(done / total) * 100}%`, background: 'linear-gradient(90deg, var(--c-200), var(--c-400))', transition: 'width 0.4s' }}/>
        </div>
        <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)' }}>{done}/{total}</div>
      </div>
      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13, color: 'var(--v-200)', marginTop: 14, fontWeight: 500, whiteSpace: 'nowrap' }}>
        Open this milestone <Icon.ArrowRight />
      </div>
    </button>
  );
}

function AgentActivityCard() {
  return (
    <div className="card" style={{ padding: 22 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
        <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--cyan)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>
          Agent activity · live
        </div>
        <div style={{ width: 6, height: 6, borderRadius: 3, background: 'var(--green)', boxShadow: '0 0 8px var(--green)' }}/>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {[
          { icon: '✓', text: 'Added 3 new FDE openings to your watchlist', time: '2m ago', color: 'var(--green)' },
          { icon: '◷', text: 'Drafting outreach to 5 Anthropic FDEs', time: '14m ago', color: 'var(--cyan)' },
          { icon: '◷', text: 'Re-planning Milestone 2 — Anthropic just posted new role', time: '1h ago', color: 'var(--amber)' },
        ].map((it, i) => (
          <div key={i} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', fontSize: 13 }}>
            <div style={{ color: it.color, fontFamily: 'var(--mono)', fontSize: 14, lineHeight: 1, paddingTop: 2 }}>{it.icon}</div>
            <div style={{ flex: 1, color: 'var(--text)', lineHeight: 1.45 }}>{it.text}</div>
            <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--dim)', flexShrink: 0 }}>{it.time}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============== STEP DETAIL OVERLAY ==============
function MilestoneDetail({ milestone, idx, isCurrent, isDone, completedActions, onToggleAction, onClose, onAdvance, onRunAgent, runningActionId, accent }) {
  const total = milestone.actions.length;
  const doneCount = milestone.actions.filter((a) => completedActions[a.id]).length;
  const allDone = doneCount === total;

  return (
    <div className="overlay" onClick={onClose}>
      <div className="overlay-card" onClick={(e) => e.stopPropagation()}>
        {/* Header */}
        <div style={{ padding: '24px 28px', borderBottom: '1px solid var(--border)', position: 'relative' }}>
          <button onClick={onClose} style={{ position: 'absolute', top: 18, right: 18, width: 32, height: 32, borderRadius: 8, display: 'grid', placeItems: 'center', color: 'var(--muted)' }}>
            <Icon.Close />
          </button>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
            <div style={{
              width: 36, height: 36, borderRadius: '50%',
              background: `linear-gradient(135deg, var(--c-300), var(--c-500))`,
              display: 'grid', placeItems: 'center',
              fontFamily: 'var(--serif)', fontWeight: 600, color: '#042f2e',
            }}>
              {idx + 1}
            </div>
            <div>
              <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--cyan)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>
                Milestone {idx + 1} · {milestone.phase}
              </div>
            </div>
          </div>
          <h2 className="serif" style={{ fontSize: 28, fontWeight: 500, marginBottom: 8 }}>{milestone.title}</h2>
          <p style={{ fontSize: 14, color: 'var(--muted)', lineHeight: 1.55 }}>{milestone.summary}</p>

          {/* Progress bar */}
          <div style={{ marginTop: 16, display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ flex: 1, height: 4, background: 'rgba(94, 234, 212, 0.12)', borderRadius: 4, overflow: 'hidden' }}>
              <div style={{ height: '100%', width: `${(doneCount / total) * 100}%`, background: `linear-gradient(90deg, var(--c-200), var(--c-400))`, transition: 'width 0.4s' }}/>
            </div>
            <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)' }}>{doneCount}/{total} complete</div>
          </div>
        </div>

        {/* Action list */}
        <div>
          {milestone.actions.map((a) => (
            <ActionRow
              key={a.id}
              action={a}
              done={!!completedActions[a.id]}
              isRunning={runningActionId === a.id}
              onToggle={() => onToggleAction(a.id)}
              onRunAgent={() => onRunAgent(a.id)}
            />
          ))}
        </div>

        {/* Footer */}
        <div style={{ padding: '20px 28px', borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
          <div style={{ fontSize: 12, color: 'var(--dim)' }}>
            {allDone ? '🎉 Milestone complete! Ready to advance?' : `Complete ${total - doneCount} more to advance`}
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            <button className="btn-ghost" onClick={onClose}>Close</button>
            {allDone && isCurrent && (
              <button className="btn-primary" onClick={onAdvance}>
                Advance to next milestone <Icon.ArrowRight />
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function ActionRow({ action, done, isRunning, onToggle, onRunAgent }) {
  const tagClass = {
    LEARN: 'tag-learn',
    BUILD: 'tag-build',
    NETWORK: 'tag-network',
    APPLY: 'tag-apply',
  }[action.tag] || 'tag-learn';

  return (
    <div className="action">
      <button
        className={`action-check ${done ? 'done' : ''}`}
        onClick={onToggle}
      >
        {done && <Icon.Check />}
      </button>
      <div className="action-body">
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginBottom: 4 }}>
          <div style={{ flex: 1 }}>
            <div className={`action-title ${done ? 'done' : ''}`}>{action.title}</div>
            <div className="action-desc">{action.desc}</div>
          </div>
          <span className={`action-tag ${tagClass}`}>{action.tag}</span>
        </div>

        {action.agentLabel && !done && (
          <button className="agent-btn" onClick={onRunAgent} disabled={isRunning}>
            <Icon.Sparkle className="spark"/>
            {isRunning ? 'Agent running…' : action.agentLabel}
          </button>
        )}

        {isRunning && action.agentRun && (
          <AgentRunLog lines={action.agentRun} onDone={() => { onRunAgent(null); onToggle(); }} />
        )}
      </div>
    </div>
  );
}

function AgentRunLog({ lines, onDone }) {
  const [visibleCount, setVisibleCount] = React.useState(0);

  React.useEffect(() => {
    if (visibleCount < lines.length) {
      const t = setTimeout(() => setVisibleCount(visibleCount + 1), 380);
      return () => clearTimeout(t);
    } else {
      const t = setTimeout(onDone, 700);
      return () => clearTimeout(t);
    }
  }, [visibleCount, lines.length]);

  const isDone = visibleCount >= lines.length;

  return (
    <div className="agent-run">
      <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--cyan)', letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 8 }}>
        ⚡ Agent execution log
      </div>
      {lines.slice(0, visibleCount).map((l, i) => (
        <div key={i} className="agent-run-line fade-up">
          <span className="agent-run-ts">{l.ts}</span>
          <span className="agent-run-tag">{l.tag}</span>
          <span>→ {l.line}</span>
        </div>
      ))}
      {!isDone && (
        <div className="agent-run-line">
          <span className="agent-run-ts">···</span>
          <span><span className="typing"><span/><span/><span/></span></span>
        </div>
      )}
      {isDone && (
        <div className="agent-run-line success fade-up">
          <span className="agent-run-ts">DONE</span>
          <span className="agent-run-tag">complete</span>
          <span>→ task marked done · synced to your profile</span>
        </div>
      )}
    </div>
  );
}

// ============== EMERGENCY (UNEMPLOYED HELP) ==============
function EmergencyPanel({ open, onClose }) {
  if (!open) return null;
  return (
    <div className="overlay" onClick={onClose}>
      <div className="overlay-card" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 560 }}>
        <div style={{ padding: '28px 28px 8px', borderBottom: '1px solid var(--border)', position: 'relative' }}>
          <button onClick={onClose} style={{ position: 'absolute', top: 18, right: 18, color: 'var(--muted)' }}><Icon.Close /></button>
          <div style={{
            width: 48, height: 48, borderRadius: 12,
            background: 'rgba(94, 234, 212, 0.10)', border: '1px solid rgba(94, 234, 212, 0.32)',
            display: 'grid', placeItems: 'center', color: 'var(--c-200)', marginBottom: 14,
          }}>
            <Icon.SOS />
          </div>
          <h2 className="serif" style={{ fontSize: 26, fontWeight: 500, marginBottom: 6 }}>Emergency mode</h2>
          <p style={{ fontSize: 14, color: 'var(--muted)', lineHeight: 1.55, marginBottom: 20 }}>
            If you're between jobs and need income or interviews <em>now</em>, the agent reorders your roadmap. Long-term skill building moves down. High-leverage outreach moves up.
          </p>
        </div>
        <div style={{ padding: '20px 28px' }}>
          {[
            { title: 'Activate 7-day sprint mode', desc: 'Replan tasks for max interview-velocity. Top 3 priorities only.', icon: <Icon.Bolt /> },
            { title: 'Surface 10 same-week opportunities', desc: 'Pulled from your network + recent FDE postings.', icon: <Icon.Briefcase /> },
            { title: 'Draft 5 warm-intro DMs right now', desc: 'You review and click send. Agent handles the rest.', icon: <Icon.Users /> },
            { title: 'Find income bridge gigs (1–4 weeks)', desc: 'Contract work that lines up with FDE skills.', icon: <Icon.Briefcase /> },
          ].map((item, i) => (
            <button key={i} style={{
              width: '100%',
              display: 'flex', alignItems: 'center', gap: 14,
              padding: 16, marginBottom: 10,
              background: 'rgba(10, 17, 36, 0.4)',
              border: '1px solid var(--border)',
              borderRadius: 12,
              textAlign: 'left',
              transition: 'all 0.15s',
            }}
            onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--c-300)'}
            onMouseLeave={(e) => e.currentTarget.style.borderColor = ''}
            >
              <div style={{
                width: 36, height: 36, borderRadius: 8,
                background: 'rgba(94, 234, 212, 0.10)', color: 'var(--c-200)',
                display: 'grid', placeItems: 'center',
              }}>{item.icon}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 500, fontSize: 14, marginBottom: 3 }}>{item.title}</div>
                <div style={{ fontSize: 12, color: 'var(--muted)', lineHeight: 1.5 }}>{item.desc}</div>
              </div>
              <Icon.ArrowRight />
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

window.TrackerScreen = TrackerScreen;
window.MilestoneDetail = MilestoneDetail;
window.EmergencyPanel = EmergencyPanel;
