// Screens for PathFinder

// ============ STEP 1: GOAL ENTRY ============
function GoalEntryScreen({ goal, setGoal, onNext, onDiscover }) {
  const [discoverResume, setDiscoverResume] = React.useState(false);
  const suggestions = [
    'Forward Deployed Engineer',
    'AI Engineer',
    'Solutions Engineer',
    'Product Manager',
    'Design Manager',
    'Technical Product Manager',
    'Engineering Manager',
    'Founder',
  ];
  return (
    <div className="stage">
      <FlowProgress step={0} />
      <div className="fade-up">
        <div className="h-eyebrow">Step 1 · Your destination</div>
        <h1 className="h1 serif">
          What do you want to <span className="accent">become</span>?
        </h1>
        <p className="sub">
          Tell us the career you're pivoting toward. One sentence is plenty — the agent will dig deeper in a moment.
        </p>
      </div>

      <div className="big-input-wrap fade-up delay-1">
        <textarea
          className="big-input serif"
          placeholder="e.g. I'm a software engineer and I want to become a Forward Deployed Engineer at an AI company…"
          value={goal}
          onChange={(e) => setGoal(e.target.value)}
          rows={3}
        />
      </div>

      <div className="fade-up delay-2" style={{ marginBottom: 36 }}>
        <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--dim)', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 12 }}>
          Or pick one to start
        </div>
        <div className="chip-row">
          {suggestions.map((s) => (
            <button
              key={s}
              className={`chip ${goal.toLowerCase().includes(s.toLowerCase()) ? 'active' : ''}`}
              onClick={() => setGoal(`I want to become a ${s}.`)}
            >
              {s}
            </button>
          ))}
        </div>
      </div>

      <div className="fade-up delay-3" style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
        <button className="btn-primary" disabled={!goal.trim()} onClick={onNext}>
          Continue
          <Icon.ArrowRight />
        </button>
        <div style={{ fontSize: 12, color: 'var(--dim)' }}>
          ⌘ + Enter
        </div>
      </div>

      {/* Secondary path: don't know yet */}
      <div className="fade-up delay-4" style={{
        marginTop: 56,
        paddingTop: 28,
        borderTop: '1px dashed var(--border)',
      }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 14, flexWrap: 'wrap' }}>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--dim)', letterSpacing: '0.12em', textTransform: 'uppercase', whiteSpace: 'nowrap' }}>
            Don't know yet?
          </div>
          <div style={{ fontSize: 14, color: 'var(--muted)' }}>
            Drop your resume — the agent will surface 3 directions worth exploring.
          </div>
        </div>

        <div
          onClick={() => {
            setDiscoverResume(true);
            setTimeout(() => onDiscover(), 650);
          }}
          style={{
            border: '1.5px dashed var(--border-strong)',
            borderRadius: 14,
            padding: '26px 24px',
            cursor: 'pointer',
            transition: 'all 0.2s',
            background: discoverResume ? 'rgba(94, 234, 212, 0.08)' : 'rgba(10, 32, 36, 0.4)',
            borderColor: discoverResume ? 'var(--c-300)' : undefined,
            display: 'flex',
            alignItems: 'center',
            gap: 18,
          }}
        >
          <div style={{
            width: 44, height: 44, borderRadius: '50%',
            background: 'rgba(94, 234, 212, 0.1)',
            display: 'grid', placeItems: 'center',
            border: '1px solid var(--border-strong)',
            color: discoverResume ? 'var(--c-200)' : 'var(--cyan)',
            flexShrink: 0,
          }}>
            {discoverResume ? <Icon.Check style={{ width: 18, height: 18 }} /> : <Icon.Upload style={{ width: 18, height: 18 }} />}
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="serif" style={{ fontSize: 17, fontWeight: 500, marginBottom: 2 }}>
              {discoverResume ? 'Resume parsed · routing to discovery questions…' : 'Drop resume or click to browse'}
            </div>
            <div style={{ fontSize: 12, color: 'var(--muted)' }}>
              PDF, DOCX, TXT · agent reads it and asks 5 questions to find the right fit
            </div>
          </div>
          <Icon.ArrowRight style={{ color: 'var(--cyan)', flexShrink: 0 }} />
        </div>
      </div>
    </div>
  );
}

