function JobDetail({ onNavigate, jobId }) {
  // 우선순위: URL/prop → localStorage → 첫 활성 공고
  const [job, setJob] = useState(() => {
    if (window.CIS) {
      const specific = jobId ? CIS.getJob(jobId) : null;
      return specific || CIS.getJobs().find(j => j.status === 'active') || CIS.getJobs()[0];
    }
    return null;
  });

  const [analyzing, setAnalyzing] = useState(true);
  const [fit, setFit] = useState(null);

  useEffect(() => {
    if (jobId && window.CIS) {
      const j = CIS.getJob(jobId);
      if (j) setJob(j);
    }
  }, [jobId]);

  // 지원자 스킬 (목업) — 실제 서비스라면 로그인된 사용자 프로필에서 로드
  const applicantSkills = ['React', 'TypeScript', 'Web Performance', 'Storybook', 'Design System', 'CSS'];
  const applicantYears = 5;

  // 채용공고 우선분석 — 페이지 진입 즉시 실행 (Job-first analysis)
  useEffect(() => {
    if (!job) return;
    setAnalyzing(true);
    const t = setTimeout(() => {
      setFit(CIS.scoreApplicantAgainstJob(applicantSkills, job));
      setAnalyzing(false);
    }, 900);
    return () => clearTimeout(t);
  }, [job]);

  if (!job) {
    return (
      <div style={{ maxWidth: 700, margin: '80px auto', padding: 40, textAlign: 'center', color: 'var(--fg-3)' }}>
        공고를 찾을 수 없습니다. · Job not found.
      </div>
    );
  }

  const ind  = CIS.industryOf(job.industryId);
  const dept = CIS.departmentOf(job.deptId);

  return (
    <div style={{ maxWidth: 1080, margin: '0 auto', padding: '32px 40px 80px' }}>
      {/* Breadcrumb */}
      <button onClick={()=>onNavigate('jobs')} style={{
        background:'none', border:'none', cursor:'pointer', color:'var(--fg-3)',
        fontSize: 12.5, display:'inline-flex', alignItems:'center', gap:4, padding: 0, marginBottom: 20,
      }}>
        <Icon name="arrow-left" size={13}/>모든 채용공고 (All jobs)
      </button>

      {/* ========================================================
         🎯 채용공고 우선분석 리포트 (최상단)
         "지원자 채용공고 우선분석" 요구사항의 핵심 구현부.
         상세 페이지 진입 즉시 이 공고에 대한 매칭 점수를 계산해서 보여줌.
         ======================================================== */}
      <FitReport analyzing={analyzing} fit={fit} job={job} ind={ind}
        onStartMock={() => onNavigate('mock', { jobId: job.id })}
        onApply={() => onNavigate('apply', { jobId: job.id })}/>

      {/* Two-column layout */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 40, marginTop: 32 }}>
        {/* Main */}
        <div>
          <TagLine>{dept.ko.toUpperCase()} · {job.level}</TagLine>
          <h1 style={{ fontSize: 32, fontWeight: 700, letterSpacing:'-0.03em', margin: '10px 0 4px', lineHeight: 1.15 }}>
            {job.title_ko || job.title}
          </h1>
          {job.title_en && (
            <div style={{ fontSize: 17, color: 'var(--fg-3)', fontWeight: 500, marginBottom: 12 }}>
              {job.title_en}
            </div>
          )}
          {/* 업종(카테고리) 병행 표시 — CORE REQUIREMENT */}
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '6px 12px', background: 'var(--brand-50)',
            border: '1px solid var(--brand-100, #BFD3FF)',
            color: 'var(--brand-700)', borderRadius: 999,
            fontSize: 12.5, fontWeight: 600, marginTop: 6,
          }}>
            <Icon name="building-2" size={12}/>
            {ind.ko} <span style={{ opacity: 0.7, fontWeight: 500 }}>({ind.en})</span>
          </div>
          <div style={{ display:'flex', gap: 14, marginTop: 14, fontSize: 13, color: 'var(--fg-2)', flexWrap: 'wrap' }}>
            <span style={{display:'inline-flex',alignItems:'center',gap:4}}><Icon name="map-pin" size={13}/>{job.loc_ko || job.loc}</span>
            <span style={{display:'inline-flex',alignItems:'center',gap:4}}><Icon name="briefcase" size={13}/>{job.empType || job.type}</span>
            <span style={{display:'inline-flex',alignItems:'center',gap:4}}><Icon name="clock" size={13}/>상시 채용 · Rolling basis</span>
          </div>

          {/* Body */}
          <div style={{ marginTop: 36, fontSize: 15, lineHeight: 1.7, color: 'var(--fg-1)' }}>
            {(job.responsibilities || job.seed) && (
              <>
                <h2 style={sectionH2}>이런 일을 해요 <span style={sectionEn}>(Responsibilities)</span></h2>
                <ContentBlock text={job.responsibilities || 'Toss 결제 SDK의 신규 기능 설계·개발\n디자인 시스템 컴포넌트 오너십 (Buttons, Fields, Modals)\n주니어 엔지니어 코드 리뷰 및 기술 멘토링'}/>
              </>
            )}

            {(job.requirements || job.seed) && (
              <>
                <h2 style={sectionH2}>이런 분을 찾아요 <span style={sectionEn}>(Requirements)</span></h2>
                <ContentBlock text={job.requirements || 'React·TypeScript로 프로덕션 제품을 5년 이상 만들어보신 분\nWeb Performance 지표를 개선한 경험 (LCP, INP)\n디자인 시스템·컴포넌트 라이브러리를 설계·유지해보신 분'}/>
              </>
            )}

            {job.preferred && (
              <>
                <h2 style={sectionH2}>우대 사항 <span style={sectionEn}>(Preferred)</span></h2>
                <ContentBlock text={job.preferred}/>
              </>
            )}

            {job.skills && job.skills.length > 0 && (
              <>
                <h2 style={sectionH2}>핵심 스킬 <span style={sectionEn}>(Key Skills)</span></h2>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 8 }}>
                  {job.skills.map(s => {
                    const hit = fit && fit.matched.map(x=>x.toLowerCase()).includes(s.toLowerCase());
                    return (
                      <span key={s} style={{
                        padding: '5px 12px',
                        background: hit ? 'var(--success-50, #E7F7EE)' : 'var(--neutral-100)',
                        color: hit ? 'var(--success-700, #0A6D30)' : 'var(--fg-2)',
                        border: hit ? '1px solid var(--success-500, #17A34A)' : '1px solid transparent',
                        borderRadius: 999, fontSize: 12.5, fontWeight: 500,
                        display: 'inline-flex', alignItems: 'center', gap: 4,
                      }}>
                        {hit && <Icon name="check" size={11}/>}
                        {s}
                      </span>
                    );
                  })}
                </div>
                {fit && (
                  <div style={{ fontSize: 11.5, color: 'var(--fg-3)', marginTop: 8 }}>
                    ● 초록색 태그 = 내 프로필과 일치하는 스킬 · Green = matches your profile
                  </div>
                )}
              </>
            )}
          </div>
        </div>

        {/* Sticky sidebar */}
        <aside>
          <div style={{
            position: 'sticky', top: 88,
            padding: 20,
            background: 'var(--neutral-0)',
            border: '1px solid var(--border-default)',
            borderRadius: 14,
          }}>
            <div style={{ fontSize: 12, color: 'var(--fg-3)', letterSpacing:'0.06em', textTransform:'uppercase', fontWeight: 500 }}>
              지원 마감 (Deadline)
            </div>
            <div style={{ fontSize: 18, fontWeight: 700, marginTop: 4 }}>상시 · 마감 없음</div>
            <div style={{ fontSize: 11.5, color: 'var(--fg-3)', marginTop: 2 }}>Rolling · No deadline</div>

            <Button variant="primary" size="lg" style={{ width:'100%', justifyContent:'center', marginTop: 16 }} onClick={()=>onNavigate('apply', { jobId: job.id })}>
              지금 지원하기 (Apply Now)
            </Button>
            <button onClick={() => onNavigate('mock', { jobId: job.id })} style={{
              width:'100%', marginTop: 8, padding: '10px 14px',
              background:'transparent', border:'1px solid var(--brand-500)', borderRadius: 8,
              fontSize: 13, fontWeight: 600, color:'var(--brand-600)', cursor:'pointer',
              display:'inline-flex', alignItems:'center', justifyContent:'center', gap: 6,
              fontFamily: 'var(--font-sans)',
            }}>
              <Icon name="sparkles" size={14}/>이 공고로 AI 모의면접 시작
            </button>

            <div style={{ height: 1, background:'var(--border-subtle)', margin: '20px -20px' }}/>

            <div style={{ display:'grid', gap: 10 }}>
              <MetaRow label="채용 담당 (Recruiter)"     value="한지현"/>
              <MetaRow label="Hiring Manager"            value="박준영"/>
              <MetaRow label="채용 절차 (Process)"        value="서류 → 1차 → 2차 → 오퍼"/>
              <MetaRow label="예상 프로세스 (Timeline)"    value="약 3-4주 (3-4 weeks)"/>
              {job.questions && (
                <MetaRow label="AI 면접질문"                value={`${job.questions.length}개 준비됨 (ready)`}/>
              )}
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}

