function JobPostings() {
  const [showForm, setShowForm] = useState(false);
  const [jobs, setJobs] = useState(() => (window.CIS ? CIS.getJobs() : []));
  const [filter, setFilter] = useState('all');   // all | active | draft | closed
  const [flash, setFlash] = useState(null);      // 방금 생성된 공고 ID (하이라이트)

  function refresh() { setJobs(CIS.getJobs()); }

  const filtered = jobs.filter(j => filter === 'all' ? true : j.status === filter);
  const counts = {
    all: jobs.length,
    active: jobs.filter(j => j.status === 'active').length,
    draft: jobs.filter(j => j.status === 'draft').length,
    closed: jobs.filter(j => j.status === 'closed').length,
  };

  function handleCreated(job) {
    refresh();
    setFlash(job.id);
    setTimeout(() => setFlash(null), 3400);
  }

  return (
    <div style={{ padding: '20px 24px', display: 'grid', gap: 16 }}>
      {/* Header */}
      <div style={{ display:'flex', alignItems:'center', gap: 10 }}>
        <div style={{ minWidth: 0 }}>
          <h1 style={{ fontSize: 22, fontWeight: 700, letterSpacing:'-0.02em', margin: 0 }}>
            채용공고 <span style={{ fontSize: 13, color: 'var(--fg-3)', fontWeight: 500, marginLeft: 4 }}>(Job Postings)</span>
          </h1>
          <div style={{ fontSize: 12.5, color: 'var(--fg-3)', marginTop: 2 }}>
            {counts.active}개 진행 중 · 이번 달 신규 지원 152건 · {counts.all} total
          </div>
        </div>
        <div style={{ flex: 1 }} />
        <Button variant="secondary" size="md" icon="download">CSV 내보내기 (Export)</Button>
        <Button variant="primary" size="md" icon="plus" onClick={() => setShowForm(true)}>
          공고 만들기 (Create Posting)
        </Button>
      </div>

      {/* Flash: 방금 생성 알림 */}
      {flash && (
        <div style={{
          padding: '12px 14px',
          background: 'linear-gradient(135deg, #E7F7EE 0%, #F0FFF6 100%)',
          border: '1px solid var(--success-100, #B7E9C6)', borderRadius: 10,
          display: 'flex', alignItems: 'center', gap: 10, fontSize: 13,
        }}>
          <div style={{
            width: 30, height: 30, borderRadius: 8,
            background: 'var(--success-500, #17A34A)', color: '#fff',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          }}><Icon name="check" size={16}/></div>
          <div style={{ flex: 1 }}>
            <b style={{ color: 'var(--success-700, #0A6D30)' }}>공고가 발행되었어요 · Posting published.</b>{' '}
            <span style={{ color: 'var(--fg-2)' }}>
              AI 면접질문이 함께 저장되어, 지원자가 이 공고로 모의면접을 시작할 수 있어요.
            </span>
          </div>
          <button onClick={() => setFlash(null)} style={{
            background: 'transparent', border: 'none', cursor: 'pointer', color: 'var(--fg-3)',
          }}><Icon name="x" size={14}/></button>
        </div>
      )}

      {/* Filter tabs */}
      <div style={{ display:'flex', gap: 4, borderBottom: '1px solid var(--border-default)' }}>
        {[
          ['all',    '전체 (All)',        counts.all],
          ['active', '진행 중 (Active)',  counts.active],
          ['draft',  '임시저장 (Draft)',   counts.draft],
          ['closed', '마감 (Closed)',      counts.closed],
        ].map(([id, label, c]) => (
          <div key={id} onClick={() => setFilter(id)} style={{
            padding: '10px 14px', fontSize: 13,
            fontWeight: filter === id ? 600 : 500,
            color: filter === id ? 'var(--fg-1)' : 'var(--fg-3)',
            borderBottom: `2px solid ${filter === id ? 'var(--brand-500)' : 'transparent'}`,
            cursor: 'pointer', marginBottom: -1,
            display:'inline-flex', alignItems:'center', gap: 6,
          }}>{label}<span style={{ fontSize: 11, color: 'var(--fg-3)', fontFamily:'var(--font-latin)', fontVariantNumeric:'tabular-nums' }}>{c}</span></div>
        ))}
      </div>

      {/* Job cards */}
      {filtered.length === 0 ? (
        <EmptyState onCreate={() => setShowForm(true)}/>
      ) : (
        <div style={{ display: 'grid', gap: 10 }}>
          {filtered.map(j => <JobCard key={j.id} job={j} isNew={flash === j.id}/>)}
        </div>
      )}

      <JobPostingForm open={showForm} onClose={() => setShowForm(false)} onCreated={handleCreated}/>
    </div>
  );
}

