// LevelScreen and CelebrateScreen — full-screen progression UI

function LevelScreen({ milestone, idx, totalMilestones, completedActions, onToggleAction, onRunAgent, runningActionId, onComplete, onOpenProfile, onBack }) {
  const total = milestone.actions.length;
  const doneCount = milestone.actions.filter((a) => completedActions[a.id]).length;
  const allDone = doneCount === total;
  const pct = (doneCount / total) * 100;

  return (
    <div className="stage stage-wide" data-screen-label={`Level ${idx + 1}`}>
      {/* Top row: breadcrumb */}
      <div className="level-top-row fade-up">
        <div className="level-breadcrumb-row">
          {Array.from({ length: totalMilestones }, (_, i) => (
            <React.Fragment key={i}>
              <div className={`level-breadcrumb-node ${i < idx ? 'done' : ''} ${i === idx ? 'current' : ''} ${i > idx ? 'upcoming' : ''}`}
                aria-label={`Milestone ${i + 1}${i < idx ? ', completed' : i === idx ? ', current' : ', upcoming'}`}>
                {i < idx ? <Icon.Check style={{ width: 11, height: 11 }} /> : (i + 1)}
              </div>
              {i < totalMilestones - 1 && <div className={`level-breadcrumb-line ${i < idx ? 'done' : ''}`}/>}
            </React.Fragment>
          ))}
        </div>
      </div>

      {/* Header */}
      <div className="level-header">
        <div className="fade-up delay-1">
          <div className="h-eyebrow">Milestone {idx + 1} of {totalMilestones} · {milestone.phase}</div>
          <h1 className="h1 serif" style={{ fontSize: 56, marginBottom: 20, maxWidth: '20ch' }}>
            {milestone.title}
          </h1>
          <p className="sub" style={{ maxWidth: 640 }}>
            {milestone.summary}
          </p>
        </div>
        <div className="level-header-right fade-up delay-2">
          <button className="level-top-roadmap" onClick={onOpenProfile} aria-label="View full roadmap">
            <span className="level-top-roadmap-badge">
              <Icon.Map />
            </span>
            <span className="level-top-roadmap-text">
              <span className="level-top-roadmap-title">View full roadmap</span>
              <span className="level-top-roadmap-sub">Milestone {idx + 1} of {totalMilestones}</span>
            </span>
            <span className="level-top-roadmap-arrow" aria-hidden="true">
              <Icon.ArrowRight style={{ width: 12, height: 12 }} />
            </span>
          </button>
          <div className="level-progress-pill">
            <div className="level-progress-pill-label">{doneCount} of {total}</div>
            <div className="level-progress-pill-bar"><div style={{ width: `${pct}%` }}/></div>
            <div className="level-progress-pill-status">{allDone ? '✓ All done — ready to celebrate' : `${total - doneCount} action${total - doneCount === 1 ? '' : 's'} to go`}</div>
          </div>
        </div>
      </div>

      {/* Actions */}
      <div className="level-actions fade-up delay-3">
        {milestone.actions.map((a, i) => (
          <LevelAction
            key={a.id}
            action={a}
            index={i}
            done={!!completedActions[a.id]}
            isRunning={runningActionId === a.id}
            onToggle={() => onToggleAction(a.id)}
            onRunAgent={() => onRunAgent(a.id)}
          />
        ))}
      </div>

      {/* Footer */}
      <div className="level-footer fade-up delay-4">
        <button className="btn-ghost" onClick={onBack}>
          <Icon.ArrowLeft /> Back
        </button>
        <div style={{ flex: 1 }}/>
        {allDone ? (
          <button className="btn-primary level-complete-btn" onClick={onComplete}>
            Mark milestone complete
            <Icon.ArrowRight />
          </button>
        ) : (
          <div style={{ fontSize: 13, color: 'var(--muted)' }}>
            Complete all actions to advance
          </div>
        )}
      </div>
    </div>
  );
}