/* ======================================================================
 * FitReport — 채용공고 우선분석 리포트 (핵심 컴포넌트)
 * 페이지 진입 → 로딩 900ms → 매칭 점수 + 스킬 갭 + 액션 안내
 * ====================================================================== */
function FitReport({ analyzing, fit, job, ind, onStartMock, onApply }) {
  return (
    <div style={{
      position: 'relative',
      background: 'linear-gradient(135deg, #F3EFFF 0%, #EDF2FF 50%, #F5F8FF 100%)',
      border: '1px solid var(--violet-100, #E4DAFF)',
      borderRadius: 16, padding: 22, overflow: 'hidden',
    }}>
      {/* Decorative sparkle glow */}
      <div style={{
        position: 'absolute', top: -40, right: -40,
        width: 220, height: 220,
        background: 'radial-gradient(circle, rgba(124,85,242,0.18), transparent 70%)',
        borderRadius: 999, pointerEvents: 'none',
      }}/>

      <div style={{ display: 'flex', alignItems: 'center', gap: 10, position: 'relative' }}>
        <div style={{
          width: 36, height: 36, borderRadius: 10,
          background: 'linear-gradient(135deg, var(--violet-500, #7C55F2), var(--brand-500))',
          color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="sparkles" size={18}/>
        </div>
        <div style={{ minWidth: 0 }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '3px 8px', background: 'rgba(124,85,242,0.12)',
            color: 'var(--violet-700, #4E27B5)', borderRadius: 999,
            fontSize: 10.5, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase',
          }}>
            Job-First Analysis · 공고 우선분석
          </div>
          <div style={{ fontSize: 15, fontWeight: 700, letterSpacing: '-0.01em', marginTop: 3 }}>
            채용공고 매칭 리포트 <span style={{ color: 'var(--fg-3)', fontWeight: 500 }}>(Fit Report)</span>
          </div>
        </div>
        <div style={{ flex: 1 }}/>
        {!analyzing && fit && (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8,
            padding: '4px 10px', background: 'rgba(255,255,255,0.7)',
            border: '1px solid var(--violet-100, #E4DAFF)', borderRadius: 999,
            fontSize: 11, color: 'var(--fg-3)',
          }}>
            <Icon name="check-circle-2" size={12}/>
            분석 완료 · {new Date().toISOString().slice(11, 16)} 기준
          </div>
        )}
      </div>

      {analyzing ? (
        <AnalyzingSkeleton/>
      ) : (
        <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: 'minmax(150px, 180px) minmax(0, 1fr) minmax(180px, auto)', gap: 24, alignItems: 'center', position: 'relative' }}>
          {/* Score dial */}
          <ScoreDial score={fit.overall}/>

          {/* Breakdown */}
          <div style={{ display: 'grid', gap: 8, minWidth: 0 }}>
            <BreakdownRow label="스킬 매칭"       en="Skill Match"        pct={fit.skill}  color="var(--brand-500)"/>
            <BreakdownRow label="경력 적합"       en="Experience Fit"     pct={fit.career} color="var(--violet-500, #7C55F2)"/>
            <BreakdownRow label="문화 fit"       en="Culture Fit"        pct={fit.culture} color="var(--success-500, #17A34A)"/>
          </div>

          {/* Actions */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, minWidth: 176 }}>
            <button onClick={onStartMock} style={{
              padding: '10px 14px',
              background: 'linear-gradient(135deg, var(--brand-500), var(--violet-500, #7C55F2))',
              color: '#fff', border: 'none', borderRadius: 8, cursor: 'pointer',
              fontSize: 12.5, fontWeight: 700, fontFamily: 'var(--font-sans)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              boxShadow: '0 4px 12px rgba(124,85,242,0.25)',
            }}>
              <Icon name="video" size={13}/>
              모의면접 시작
            </button>
            <button onClick={onApply} style={{
              padding: '10px 14px',
              background: 'var(--neutral-0)', color: 'var(--fg-1)',
              border: '1px solid var(--border-strong)', borderRadius: 8, cursor: 'pointer',
              fontSize: 12.5, fontWeight: 600, fontFamily: 'var(--font-sans)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            }}>
              <Icon name="send" size={13}/>
              바로 지원 (Apply)
            </button>
          </div>

          {/* Skill gap detail — spans full width */}
          <div style={{ gridColumn: '1 / -1', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 6 }}>
            <SkillGapCard tone="ok" title="일치하는 스킬" en="Matching skills" items={fit.matched}/>
            <SkillGapCard tone="gap" title="보완이 필요한 스킬" en="Skills to strengthen" items={fit.missing}
              hint={fit.missing.length > 0 ? '모의면접에서 이 주제 위주로 연습해보세요.' : '완벽해요! 자신감을 가지고 지원하세요.'}/>
          </div>
        </div>
      )}
    </div>
  );
}