// ============ STEP 2: RESUME ============
function ResumeScreen({ goal, resume, setResume, onNext, onBack, sessionId }) {
  const [tab, setTab] = React.useState('upload');
  const [hasFile, setHasFile] = React.useState(false);
  const [selectedFile, setSelectedFile] = React.useState(null);
  const [uploading, setUploading] = React.useState(false);
  const fileInputRef = React.useRef(null);

  return (
    <div className="stage">
      <FlowProgress step={1} />
      <div className="fade-up">
        <div className="h-eyebrow">Step 2 · Your starting point</div>
        <h1 className="h1 serif">
          So we know <span className="accent">where you stand</span>.
        </h1>
        <p className="sub">
          The agent reads your background to extract skills, transferable strengths, and gaps — used to build a path that's actually plausible for you.
        </p>
      </div>

      <div className="card glow fade-up delay-1" style={{ padding: 28, marginBottom: 24 }}>
        <div style={{ display: 'flex', gap: 8, marginBottom: 22, borderBottom: '1px solid var(--border)', paddingBottom: 16 }}>
          {[
            { id: 'upload', label: 'Upload resume', icon: <Icon.Upload /> },
            { id: 'paste', label: 'Paste text', icon: <Icon.Note /> },
            { id: 'linkedin', label: 'LinkedIn URL', icon: <Icon.Users /> },
          ].map((t) => (
            <button
              key={t.id}
              className={`chip ${tab === t.id ? 'active' : ''}`}
              onClick={() => setTab(t.id)}
            >
              {t.icon} {t.label}
            </button>
          ))}
        </div>

        {tab === 'upload' && (
          <div>
            <input
              type="file"
              ref={fileInputRef}
              accept=".pdf,.txt,.md,.doc,.docx"
              style={{ display: 'none' }}
              onChange={(e) => {
                const file = e.target.files[0];
                if (file) { setSelectedFile(file); setHasFile(true); }
              }}
            />
            <div
              onClick={() => fileInputRef.current && fileInputRef.current.click()}
              style={{
                border: '1.5px dashed var(--border-strong)',
                borderRadius: 14,
                padding: '44px 28px',
                textAlign: 'center',
                cursor: 'pointer',
                transition: 'all 0.2s',
                background: hasFile ? 'rgba(94, 234, 212, 0.08)' : 'rgba(10, 32, 36, 0.4)',
                borderColor: hasFile ? 'var(--c-300)' : undefined,
              }}
            >
              <div style={{
                width: 56, height: 56, borderRadius: '50%',
                background: 'rgba(94, 234, 212, 0.1)',
                display: 'inline-grid', placeItems: 'center',
                border: '1px solid var(--border-strong)',
                marginBottom: 14,
                color: hasFile ? 'var(--c-200)' : 'var(--cyan)',
              }}>
                {hasFile ? <Icon.Check style={{ width: 22, height: 22 }} /> : <Icon.Upload style={{ width: 22, height: 22 }} />}
              </div>
              <div className="serif" style={{ fontSize: 19, marginBottom: 6 }}>
                {hasFile ? 'Resume ready' : 'Drop resume or click to browse'}
              </div>
              <div style={{ fontSize: 13, color: 'var(--muted)' }}>
                {hasFile && selectedFile
                  ? `${selectedFile.name} · ${(selectedFile.size / 1024).toFixed(0)} KB`
                  : 'PDF, DOCX, TXT · agent reads it in seconds'}
              </div>
            </div>
          </div>
        )}

        {tab === 'paste' && (
          <textarea
            placeholder="Paste your resume text here…"
            value={typeof resume === 'string' && tab === 'paste' ? resume : ''}
            onChange={(e) => setResume(e.target.value)}
            style={{
              width: '100%', minHeight: 220,
              padding: 18,
              background: 'rgba(10, 17, 36, 0.4)',
              border: '1px solid var(--border)',
              borderRadius: 12,
              fontSize: 14,
              fontFamily: 'var(--mono)',
              lineHeight: 1.6,
              resize: 'vertical',
            }}
          />
        )}

        {tab === 'linkedin' && (
          <div>
            <div style={{ fontSize: 13, color: 'var(--muted)', marginBottom: 10 }}>Public LinkedIn profile URL</div>
            <input
              placeholder="linkedin.com/in/yourname"
              onChange={(e) => setResume(`linkedin: ${e.target.value}`)}
              style={{
                width: '100%',
                padding: '14px 18px',
                background: 'rgba(10, 17, 36, 0.4)',
                border: '1px solid var(--border)',
                borderRadius: 12,
                fontSize: 15,
              }}
            />
          </div>
        )}
      </div>

      {/* Quick context fields */}
      <div className="fade-up delay-2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 32 }}>
        <CompactField label="Current / last role" defaultValue="Senior Software Engineer · Linear" />
        <CompactField label="Years of experience" defaultValue="5 years" />
        <CompactField label="Location" defaultValue="San Francisco, CA" />
        <CompactField label="Employment status" type="select" options={['Employed full-time', 'Employed part-time', 'Unemployed — actively looking', 'Student', 'Freelance / contract']} />
      </div>

      <div className="fade-up delay-3" style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
        <button className="btn-ghost" onClick={onBack}><Icon.ArrowLeft />Back</button>
        <button
          className="btn-primary"
          disabled={(tab === 'upload' && !hasFile && !resume) || uploading}
          onClick={async () => {
            if (window.api && window.api.isAuthenticated() && sessionId) {
              setUploading(true);
              try {
                if (tab === 'upload' && selectedFile) {
                  await window.api.uploadResume(sessionId, selectedFile);
                } else if ((tab === 'paste' || tab === 'linkedin') && resume) {
                  await window.api.uploadResumeText(sessionId, resume);
                }
              } finally {
                setUploading(false);
              }
            }
            onNext();
          }}
        >
          {uploading ? 'Uploading…' : 'Let the agent analyze'}
          {!uploading && <Icon.Sparkle />}
        </button>
      </div>
    </div>
  );
}

function CompactField({ label, placeholder, type, options, defaultValue }) {
  return (
    <div style={{
      padding: '12px 16px',
      background: 'rgba(10, 17, 36, 0.4)',
      border: '1px solid var(--border)',
      borderRadius: 12,
    }}>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--dim)', letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 4 }}>{label}</div>
      {type === 'select' ? (
        <select style={{ width: '100%', background: 'none', border: 'none', color: 'var(--text)', fontSize: 14, outline: 'none', appearance: 'none', cursor: 'pointer' }}>
          {options.map((o) => <option key={o} style={{ background: '#0a1124' }}>{o}</option>)}
        </select>
      ) : (
        <input placeholder={placeholder} defaultValue={defaultValue} style={{ width: '100%', fontSize: 14 }} />
      )}
    </div>
  );
}