function LevelAction({ action, index, 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={`level-action ${done ? 'done' : ''}`} style={{ animationDelay: `${0.05 * index}s` }}>
      <div className="level-action-left">
        <button
          className={`level-action-check ${done ? 'done' : ''}`}
          onClick={onToggle}
          aria-label={done ? 'Mark incomplete' : 'Mark complete'}
        >
          {done && <Icon.Check style={{ width: 14, height: 14 }} />}
        </button>
        <div className="level-action-index">{String(index + 1).padStart(2, '0')}</div>
      </div>

      <div className="level-action-body">
        <div className="level-action-head">
          <div className={`level-action-title ${done ? 'done' : ''}`}>{action.title}</div>
          <span className={`action-tag ${tagClass}`}>{action.tag}</span>
        </div>
        <div className="level-action-desc">{action.desc}</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>
  );
}

// ============= CELEBRATE SCREEN =============
function CelebrateScreen({ milestone, idx, totalMilestones, isFinal, onContinue, onPause, onOpenProfile, avatarFace, avatarImage, milestones }) {
  const [confetti, setConfetti] = React.useState(true);
  React.useEffect(() => {
    const t = setTimeout(() => setConfetti(false), 4000);
    return () => clearTimeout(t);
  }, []);

  // For the mini-tracker: animate avatar to advance position after a small delay
  const [avatarAt, setAvatarAt] = React.useState(idx);
  React.useEffect(() => {
    const t = setTimeout(() => setAvatarAt(idx + (isFinal ? 0 : 0)), 100);
    return () => clearTimeout(t);
  }, []);

  const remaining = totalMilestones - idx - 1;

  return (
    <div className="stage stage-wide celebrate-stage" data-screen-label={`Celebrate Level ${idx + 1}`}>
      {confetti && <Confetti />}

      <div className="celebrate-grid">
        {/* Left: message */}
        <div className="celebrate-message">
          <div className="h-eyebrow fade-up">
            {isFinal ? 'Final milestone' : `Milestone ${idx + 1} complete`}
          </div>
          <h1 className="h1 serif fade-up delay-1" style={{ fontSize: 60, marginBottom: 22 }}>
            {isFinal ? (
              <>You <span className="accent">made it</span>.</>
            ) : (
              <>That's <span className="accent">one step</span><br/>closer.</>
            )}
          </h1>

          <p className="sub fade-up delay-2" style={{ maxWidth: 540, marginBottom: 32 }}>
            {isFinal
              ? `Congratulations. You finished every milestone on your path to ${milestone.title}. The agent will keep watching for opportunities and check in weekly.`
              : `You finished "${milestone.title}" — ${milestone.actions.length} actions, all done. The agent has already updated your roadmap based on what you did and didn't lean into.`}
          </p>

          {/* Conversational ask */}
          {!isFinal && (
            <div className="celebrate-ask fade-up delay-3">
              <div className="celebrate-ask-bubble">
                <div className="celebrate-ask-avatar">
                  <Icon.Sparkle />
                </div>
                <div>
                  <div className="celebrate-ask-meta">Path Weave Agent</div>
                  <div className="celebrate-ask-text">
                    Want to keep going? <strong>{milestones[idx + 1].title}</strong> is next — {milestones[idx + 1].actions.length} actions, est. {milestones[idx + 1].phase}.
                  </div>
                </div>
              </div>

              <div className="celebrate-actions">
                <button className="btn-primary" onClick={onContinue}>
                  Yes, let's keep going
                  <Icon.ArrowRight />
                </button>
                <button className="btn-ghost" onClick={onPause}>
                  Take a break · I'll come back
                </button>
              </div>
            </div>
          )}

          {isFinal && (
            <div className="celebrate-actions fade-up delay-3">
              <button className="btn-primary" onClick={onOpenProfile}>
                See your full journey
                <Icon.ArrowRight />
              </button>
            </div>
          )}
        </div>

        {/* Right: mini tracker */}
        <div className="celebrate-tracker fade-up delay-2">
          <div className="celebrate-tracker-label">
            <Icon.Map />
            Your path
          </div>
          <Tracker
            milestones={milestones}
            currentIdx={avatarAt}
            avatarFace={avatarFace}
            avatarImage={avatarImage}
            onSelectMilestone={() => {}}
            pathTitle={isFinal ? '✦ Reached ✦' : 'Goal'}
            compact
          />
          <div className="celebrate-tracker-foot">
            <button className="text-link" onClick={onOpenProfile}>
              Open full progress page →
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function VerifyModal({ action, onConfirm, onClose }) {
  const [phase, setPhase] = React.useState('loading'); // loading | question | checking | failed | passed
  const [question, setQuestion] = React.useState('');
  const [answer, setAnswer] = React.useState('');
  const [feedback, setFeedback] = React.useState('');

  React.useEffect(() => {
    if (!action) return;
    setPhase('loading');
    setAnswer('');
    setFeedback('');
    const fetch = async () => {
      const res = window.api ? await window.api.getVerifyQuestion(action.id, action.title, action.desc || '') : null;
      setQuestion(res?.question || 'Briefly describe what you did to complete this task.');
      setPhase('question');
    };
    fetch();
  }, [action && action.id]);

  const handleSubmit = async () => {
    if (!answer.trim()) return;
    setPhase('checking');
    const res = window.api
      ? await window.api.checkVerifyAnswer(action.id, action.title, action.desc || '', question, answer)
      : { passed: true, feedback: 'Great work!' };
    if (res && res.passed) {
      setFeedback(res.feedback || 'Great work!');
      setPhase('passed');
      setTimeout(() => onConfirm(action.id), 900);
    } else {
      setFeedback((res && res.feedback) || "That doesn't quite show completion — try again.");
      setPhase('failed');
    }
  };

  if (!action) return null;

  return (
    <div className="overlay" onClick={onClose}>
      <div className="overlay-card verify-modal" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 540 }}>
        <div style={{ padding: '28px 28px 0', borderBottom: '1px solid var(--border)', paddingBottom: 20 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16 }}>
            <div style={{ fontSize: 11, fontFamily: 'var(--mono)', color: 'var(--accent)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
              Mark as complete
            </div>
            <button onClick={onClose} style={{ background: 'none', border: 'none', color: 'var(--muted)', cursor: 'pointer', fontSize: 18, lineHeight: 1 }}>✕</button>
          </div>
          <div style={{ fontWeight: 600, fontSize: 16, marginTop: 8, color: 'var(--fg)' }}>{action.title}</div>
        </div>

        <div style={{ padding: 28 }}>
          {phase === 'loading' && (
            <p style={{ color: 'var(--muted)', fontSize: 14 }}>Generating verification question…</p>
          )}

          {phase === 'checking' && (
            <p style={{ color: 'var(--muted)', fontSize: 14 }}>Checking your answer…</p>
          )}

          {phase === 'passed' && (
            <div style={{ textAlign: 'center', padding: '12px 0' }}>
              <div style={{ fontSize: 32, marginBottom: 10 }}>✓</div>
              <div style={{ color: 'var(--green)', fontWeight: 600, fontSize: 15 }}>Correct! Marking as complete…</div>
              {feedback && <div style={{ color: 'var(--muted)', fontSize: 13, marginTop: 6 }}>{feedback}</div>}
            </div>
          )}

          {(phase === 'question' || phase === 'failed') && (
            <>
              <div style={{ fontSize: 14, color: 'var(--fg)', lineHeight: 1.6, marginBottom: 16, fontWeight: 500 }}>
                {question}
              </div>
              {phase === 'failed' && feedback && (
                <div style={{ background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.2)', borderRadius: 8, padding: '10px 14px', fontSize: 13, color: '#f87171', marginBottom: 14 }}>
                  {feedback}
                </div>
              )}
              <textarea
                style={{
                  width: '100%', boxSizing: 'border-box',
                  background: 'rgba(255,255,255,0.04)', border: '1px solid var(--border-strong)',
                  borderRadius: 10, padding: '12px 14px', fontSize: 14, color: 'var(--fg)',
                  resize: 'vertical', minHeight: 90, fontFamily: 'inherit', lineHeight: 1.5,
                  outline: 'none', marginBottom: 16,
                }}
                placeholder="Your answer…"
                value={answer}
                onChange={(e) => setAnswer(e.target.value)}
                onKeyDown={(e) => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) handleSubmit(); }}
                autoFocus
              />
              <button
                className="btn-primary"
                style={{ width: '100%' }}
                onClick={handleSubmit}
                disabled={!answer.trim()}
              >
                Submit answer
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

window.LevelScreen = LevelScreen;
window.CelebrateScreen = CelebrateScreen;
window.VerifyModal = VerifyModal;