function AnalyzingSkeleton() {
  return (
    <div style={{ marginTop: 18, display: 'flex', alignItems: 'center', gap: 14 }}>
      <div style={{
        width: 22, height: 22, borderRadius: 999,
        border: '2.5px solid var(--violet-200, #D6C4FF)',
        borderTopColor: 'var(--violet-500, #7C55F2)',
        animation: 'spin 800ms linear infinite',
      }}/>
      <div>
        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-1)' }}>
          공고를 분석하고 있어요… <span style={{ color: 'var(--fg-3)', fontWeight: 500 }}>Analyzing job requirements…</span>
        </div>
        <div style={{ fontSize: 12, color: 'var(--fg-3)', marginTop: 2 }}>
          자격 요건 · 스킬 · 업종 특성을 기준으로 매칭 점수 계산 중.
        </div>
      </div>
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
}

function ScoreDial({ score }) {
  const color = score >= 85 ? 'var(--success-500, #17A34A)' : score >= 70 ? 'var(--brand-500)' : 'var(--warn-500, #E39514)';
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
      <div style={{
        width: 132, height: 132, borderRadius: 999,
        background: `conic-gradient(${color} ${score * 3.6}deg, rgba(255,255,255,0.5) 0deg)`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: '0 4px 20px rgba(124,85,242,0.15)',
      }}>
        <div style={{
          width: 108, height: 108, borderRadius: 999, background: '#fff',
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        }}>
          <div style={{
            fontFamily: 'var(--font-latin)', fontVariantNumeric: 'tabular-nums',
            fontSize: 40, fontWeight: 800, letterSpacing: '-0.03em', color, lineHeight: 1,
          }}>{score}</div>
          <div style={{ fontSize: 10, color: 'var(--fg-3)', letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 600, marginTop: 4 }}>
            Match Score
          </div>
        </div>
      </div>
      <div style={{
        marginTop: 8, fontSize: 11, color: 'var(--fg-3)',
        fontWeight: 500, textAlign: 'center',
      }}>
        {score >= 85 ? '강력 추천 · Strong match'
         : score >= 70 ? '적합 · Good match'
         : '연습 후 도전 · Practice recommended'}
      </div>
    </div>
  );
}