// ============ STEP 3: AGENT QUESTIONS ============
function QuestionsScreen({ goal, onNext, onBack, sessionId }) {
  const FALLBACK_QUESTIONS = [
    {
      id: 'q1',
      q: "Your resume shows strong engineering experience. FDE is a hybrid role: 50% engineering, 50% in front of customers. What's pulling you toward it?",
      options: [
        "I want customer contact — building in a vacuum drains me",
        "I love the ambiguity — wearing many hats",
        "I want to ship in days, not quarters",
        "Honestly, the comp at AI labs is the headline",
      ],
    },
    {
      id: 'q2',
      q: "How comfortable are you walking into a customer's office and rewriting their workflow in front of them?",
      options: [
        "Very — I've led on-site integrations before",
        "Comfortable enough — I've done client demos",
        "Nervous but willing to push through",
        "This is the part I need to grow into",
      ],
    },
    {
      id: 'q3',
      q: "Where do you want to land?",
      options: [
        "Frontier AI lab (Anthropic, OpenAI, etc.)",
        "AI-first applied company (Palantir, Sierra, Decagon)",
        "Hot AI startup, Series A–B",
        "Wherever pays best & lets me work directly with customers",
      ],
    },
  ];

  const [questions, setQuestions] = React.useState(FALLBACK_QUESTIONS);
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState([]);
  const [thinking, setThinking] = React.useState(true);

  // Fetch Gemini-generated questions on mount if session available
  React.useEffect(() => {
    if (!window.api || !window.api.isAuthenticated() || !sessionId) {
      const t = setTimeout(() => setThinking(false), 900);
      return () => clearTimeout(t);
    }
    setThinking(true);
    window.api.getQuestions(sessionId)
      .then(data => { if (data?.questions?.length) setQuestions(data.questions); })
      .catch(() => {})
      .finally(() => setThinking(false));
  }, [sessionId]);

  React.useEffect(() => {
    if (step === 0) return; // initial load handled above
    setThinking(true);
    const t = setTimeout(() => setThinking(false), 500);
    return () => clearTimeout(t);
  }, [step]);

  const pickAnswer = async (opt) => {
    const current = questions[step];
    const next = [...answers, { question_id: current.id || `q${step + 1}`, answer: opt }];
    setAnswers(next);
    if (step < questions.length - 1) {
      setStep(step + 1);
    } else {
      if (window.api && window.api.isAuthenticated() && sessionId) {
        await window.api.saveAnswers(sessionId, next);
      }
      setTimeout(onNext, 500);
    }
  };

  const current = questions[step];

  return (
    <div className="stage">
      <FlowProgress step={2} />
      <div className="fade-up">
        <div className="h-eyebrow">Step 3 · Sharpening your target</div>
        <h1 className="h1 serif" style={{ fontSize: 44 }}>
          The agent has <span className="accent">a few questions</span>.
        </h1>
        <p className="sub">
          {questions.length - step} of {questions.length} remaining. Quick — your answers shape the next 20 weeks of your plan.
        </p>
      </div>

      {/* Conversation stream */}
      <div className="card fade-up delay-1" style={{ padding: 28, marginBottom: 28 }}>
        <div className="msg-stream">
          {/* Initial summary message */}
          <div className="msg fade-up">
            <div className="msg-avatar agent"><Icon.Sparkle /></div>
            <div className="msg-body">
              <div className="msg-meta">PATHFINDER · ANALYZED YOUR RESUME</div>
              <div className="msg-text">
                I parsed <strong style={{ color: 'var(--cyan)' }}>17 transferable skills</strong> across your resume. Strongest signals: <em style={{ color: 'var(--text)' }}>full-stack shipping speed, customer demos at your last gig, and Python + TypeScript fluency</em>. Let me ask a few things before I rank pivot paths.
              </div>
            </div>
          </div>

          {/* Already-answered Qs */}
          {answers.map((a, i) => (
            <React.Fragment key={i}>
              <div className="msg">
                <div className="msg-avatar agent">A</div>
                <div className="msg-body">
                  <div className="msg-meta">QUESTION {i + 1} / {questions.length}</div>
                  <div className="msg-text">{questions[i] && questions[i].q}</div>
                </div>
              </div>
              <div className="msg" style={{ flexDirection: 'row-reverse' }}>
                <div className="msg-avatar user">R</div>
                <div className="msg-body" style={{ textAlign: 'right' }}>
                  <div className="msg-meta">YOU</div>
                  <div style={{
                    display: 'inline-block',
                    background: 'rgba(94, 234, 212, 0.1)',
                    border: '1px solid var(--border-strong)',
                    borderRadius: 14,
                    borderBottomRightRadius: 4,
                    padding: '10px 14px',
                    fontSize: 14,
                    maxWidth: '80%',
                    textAlign: 'left',
                  }}>
                    {a.answer}
                  </div>
                </div>
              </div>
            </React.Fragment>
          ))}

          {/* Current Q */}
          {!thinking && current && (
            <div className="msg fade-up" key={`q-${step}`}>
              <div className="msg-avatar agent">A</div>
              <div className="msg-body">
                <div className="msg-meta">QUESTION {step + 1} / {questions.length}</div>
                <div className="msg-text" style={{ marginBottom: 16 }}>{current.q}</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {current.options.map((opt, i) => (
                    <button
                      key={opt}
                      onClick={() => pickAnswer(opt)}
                      style={{
                        textAlign: 'left',
                        padding: '12px 16px',
                        background: 'rgba(10, 17, 36, 0.5)',
                        border: '1px solid var(--border)',
                        borderRadius: 10,
                        fontSize: 14,
                        color: 'var(--text)',
                        transition: 'all 0.15s',
                        animation: `fadeUp 0.4s ease-out ${i * 0.05}s both`,
                      }}
                      onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--cyan)'; e.currentTarget.style.background = 'rgba(94, 234, 212, 0.06)'; }}
                      onMouseLeave={(e) => { e.currentTarget.style.borderColor = ''; e.currentTarget.style.background = 'rgba(10, 17, 36, 0.5)'; }}
                    >
                      <span style={{ color: 'var(--cyan)', fontFamily: 'var(--mono)', fontSize: 11, marginRight: 10 }}>{String.fromCharCode(65 + i)}</span>
                      {opt}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          )}

          {thinking && (
            <div className="msg fade-up">
              <div className="msg-avatar agent">A</div>
              <div className="msg-body">
                <div className="msg-meta">THINKING…</div>
                <div className="typing"><span/><span/><span/></div>
              </div>
            </div>
          )}
        </div>
      </div>

      <div className="fade-up delay-2" style={{ display: 'flex', gap: 12 }}>
        <button className="btn-ghost" onClick={onBack}><Icon.ArrowLeft />Back</button>
      </div>
    </div>
  );
}

// ============ STEP 4: PATH REFINEMENT ============
function RefineScreen({ goal, onPick, onBack, onRedo, sessionId }) {
  const FALLBACK_PATHS = [
    {
      title: 'Forward Deployed Engineer',
      match_score: 94,
      recommended: true,
      summary: "Exactly what you asked for. You'll be 50% writing code, 50% in customer Slacks. Your demo skills + full-stack range fit the bill.",
      reasoning: [
        "Your last role included customer-facing integrations — rare for FDE applicants",
        "Full-stack range (frontend + Python + cloud) matches the breadth FDE work demands",
        "You've shipped greenfield projects under ambiguity — the #1 FDE filter",
      ],
      timeline: '3–5 months',
      salary_delta: '+38% median',
      sample_cos: ['Anthropic', 'OpenAI', 'Sierra', 'Decagon', 'Palantir'],
    },
    {
      title: 'Solutions Engineer',
      match_score: 81,
      summary: "FDE-adjacent — more pre-sales, less custom code. Faster path in, but lower ceiling on technical depth.",
      reasoning: [
        "Lower bar on shipping — more on communication and demos",
        "Larger market — every B2B SaaS hires SEs",
        "Easier to land in the next 60 days; can serve as a stepping stone to FDE",
      ],
      timeline: '2–3 months',
      salary_delta: '+22% median',
      sample_cos: ['Stripe', 'Snowflake', 'Datadog', 'MongoDB'],
    },
    {
      title: 'Applied AI Engineer (Customer-facing)',
      match_score: 88,
      summary: "FDE in everything but title — eval design, prompt engineering, customer integrations.",
      reasoning: [
        "Eval & prompt engineering chops can be self-taught in weeks given your background",
        "Compensation at frontier labs is currently 25–45% above standard FDE",
        "Smaller hiring funnel — faster interview loops, less competition",
      ],
      timeline: '3–6 months',
      salary_delta: '+45% median',
      sample_cos: ['OpenAI', 'Anthropic', 'Inflection', 'Cohere'],
    },
  ];

  const [selectedIdx, setSelectedIdx] = React.useState(0);
  const [thinking, setThinking] = React.useState(true);
  const [paths, setPaths] = React.useState([]);

  React.useEffect(() => {
    if (!window.api || !window.api.isAuthenticated() || !sessionId) {
      const t = setTimeout(() => { setPaths(FALLBACK_PATHS); setThinking(false); }, 1400);
      return () => clearTimeout(t);
    }
    setThinking(true);
    window.api.rankPaths(sessionId)
      .then(data => setPaths(data?.paths?.length ? data.paths : FALLBACK_PATHS))
      .catch(() => setPaths(FALLBACK_PATHS))
      .finally(() => setThinking(false));
  }, [sessionId]);

  if (thinking) {
    return (
      <div className="stage">
        <FlowProgress step={3} />
        <div className="fade-up" style={{ textAlign: 'center', padding: '80px 0' }}>
          <div style={{ display: 'inline-flex', flexDirection: 'column', alignItems: 'center', gap: 20 }}>
            <div style={{
              width: 64, height: 64, borderRadius: '50%',
              background: 'conic-gradient(from 0deg, transparent, var(--cyan), transparent)',
              animation: 'spin 1.4s linear infinite',
              padding: 2,
            }}>
              <div style={{ width: '100%', height: '100%', borderRadius: '50%', background: 'var(--bg)', display: 'grid', placeItems: 'center' }}>
                <Icon.Brain style={{ width: 24, height: 24, color: 'var(--cyan)' }} />
              </div>
            </div>
            <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
            <div className="h-eyebrow" style={{ margin: 0 }}>Refining target role</div>
            <div className="h1 serif" style={{ fontSize: 36 }}>Matching your signal to 1,400 career trajectories…</div>
            <div className="agent-run" style={{ marginTop: 16, textAlign: 'left', minWidth: 480 }}>
              <RunLine ts="0142ms" tag="resume.parse" line="14 skills · 4 roles · risk 28"/>
              <RunLine ts="0410ms" tag="answers.analyze" line="weighting: technical-depth=0.9, speed=0.7"/>
              <RunLine ts="0780ms" tag="paths.rank" line="scanning 1,412 trajectories…"/>
              <RunLine ts="1180ms" tag="paths.rank" line="3 viable pivots found"/>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="stage">
      <FlowProgress step={3} />
      <div className="fade-up">
        <div className="h-eyebrow">Step 4 · Calibrate your target</div>
        <h1 className="h1 serif">
          You said <span className="accent">Forward Deployed Engineer</span>.<br/>Here's how the agent reads it.
        </h1>
        <p className="sub">
          Based on your resume signals + answers, here are 3 ranked variations of your stated goal. Pick the one that fits — or ask the agent to try again.
        </p>
      </div>

      <div className="fade-up delay-1" style={{ display: 'grid', gap: 16, marginBottom: 32 }}>
        {paths.map((p, i) => (
          <button
            key={p.title}
            className={`path-card ${p.recommended || p.is_recommended ? 'recommended' : ''}`}
            onClick={() => setSelectedIdx(i)}
            style={{
              outline: selectedIdx === i ? '2px solid var(--cyan)' : 'none',
              outlineOffset: 2,
            }}
          >
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 14, gap: 24 }}>
              <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 8 }}>
                  <div className="serif" style={{ fontSize: 24, fontWeight: 500 }}>{p.title}</div>
                  <div style={{ fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--cyan)' }}>{p.match_score || p.match}% match</div>
                </div>
                <div style={{ fontSize: 14, color: 'var(--muted)', lineHeight: 1.55, marginBottom: 14, maxWidth: 600 }}>
                  {p.summary}
                </div>
              </div>
              <div style={{ flexShrink: 0, width: 80, textAlign: 'right' }}>
                <RingMatch value={p.match_score || p.match} />
              </div>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 14, paddingTop: 14, borderTop: '1px solid var(--border)' }}>
              <Stat label="Timeline" value={p.timeline}/>
              <Stat label="Salary delta" value={p.salary_delta || p.salaryDelta} valueColor="var(--green)"/>
              <Stat label="Sample cos" value={(p.sample_cos || p.sampleCos || []).slice(0, 2).join(', ') + '…'} small/>
            </div>

            <details style={{ marginTop: 6 }}>
              <summary style={{ cursor: 'pointer', fontSize: 12, color: 'var(--cyan)', fontFamily: 'var(--mono)', letterSpacing: '0.06em', listStyle: 'none' }}>
                ▸ Why this match
              </summary>
              <ul style={{ marginTop: 10, paddingLeft: 18, fontSize: 13, color: 'var(--muted)', lineHeight: 1.7 }}>
                {(p.reasoning || []).map((r) => <li key={r}>{r}</li>)}
              </ul>
            </details>
          </button>
        ))}
      </div>

      <div className="fade-up delay-2" style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
        <button className="btn-ghost" onClick={onBack}><Icon.ArrowLeft />Back</button>
        <button className="btn-primary" onClick={() => onPick(paths[selectedIdx])}>
          Build my roadmap to {paths[selectedIdx].title}
          <Icon.ArrowRight />
        </button>
        <button className="btn-ghost" onClick={onRedo}>
          <Icon.Refresh /> None feel right — redo
        </button>
      </div>
    </div>
  );
}