function JobCard({ job, isNew }) {
  const stageTone = { active: 'success', draft: 'neutral', closed: 'danger' };
  const stageLabel = {
    active: '진행 중 · Active',
    draft:  '임시저장 · Draft',
    closed: '마감 · Closed',
  };
  const ind = CIS.industryOf(job.industryId);
  const dept = CIS.departmentOf(job.deptId);

  return (
    <Card hoverable style={{
      padding: '14px 18px',
      display:'grid', gridTemplateColumns:'1fr 320px', gap: 20, alignItems: 'center',
      border: isNew ? '2px solid var(--success-500, #17A34A)' : undefined,
      boxShadow: isNew ? '0 0 0 4px rgba(23, 163, 74, 0.12)' : undefined,
      position: 'relative',
    }}>
      {isNew && (
        <div style={{
          position: 'absolute', top: -10, right: 14,
          padding: '3px 10px', background: 'var(--success-500, #17A34A)', color: '#fff',
          fontSize: 10.5, fontWeight: 700, letterSpacing: '0.06em',
          borderRadius: 999,
        }}>NEW · 방금 생성됨</div>
      )}
      <div>
        <div style={{ display:'flex', alignItems:'center', gap: 10, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 15, fontWeight: 600 }}>
            {job.title_ko || job.title}
            {job.title_en && (
              <span style={{ fontSize: 12.5, color: 'var(--fg-3)', fontWeight: 500, marginLeft: 6 }}>
                ({job.title_en})
              </span>
            )}
          </span>
          <Badge tone={stageTone[job.status]} dot>{stageLabel[job.status]}</Badge>
          {job.questions && job.questions.length > 0 && (
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: 4,
              padding: '2px 8px', background: 'var(--violet-50, #F3EFFF)',
              color: 'var(--violet-700, #4E27B5)', borderRadius: 999,
              fontSize: 10.5, fontWeight: 600,
            }}>
              <AISparkle size={10}/>
              면접질문 {job.questions.length}개
            </span>
          )}
        </div>
        {/* 업종(카테고리) 병행 표시 */}
        <div style={{
          display: 'flex', gap: 12, marginTop: 8, flexWrap: 'wrap',
          fontSize: 12, color: 'var(--fg-3)',
        }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
            <Icon name="building" size={11}/>
            <b style={{ color: 'var(--fg-2)' }}>{ind.ko}</b>
            <span style={{ opacity: .7 }}>({ind.en})</span>
          </span>
          <span style={{ opacity: .5 }}>·</span>
          <span>{dept.ko} <span style={{ opacity: .6 }}>({dept.en})</span></span>
          <span style={{ opacity: .5 }}>·</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
            <Icon name="map-pin" size={11}/>{job.loc_ko || job.loc}
          </span>
          <span style={{ opacity: .5 }}>·</span>
          <span>{job.empType || job.type}</span>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 20, alignItems: 'center', justifyContent: 'flex-end' }}>
        <MetricSmall value={job.applicants} label="지원자 (Applicants)"/>
        {job.new > 0 && <MetricSmall value={`+${job.new}`} label="신규 (New)" accent/>}
        <button style={{
          padding: '8px 12px', background: 'transparent',
          border: '1px solid var(--border-strong)', borderRadius: 8,
          fontSize: 12.5, fontWeight: 600, cursor: 'pointer', color: 'var(--fg-1)',
          fontFamily: 'var(--font-sans)',
          display: 'inline-flex', alignItems: 'center', gap: 4,
        }}>파이프라인 <Icon name="arrow-right" size={12}/></button>
      </div>
    </Card>
  );
}

function MetricSmall({ value, label, accent }) {
  return (
    <div style={{ textAlign: 'right', minWidth: 62 }}>
      <div style={{
        fontFamily: 'var(--font-latin)', fontVariantNumeric: 'tabular-nums',
        fontSize: 20, fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1,
        color: accent ? 'var(--brand-600)' : 'var(--fg-1)',
      }}>{value}</div>
      <div style={{
        fontSize: 10, color: 'var(--fg-3)', letterSpacing: '0.04em',
        textTransform: 'uppercase', fontWeight: 500, marginTop: 4, whiteSpace: 'nowrap',
      }}>{label}</div>
    </div>
  );
}

function EmptyState({ onCreate }) {
  return (
    <div style={{
      padding: '48px 24px', textAlign: 'center',
      background: 'var(--neutral-0)', border: '1px dashed var(--border-strong)',
      borderRadius: 12,
    }}>
      <div style={{
        width: 48, height: 48, borderRadius: 12,
        background: 'var(--brand-50)', color: 'var(--brand-600)',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        marginBottom: 12,
      }}><Icon name="briefcase" size={22}/></div>
      <div style={{ fontSize: 15, fontWeight: 700 }}>등록된 공고가 없어요</div>
      <div style={{ fontSize: 12.5, color: 'var(--fg-3)', marginTop: 4 }}>
        No postings yet · 첫 공고를 만들면 AI가 면접질문을 자동 생성합니다.
      </div>
      <div style={{ marginTop: 16 }}>
        <Button variant="primary" size="md" icon="plus" onClick={onCreate}>공고 만들기 (Create Posting)</Button>
      </div>
    </div>
  );
}

window.JobPostings = JobPostings;