function BreakdownRow({ label, en, pct, color }) {
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', fontSize: 12, gap: 8 }}>
        <span style={{ color: 'var(--fg-1)', fontWeight: 600, whiteSpace: 'nowrap' }}>
          {label} <span style={{ color: 'var(--fg-3)', fontWeight: 400 }}>({en})</span>
        </span>
        <span style={{
          fontFamily: 'var(--font-latin)', fontVariantNumeric: 'tabular-nums',
          fontWeight: 700, color: color, whiteSpace: 'nowrap',
        }}>{pct}%</span>
      </div>
      <div style={{
        marginTop: 5, height: 6, background: 'rgba(255,255,255,0.6)', borderRadius: 999, overflow: 'hidden',
      }}>
        <div style={{ width: `${pct}%`, height: '100%', background: color, borderRadius: 999, transition: 'width 400ms ease-out' }}/>
      </div>
    </div>
  );
}

function SkillGapCard({ tone, title, en, items, hint }) {
  const bg = tone === 'ok' ? 'rgba(23,163,74,0.08)' : 'rgba(227,149,20,0.08)';
  const border = tone === 'ok' ? 'rgba(23,163,74,0.24)' : 'rgba(227,149,20,0.28)';
  const fg = tone === 'ok' ? 'var(--success-700, #0A6D30)' : 'var(--warn-700, #8F5807)';
  const icon = tone === 'ok' ? 'check-circle-2' : 'alert-triangle';
  return (
    <div style={{
      padding: 12, background: bg, border: `1px solid ${border}`, borderRadius: 10,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <Icon name={icon} size={13} style={{ color: fg }}/>
        <span style={{ fontSize: 11.5, fontWeight: 700, color: fg }}>
          {title} <span style={{ opacity: 0.7, fontWeight: 500 }}>({en})</span>
        </span>
      </div>
      <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap', marginTop: 8, minHeight: 22 }}>
        {items.length === 0 ? (
          <span style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>{tone === 'gap' ? '없음 · None' : '—'}</span>
        ) : items.map(s => (
          <span key={s} style={{
            padding: '2px 8px', background: 'rgba(255,255,255,0.7)',
            borderRadius: 4, fontSize: 11, fontWeight: 500, color: 'var(--fg-1)',
          }}>{s}</span>
        ))}
      </div>
      {hint && (
        <div style={{ fontSize: 10.5, color: 'var(--fg-3)', marginTop: 6, lineHeight: 1.5 }}>{hint}</div>
      )}
    </div>
  );
}

function ContentBlock({ text }) {
  const lines = text.split('\n').filter(Boolean);
  return (
    <ul style={{ margin: 0, paddingLeft: 20, color: 'var(--fg-2)' }}>
      {lines.map((l, i) => <li key={i} style={{ marginBottom: 4 }}>{l.replace(/^[-•]\s*/, '')}</li>)}
    </ul>
  );
}

function MetaRow({ label, value }) {
  return (
    <div>
      <div style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>{label}</div>
      <div style={{ fontSize: 13, fontWeight: 500, marginTop: 2 }}>{value}</div>
    </div>
  );
}

const sectionH2 = { fontSize: 20, fontWeight: 700, letterSpacing:'-0.01em', margin: '32px 0 12px' };
const sectionEn = { fontSize: 14, color: 'var(--fg-3)', fontWeight: 500, marginLeft: 4 };

window.JobDetail = JobDetail;