function Stat({ label, value, valueColor, small }) {
  return (
    <div>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 9.5, color: 'var(--dim)', letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 4 }}>{label}</div>
      <div style={{ fontSize: small ? 12 : 14, fontWeight: 500, color: valueColor || 'var(--text)' }}>{value}</div>
    </div>
  );
}

function RingMatch({ value }) {
  const r = 28;
  const c = 2 * Math.PI * r;
  const offset = c - (value / 100) * c;
  return (
    <svg width="68" height="68" viewBox="0 0 68 68">
      <circle cx="34" cy="34" r={r} fill="none" stroke="rgba(94, 234, 212, 0.12)" strokeWidth="4"/>
      <circle cx="34" cy="34" r={r} fill="none" stroke="var(--cyan)" strokeWidth="4"
        strokeDasharray={c} strokeDashoffset={offset}
        strokeLinecap="round"
        transform="rotate(-90 34 34)"/>
      <text x="34" y="38" textAnchor="middle" fill="var(--cyan)" fontSize="13" fontWeight="600" fontFamily="var(--mono)">{value}</text>
    </svg>
  );
}

// ============ DISCOVERY FLOW (secondary path) ============
// For users who don't know what they want — agent guides via resume + Qs
function DiscoverScreen({ onPick, onBack, initialStage = 'intro', sessionId }) {
  const [stage, setStage] = React.useState(initialStage); // intro | resume | questions | thinking | paths
  const [hasResume, setHasResume] = React.useState(initialStage !== 'intro' && initialStage !== 'resume');
  const [answers, setAnswers] = React.useState([]);
  const [qStep, setQStep] = React.useState(0);
  const [discoveredPaths, setDiscoveredPaths] = React.useState([]);

  const discoveryQs = [
    {
      q: "When you finish a workday energized — what were you doing?",
      options: [
        "Shipping something a user touches",
        "Untangling a hard technical problem",
        "Talking through trade-offs with smart people",
        "Helping someone unblock themselves",
      ],
    },
    {
      q: "Pick the worst part of your last role.",
      options: [
        "Politics & roadmap drift",
        "Working on things no one used",
        "Being too isolated from customers",
        "Slow pace — quarters of planning, weeks of building",
      ],
    },
    {
      q: "If money & risk weren't factors, what would you build for a year?",
      options: [
        "A tool I wish existed",
        "A startup with 2 friends",
        "A creative project (book, course, film)",
        "Honestly, I just want a great team to ship with",
      ],
    },
    {
      q: "How much do you want to be in front of people vs. heads-down?",
      options: [
        "Mostly heads-down with weekly syncs",
        "Mixed — I like switching modes",
        "Mostly people — I'm drained by long solo stretches",
        "Doesn't matter, just pay me",
      ],
    },
    {
      q: "Pick one trait you want your next job to optimize for.",
      options: [
        "Speed — ship every week",
        "Depth — go obsessive on hard problems",
        "Impact — fewer projects, bigger swings",
        "Comp — show me the money",
      ],
    },
  ];

  const FALLBACK_DISCOVER = [
    {
      title: 'Forward Deployed Engineer',
      match_score: 92,
      recommended: true,
      summary: "Your resume + answers point hard at this. You light up around customers, ship fast, and hate political roadmaps.",
      reasoning: [
        "Top signal from your Q&A: you want customer contact + speed",
        "Resume: strong full-stack work + customer-facing integrations",
        "Salary: +38% over typical roles; demand is at an all-time high",
      ],
      timeline: '3–5 months',
      salary_delta: '+38% median',
      sample_cos: ['Anthropic', 'OpenAI', 'Sierra', 'Decagon'],
    },
    {
      title: 'Founding Engineer (early startup)',
      match_score: 85,
      summary: "Wearing many hats, owning everything, occasional customer contact.",
      reasoning: [
        "Your answers suggest founding-engineer DNA — ownership + speed",
        "You prefer speed over depth, with high autonomy",
        "Path-to-equity matters more than base",
      ],
      timeline: '1–3 months',
      salary_delta: '+0% base / equity upside',
      sample_cos: ['YC seed cos', 'Recently funded Series A'],
    },
    {
      title: 'Developer Relations (DevRel)',
      match_score: 78,
      summary: "Hybrid people + code role. Less ambiguity than FDE, more storytelling.",
      reasoning: [
        "You like being in front of people but also writing code",
        "Lower interview bar than FDE, higher visibility",
        "Strong stepping stone into PM or founder later",
      ],
      timeline: '2–4 months',
      salary_delta: '+15% median',
      sample_cos: ['Vercel', 'Supabase', 'Cloudflare', 'Modal'],
    },
  ];

  // INTRO
  if (stage === 'intro') {
    return (
      <div className="stage">
        <FlowProgress step={0} />
        <div className="fade-up">
          <div className="h-eyebrow">Discovery mode</div>
          <h1 className="h1 serif">
            Let's <span className="accent">figure it out</span> together.
          </h1>
          <p className="sub">
            No goal? No problem. The agent will read your background, ask 5 short questions about what energizes you, and surface 3 career directions worth exploring.
          </p>
        </div>

        <div className="card glow fade-up delay-1" style={{ padding: 28, marginBottom: 28 }}>
          <div style={{ display: 'flex', gap: 16, alignItems: 'flex-start' }}>
            <div style={{
              width: 44, height: 44, borderRadius: 12,
              background: 'rgba(94, 234, 212, 0.12)',
              border: '1px solid var(--border-strong)',
              display: 'grid', placeItems: 'center', color: 'var(--cyan)',
              flexShrink: 0,
            }}>
              <Icon.Brain style={{ width: 22, height: 22 }} />
            </div>
            <div style={{ flex: 1 }}>
              <div className="serif" style={{ fontSize: 18, fontWeight: 500, marginBottom: 6 }}>How discovery works</div>
              <ol style={{ paddingLeft: 18, fontSize: 14, color: 'var(--muted)', lineHeight: 1.8 }}>
                <li>You drop your resume — agent extracts skills & implicit interests</li>
                <li>5 quick MCQs about what energizes & drains you</li>
                <li>Agent ranks 3 career directions specific to your profile</li>
                <li>Pick one — the full roadmap unlocks from there</li>
              </ol>
            </div>
          </div>
        </div>

        <div className="fade-up delay-2" style={{ display: 'flex', gap: 12 }}>
          <button className="btn-ghost" onClick={onBack}><Icon.ArrowLeft /> Back</button>
          <button className="btn-primary" onClick={() => setStage('resume')}>
            Start with my resume
            <Icon.ArrowRight />
          </button>
        </div>
      </div>
    );
  }

  // RESUME
  if (stage === 'resume') {
    return (
      <div className="stage">
        <FlowProgress step={0} />
        <div className="fade-up">
          <div className="h-eyebrow">Discovery · Step 1 of 3</div>
          <h1 className="h1 serif">First, <span className="accent">show us where you stand</span>.</h1>
          <p className="sub">
            We'll mine your resume for skills, transferable strengths, and signals about what you've actually liked doing.
          </p>
        </div>

        <div className="card glow fade-up delay-1" style={{ padding: 28, marginBottom: 28 }}>
          <div
            onClick={() => setHasResume(true)}
            style={{
              border: '1.5px dashed var(--border-strong)',
              borderRadius: 14,
              padding: '44px 28px',
              textAlign: 'center',
              cursor: 'pointer',
              transition: 'all 0.2s',
              background: hasResume ? 'rgba(94, 234, 212, 0.08)' : 'rgba(10, 32, 36, 0.4)',
              borderColor: hasResume ? 'var(--c-300)' : undefined,
            }}
          >
            <div style={{
              width: 56, height: 56, borderRadius: '50%',
              background: 'rgba(94, 234, 212, 0.1)',
              display: 'inline-grid', placeItems: 'center',
              border: '1px solid var(--border-strong)',
              marginBottom: 14,
              color: hasResume ? 'var(--c-200)' : 'var(--cyan)',
            }}>
              {hasResume ? <Icon.Check style={{ width: 22, height: 22 }} /> : <Icon.Upload style={{ width: 22, height: 22 }} />}
            </div>
            <div className="serif" style={{ fontSize: 19, marginBottom: 6 }}>
              {hasResume ? 'Resume parsed · 17 skills, 3 prior roles' : 'Drop resume or click to browse'}
            </div>
            <div style={{ fontSize: 13, color: 'var(--muted)' }}>
              {hasResume ? 'Agent extracted: full-stack range, customer demos, AI-curious side projects' : 'PDF, DOCX, TXT · agent reads it in seconds'}
            </div>
          </div>
        </div>

        <div className="fade-up delay-2" style={{ display: 'flex', gap: 12 }}>
          <button className="btn-ghost" onClick={() => setStage('intro')}><Icon.ArrowLeft /> Back</button>
          <button className="btn-primary" disabled={!hasResume} onClick={() => setStage('questions')}>
            Continue to questions
            <Icon.ArrowRight />
          </button>
        </div>
      </div>
    );
  }

  // QUESTIONS
  if (stage === 'questions') {
    const cur = discoveryQs[qStep];
    return (
      <div className="stage">
        <FlowProgress step={0} />
        <div className="fade-up">
          <div className="h-eyebrow">Discovery · Question {qStep + 1} of {discoveryQs.length}</div>
          <h1 className="h1 serif" style={{ fontSize: 40 }}>
            <span className="accent">{cur.q}</span>
          </h1>
          <p className="sub">No wrong answers. The agent weighs every response when ranking your fit.</p>
        </div>

        <div className="fade-up delay-1" style={{ display: 'grid', gap: 10, marginBottom: 28 }}>
          {cur.options.map((opt, i) => (
            <button
              key={opt}
              onClick={() => {
                const nextAns = [...answers, opt];
                setAnswers(nextAns);
                if (qStep < discoveryQs.length - 1) {
                  setQStep(qStep + 1);
                } else {
                  setStage('thinking');
                  if (window.api && window.api.isAuthenticated() && sessionId) {
                    window.api.discoverPaths(sessionId)
                      .then(data => { setDiscoveredPaths(data?.paths?.length ? data.paths : FALLBACK_DISCOVER); })
                      .catch(() => setDiscoveredPaths(FALLBACK_DISCOVER))
                      .finally(() => setStage('paths'));
                  } else {
                    setTimeout(() => { setDiscoveredPaths(FALLBACK_DISCOVER); setStage('paths'); }, 2200);
                  }
                }
              }}
              style={{
                textAlign: 'left',
                padding: '18px 22px',
                background: 'rgba(10, 17, 36, 0.5)',
                border: '1px solid var(--border)',
                borderRadius: 14,
                fontSize: 16,
                color: 'var(--text)',
                transition: 'all 0.15s',
                animation: `fadeUp 0.4s ease-out ${i * 0.05}s both`,
                display: 'flex',
                alignItems: 'center',
                gap: 14,
              }}
              onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--cyan)'; e.currentTarget.style.background = 'rgba(94, 234, 212, 0.06)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.borderColor = ''; e.currentTarget.style.background = 'rgba(10, 17, 36, 0.5)'; }}
            >
              <span style={{ color: 'var(--cyan)', fontFamily: 'var(--mono)', fontSize: 12, width: 22 }}>{String.fromCharCode(65 + i)}</span>
              {opt}
            </button>
          ))}
        </div>

        <div className="fade-up delay-2" style={{ display: 'flex', gap: 12 }}>
          <button className="btn-ghost" onClick={() => {
            if (qStep === 0) {
              if (initialStage === 'questions') onBack();
              else setStage('resume');
            }
            else { setQStep(qStep - 1); setAnswers(answers.slice(0, -1)); }
          }}><Icon.ArrowLeft /> Back</button>
          <div style={{ flex: 1, height: 4, background: 'rgba(94, 234, 212, 0.12)', borderRadius: 4, marginTop: 16, overflow: 'hidden' }}>
            <div style={{
              height: '100%',
              width: `${((qStep + 1) / discoveryQs.length) * 100}%`,
              background: 'linear-gradient(90deg, var(--c-200), var(--c-400))',
              transition: 'width 0.4s',
            }}/>
          </div>
        </div>
      </div>
    );
  }

  // THINKING
  if (stage === 'thinking') {
    return (
      <div className="stage">
        <FlowProgress step={0} />
        <div className="fade-up" style={{ textAlign: 'center', padding: '80px 0' }}>
          <div style={{ display: 'inline-flex', flexDirection: 'column', alignItems: 'center', gap: 20 }}>
            <div style={{
              width: 64, height: 64, borderRadius: '50%',
              background: 'conic-gradient(from 0deg, transparent, var(--cyan), transparent)',
              animation: 'spin 1.4s linear infinite',
              padding: 2,
            }}>
              <div style={{ width: '100%', height: '100%', borderRadius: '50%', background: 'var(--bg)', display: 'grid', placeItems: 'center' }}>
                <Icon.Brain style={{ width: 24, height: 24, color: 'var(--cyan)' }} />
              </div>
            </div>
            <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
            <div className="h-eyebrow" style={{ margin: 0 }}>Cross-referencing your profile</div>
            <div className="h1 serif" style={{ fontSize: 30 }}>Matching your signal to 1,412 career trajectories…</div>
            <div className="agent-run" style={{ marginTop: 16, textAlign: 'left', minWidth: 480 }}>
              <RunLine ts="0142ms" tag="resume.parse" line="17 skills · 3 roles detected"/>
              <RunLine ts="0410ms" tag="discovery.score" line="weights: customer-contact=0.9, speed=0.8, depth=0.4"/>
              <RunLine ts="0780ms" tag="paths.rank" line="filtering 1,412 trajectories…"/>
              <RunLine ts="1180ms" tag="paths.rank" line="3 strong directions surfaced"/>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // PATHS
  return (
    <div className="stage">
      <FlowProgress step={0} />
      <div className="fade-up">
        <div className="h-eyebrow">Discovery · Pick a direction</div>
        <h1 className="h1 serif">
          You said you wanted <span className="accent">customer contact + speed</span>.<br/>Here's what fits.
        </h1>
        <p className="sub">
          3 directions ranked by your resume + answers. Pick one to unlock the full roadmap. (Or go back and answer differently.)
        </p>
      </div>

      <div className="fade-up delay-1" style={{ display: 'grid', gap: 16, marginBottom: 32 }}>
        {discoveredPaths.map((p, i) => (
          <button
            key={p.title}
            className={`path-card ${p.recommended ? 'recommended' : ''}`}
            onClick={() => onPick(p)}
          >
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 14, gap: 24 }}>
              <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 8 }}>
                  <div className="serif" style={{ fontSize: 24, fontWeight: 500 }}>{p.title}</div>
                  <div style={{ fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--cyan)' }}>{p.match_score || p.match}% match</div>
                </div>
                <div style={{ fontSize: 14, color: 'var(--muted)', lineHeight: 1.55, marginBottom: 14, maxWidth: 600 }}>
                  {p.summary}
                </div>
              </div>
              <div style={{ flexShrink: 0, width: 80, textAlign: 'right' }}>
                <RingMatch value={p.match_score || p.match} />
              </div>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 14, paddingTop: 14, borderTop: '1px solid var(--border)' }}>
              <Stat label="Timeline" value={p.timeline}/>
              <Stat label="Salary delta" value={p.salary_delta || p.salaryDelta} valueColor="var(--green)"/>
              <Stat label="Sample cos" value={(p.sample_cos || p.sampleCos || []).slice(0, 2).join(', ') + '…'} small/>
            </div>

            <details style={{ marginTop: 6 }}>
              <summary style={{ cursor: 'pointer', fontSize: 12, color: 'var(--cyan)', fontFamily: 'var(--mono)', letterSpacing: '0.06em', listStyle: 'none' }}>
                ▸ Why this fits
              </summary>
              <ul style={{ marginTop: 10, paddingLeft: 18, fontSize: 13, color: 'var(--muted)', lineHeight: 1.7 }}>
                {(p.reasoning || []).map((r) => <li key={r}>{r}</li>)}
              </ul>
            </details>
          </button>
        ))}
      </div>

      <div className="fade-up delay-2" style={{ display: 'flex', gap: 12 }}>
        <button className="btn-ghost" onClick={() => setStage('questions')}><Icon.ArrowLeft /> Re-answer questions</button>
        <button className="btn-ghost" onClick={onBack}>
          <Icon.Refresh /> Restart — I do know what I want
        </button>
      </div>
    </div>
  );
}

function RunLine({ ts, tag, line, status }) {
  return (
    <div className={`agent-run-line ${status || ''}`}>
      <span className="agent-run-ts">{ts}</span>
      <span className="agent-run-tag">{tag}</span>
      <span>→ {line}</span>
    </div>
  );
}

// ============ FLOW PROGRESS ============
function FlowProgress({ step }) {
  const steps = ['Goal', 'Profile', 'Q&A', 'Refine', 'Roadmap'];
  return (
    <div className="flow-progress">
      {steps.map((s, i) => (
        <React.Fragment key={s}>
          <div className={`dot ${i === step ? 'active' : i < step ? 'done' : ''}`} />
          {i === step && <span className="label">{s.toUpperCase()}</span>}
        </React.Fragment>
      ))}
    </div>
  );
}

window.GoalEntryScreen = GoalEntryScreen;
window.ResumeScreen = ResumeScreen;
window.QuestionsScreen = QuestionsScreen;
window.RefineScreen = RefineScreen;
window.DiscoverScreen = DiscoverScreen;
window.FlowProgress = FlowProgress;
window.RunLine = RunLine;
