/* JobPostingForm.jsx
 * 관리자용 채용공고 등록 모달.
 * 단계: 1) 기본 정보 (포지션/업종/부서) → 2) JD 작성 → 3) AI 면접질문 자동생성 리뷰 → 4) 발행
 * 저장 대상: window.CIS.saveJob(job)  · localStorage: 'cis-jobs-v1'
 */
function JobPostingForm({ open, onClose, onCreated }) {
  const [step, setStep] = useState(1);      // 1 = form, 2 = questions review
  const [form, setForm] = useState({
    title_ko: '', title_en: '',
    company: 'Toss Payments',
    industryId: 'fintech',
    deptId: 'eng',
    level: 'Mid',
    loc_ko: '서울', loc_en: 'Seoul',
    empType: 'Full-time',
    skills: '',           // comma-separated
    responsibilities: '',
    requirements: '',
    preferred: '',
  });
  const [busy, setBusy] = useState(false);
  const [questions, setQuestions] = useState(null);
  const [errors, setErrors] = useState({});

  useEffect(() => {
    if (open) {
      // 모달 열릴 때마다 초기화
      setStep(1); setQuestions(null); setErrors({});
    }
  }, [open]);

  if (!open) return null;

  function set(k, v) { setForm(f => ({ ...f, [k]: v })); }

  function validate() {
    const e = {};
    if (!form.title_ko.trim()) e.title_ko = '포지션 (한글)을 입력해주세요.';
    if (!form.title_en.trim()) e.title_en = 'Position (English) is required.';
    if (!form.requirements.trim()) e.requirements = '자격 요건을 입력해주세요.';
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  async function goNext() {
    if (!validate()) return;
    setBusy(true);
    const job = buildJob();
    try {
      const qs = await CIS.generateInterviewQuestions(job);
      setQuestions(qs);
      setStep(2);
    } catch (err) {
      alert('면접질문 생성 중 오류: ' + err.message);
    } finally {
      setBusy(false);
    }
  }

  function buildJob() {
    const skills = form.skills.split(',').map(s => s.trim()).filter(Boolean);
    return {
      id: CIS.newJobId(),
      title_ko: form.title_ko.trim(),
      title_en: form.title_en.trim(),
      company: form.company,
      industryId: form.industryId,
      deptId: form.deptId,
      level: form.level,
      loc_ko: form.loc_ko.trim(),
      loc_en: form.loc_en.trim(),
      empType: form.empType,
      skills,
      responsibilities: form.responsibilities.trim(),
      requirements: form.requirements.trim(),
      preferred: form.preferred.trim(),
      status: 'active',
      openedAt: new Date().toISOString().slice(0,10),
      applicants: 0, new: 0,
      questions: null,
      createdAt: Date.now(),
    };
  }

  function publish() {
    const job = buildJob();
    job.questions = questions;
    CIS.saveJob(job);
    onCreated && onCreated(job);
    onClose && onClose();
  }

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

  return (
    <div style={backdropStyle} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div style={modalStyle} role="dialog" aria-modal="true">
        {/* Header */}
        <div style={{
          padding: '18px 24px', borderBottom: '1px solid var(--border-subtle)',
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{
            width: 34, height: 34, borderRadius: 8,
            background: 'linear-gradient(135deg, var(--brand-500), var(--violet-500))',
            color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name={step === 1 ? 'briefcase' : 'sparkles'} size={17}/>
          </div>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 15, fontWeight: 700, letterSpacing: '-0.01em' }}>
              {step === 1 ? '채용공고 만들기 (Create Job Posting)' : 'AI 면접질문 생성 결과 (AI-generated Questions)'}
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--fg-3)', marginTop: 2 }}>
              {step === 1
                ? '공고를 등록하면 이 JD 기반의 실전 면접질문이 자동 생성돼요.'
                : '검토 후 편집하거나 그대로 발행할 수 있어요. · Review & edit or publish as is.'}
            </div>
          </div>
          <div style={{ flex: 1 }}/>
          {/* Step indicator */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, fontWeight: 600, color: 'var(--fg-3)' }}>
            <StepDot n={1} active={step === 1} done={step > 1}/>
            <div style={{ width: 24, height: 1, background: 'var(--border-default)' }}/>
            <StepDot n={2} active={step === 2} done={false}/>
          </div>
          <button onClick={onClose} style={closeBtnStyle} aria-label="닫기"><Icon name="x" size={16}/></button>
        </div>

        {/* Body */}
        <div style={{ overflow: 'auto', flex: 1, padding: '20px 24px' }}>
          {step === 1 ? (
            <FormStep form={form} set={set} errors={errors} ind={ind} dept={dept}/>
          ) : (
            <QuestionsStep questions={questions} setQuestions={setQuestions} job={buildJob()}/>
          )}
        </div>

        {/* Footer */}
        <div style={{
          padding: '14px 24px', borderTop: '1px solid var(--border-subtle)',
          background: 'var(--neutral-25, #FAFBFC)',
          display: 'flex', alignItems: 'center', gap: 10,
        }}>
          {step === 2 && (
            <button onClick={() => setStep(1)} style={secondaryBtnStyle}>
              <Icon name="arrow-left" size={13}/> 이전 (Back)
            </button>
          )}
          <div style={{ flex: 1, fontSize: 11.5, color: 'var(--fg-3)' }}>
            {step === 1
              ? '* 표시는 필수 입력 · Required fields are marked *'
              : `${(questions || []).length}개 질문 · 편집 후 발행하세요.`}
          </div>
          {step === 1 ? (
            <>
              <button onClick={onClose} style={secondaryBtnStyle}>취소 (Cancel)</button>
              <button onClick={goNext} disabled={busy} style={{
                ...primaryBtnStyle, background: busy ? 'var(--brand-300)' : primaryBtnStyle.background, cursor: busy ? 'wait' : 'pointer',
              }}>
                {busy ? (<><Icon name="loader-2" size={13}/> 면접질문 생성 중… (Generating…)</>) : (<>다음: 면접질문 자동생성 <Icon name="sparkles" size={13}/></>)}
              </button>
            </>
          ) : (
            <button onClick={publish} style={{ ...primaryBtnStyle, background: 'var(--success-500, #17A34A)' }}>
              <Icon name="check" size={13}/> 공고 발행 (Publish)
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

/* ---------- Sub-components ---------- */

function FormStep({ form, set, errors, ind, dept }) {
  return (
    <div style={{ display: 'grid', gap: 18 }}>

      {/* Row: 포지션(한글) / Position(EN) */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <TextField label="포지션 (한글) *" hint="예: 시니어 프론트엔드 엔지니어"
          value={form.title_ko} onChange={v => set('title_ko', v)} error={errors.title_ko}/>
        <TextField label="Position (English) *" hint="e.g. Sr. Frontend Engineer"
          value={form.title_en} onChange={v => set('title_en', v)} error={errors.title_en}/>
      </div>

      {/* Row: 회사 / 레벨 */}
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 12 }}>
        <TextField label="회사 (Company)" value={form.company} onChange={v => set('company', v)}/>
        <SelectField label="레벨 (Level)" value={form.level} onChange={v => set('level', v)}
          options={[
            { v: 'Intern', l: '인턴 (Intern)' },
            { v: 'Jr',     l: '주니어 (Junior)' },
            { v: 'Mid',    l: '미드 (Mid)' },
            { v: 'Sr',     l: '시니어 (Senior)' },
            { v: 'Staff',  l: '스태프 (Staff)' },
            { v: 'Lead',   l: '리드 (Lead)' },
          ]}/>
      </div>

      {/* Row: 업종 / 부서 — 병행 표시 */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <SelectField label="업종 (Industry) *" value={form.industryId} onChange={v => set('industryId', v)}
          options={CIS.INDUSTRIES.map(x => ({ v: x.id, l: `${x.ko} (${x.en})` }))}/>
        <SelectField label="부서 (Department)" value={form.deptId} onChange={v => set('deptId', v)}
          options={CIS.DEPARTMENTS.map(x => ({ v: x.id, l: `${x.ko} (${x.en})` }))}/>
      </div>

      {/* Preview chip */}
      <div style={{
        padding: '10px 12px', background: 'var(--brand-50)',
        border: '1px solid var(--brand-100, #BFD3FF)', borderRadius: 8,
        display: 'inline-flex', alignItems: 'center', gap: 10, flexWrap: 'wrap',
        fontSize: 12.5, color: 'var(--brand-700)',
      }}>
        <Icon name="eye" size={13}/>
        <b>미리보기 · Preview:</b>
        <span>{form.title_ko || '(포지션)'} <span style={{opacity:.7}}>({form.title_en || 'Position'})</span></span>
        <span style={{ color: 'var(--fg-3)' }}>·</span>
        <span><b>{ind.ko}</b> <span style={{opacity:.7}}>({ind.en})</span></span>
        <span style={{ color: 'var(--fg-3)' }}>·</span>
        <span>{dept.ko} ({dept.en})</span>
      </div>

      {/* Row: 근무지 / 고용형태 */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
        <TextField label="근무지 (한글)" value={form.loc_ko} onChange={v => set('loc_ko', v)}/>
        <TextField label="Location (EN)" value={form.loc_en} onChange={v => set('loc_en', v)}/>
        <SelectField label="고용형태 (Employment)" value={form.empType} onChange={v => set('empType', v)}
          options={[
            { v: 'Full-time', l: '정규직 (Full-time)' },
            { v: 'Contract',  l: '계약직 (Contract)' },
            { v: 'Part-time', l: '파트타임 (Part-time)' },
            { v: 'Intern',    l: '인턴 (Intern)' },
          ]}/>
      </div>

      {/* Skills */}
      <TextField label="핵심 스킬 (Key Skills)" hint="쉼표로 구분 · Comma-separated. e.g. React, TypeScript, Web Performance"
        value={form.skills} onChange={v => set('skills', v)}/>

      {/* Long-form JD */}
      <TextArea label="주요 업무 (Responsibilities)" rows={4}
        placeholder="- Toss 결제 SDK의 신규 기능 설계·개발&#10;- 디자인 시스템 컴포넌트 오너십"
        value={form.responsibilities} onChange={v => set('responsibilities', v)}/>

      <TextArea label="자격 요건 (Requirements) *" rows={4}
        placeholder="- React·TypeScript로 프로덕션 제품을 5년 이상 만들어보신 분&#10;- Web Performance 지표 개선 경험"
        value={form.requirements} onChange={v => set('requirements', v)} error={errors.requirements}/>

      <TextArea label="우대 사항 (Preferred)" rows={3}
        placeholder="- 결제/금융 도메인 경험&#10;- 오픈소스 기여"
        value={form.preferred} onChange={v => set('preferred', v)}/>
    </div>
  );
}

function QuestionsStep({ questions, setQuestions, job }) {
  function editAt(i, patch) {
    setQuestions(qs => qs.map((q, idx) => idx === i ? { ...q, ...patch } : q));
  }
  function remove(i) {
    setQuestions(qs => qs.filter((_, idx) => idx !== i));
  }
  function add() {
    setQuestions(qs => [...qs, { type: '커스텀', q: '', hint: '' }]);
  }
  async function regen() {
    const qs = await CIS.generateInterviewQuestions(job);
    setQuestions(qs);
  }

  return (
    <div>
      <div style={{
        padding: '12px 14px', background: 'linear-gradient(135deg, #F3EFFF 0%, #F8F5FF 100%)',
        border: '1px solid var(--violet-100, #E4DAFF)', borderRadius: 10,
        marginBottom: 16, display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <div style={{
          width: 32, height: 32, borderRadius: 8,
          background: 'var(--violet-500, #7C55F2)', color: '#fff',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="sparkles" size={16}/>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--violet-700, #4E27B5)' }}>
            공고 기반 실전 면접질문이 준비됐어요 · Interview questions ready
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--fg-3)', marginTop: 2 }}>
            공고의 업종·부서·스킬을 반영한 {questions.length}개 질문. 편집 후 그대로 발행하면 지원자가 AI 모의면접에서 이 질문으로 연습할 수 있어요.
          </div>
        </div>
        <button onClick={regen} style={secondaryBtnStyle}>
          <Icon name="refresh-cw" size={13}/> 재생성 (Regenerate)
        </button>
      </div>

      <div style={{ display: 'grid', gap: 10 }}>
        {questions.map((q, i) => (
          <div key={i} style={{
            padding: 14, background: 'var(--neutral-0)',
            border: '1px solid var(--border-default)', borderRadius: 10,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
              <span style={{
                width: 22, height: 22, borderRadius: 999,
                background: 'var(--brand-500)', color: '#fff',
                fontSize: 11, fontWeight: 700, fontFamily: 'var(--font-latin)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              }}>Q{i+1}</span>
              <input value={q.type} onChange={e => editAt(i, { type: e.target.value })}
                style={{
                  padding: '3px 8px', border: 'none', background: 'var(--brand-50)',
                  color: 'var(--brand-700)', borderRadius: 999,
                  fontSize: 11, fontWeight: 600, outline: 'none',
                  fontFamily: 'var(--font-sans)', maxWidth: 140,
                }}/>
              <div style={{ flex: 1 }}/>
              <button onClick={() => remove(i)} style={{
                background: 'transparent', border: 'none', cursor: 'pointer',
                color: 'var(--fg-3)', padding: 4,
              }} title="삭제 (Remove)"><Icon name="trash-2" size={13}/></button>
            </div>
            <textarea value={q.q} onChange={e => editAt(i, { q: e.target.value })}
              rows={2}
              style={{
                width: '100%', padding: '8px 10px',
                border: '1px solid var(--border-subtle)', borderRadius: 6,
                fontSize: 13.5, lineHeight: 1.5, fontFamily: 'var(--font-sans)',
                outline: 'none', resize: 'vertical', color: 'var(--fg-1)', boxSizing: 'border-box',
              }}/>
            <input value={q.hint || ''} onChange={e => editAt(i, { hint: e.target.value })}
              placeholder="답변 가이드 (Hint) · 예: STAR 구조, 지표 포함"
              style={{
                marginTop: 6, width: '100%', padding: '6px 10px',
                border: '1px solid var(--border-subtle)', borderRadius: 6,
                fontSize: 12, color: 'var(--fg-2)', fontFamily: 'var(--font-sans)',
                outline: 'none', boxSizing: 'border-box',
              }}/>
          </div>
        ))}
      </div>

      <button onClick={add} style={{
        marginTop: 12, width: '100%', padding: '10px',
        background: 'transparent', border: '1px dashed var(--border-strong)',
        borderRadius: 8, fontSize: 12.5, fontWeight: 500, color: 'var(--fg-2)',
        cursor: 'pointer', fontFamily: 'var(--font-sans)',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
      }}>
        <Icon name="plus" size={13}/> 질문 추가 (Add question)
      </button>
    </div>
  );
}

/* ---------- Field atoms ---------- */
function TextField({ label, hint, value, onChange, error }) {
  return (
    <label style={{ display: 'block' }}>
      <FieldLabel label={label} hint={hint}/>
      <input value={value} onChange={e => onChange(e.target.value)}
        style={{ ...fieldInputStyle, borderColor: error ? 'var(--danger-500, #DC2E2E)' : 'var(--border-default)' }}/>
      {error && <div style={fieldErrorStyle}>{error}</div>}
    </label>
  );
}
function TextArea({ label, hint, rows, value, onChange, placeholder, error }) {
  return (
    <label style={{ display: 'block' }}>
      <FieldLabel label={label} hint={hint}/>
      <textarea value={value} onChange={e => onChange(e.target.value)} rows={rows || 3}
        placeholder={placeholder}
        style={{
          ...fieldInputStyle, resize: 'vertical', lineHeight: 1.55,
          borderColor: error ? 'var(--danger-500, #DC2E2E)' : 'var(--border-default)',
          fontFamily: 'var(--font-sans)',
        }}/>
      {error && <div style={fieldErrorStyle}>{error}</div>}
    </label>
  );
}
function SelectField({ label, value, onChange, options }) {
  return (
    <label style={{ display: 'block' }}>
      <FieldLabel label={label}/>
      <select value={value} onChange={e => onChange(e.target.value)} style={{
        ...fieldInputStyle,
        appearance: 'none',
        backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%236B7383' stroke-width='2'><path d='M6 9l6 6 6-6'/></svg>\")",
        backgroundRepeat: 'no-repeat',
        backgroundPosition: 'right 10px center',
        paddingRight: 32,
      }}>
        {options.map(o => <option key={o.v} value={o.v}>{o.l}</option>)}
      </select>
    </label>
  );
}
function FieldLabel({ label, hint }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
      marginBottom: 6,
    }}>
      <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--fg-2)' }}>{label}</span>
      {hint && <span style={{ fontSize: 11, color: 'var(--fg-3)' }}>{hint}</span>}
    </div>
  );
}
function StepDot({ n, active, done }) {
  const bg = done ? 'var(--success-500, #17A34A)' : active ? 'var(--brand-500)' : 'var(--neutral-100)';
  const fg = done || active ? '#fff' : 'var(--fg-3)';
  return (
    <span style={{
      width: 22, height: 22, borderRadius: 999,
      background: bg, color: fg,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontSize: 11, fontWeight: 700, fontFamily: 'var(--font-latin)',
    }}>{done ? '✓' : n}</span>
  );
}

/* ---------- Shared styles ---------- */
const backdropStyle = {
  position: 'fixed', inset: 0, background: 'rgba(6, 19, 63, 0.5)',
  backdropFilter: 'blur(4px)',
  display: 'flex', justifyContent: 'center', alignItems: 'center',
  padding: 24, zIndex: 100, animation: 'fadein 160ms ease-out',
};
const modalStyle = {
  width: '100%', maxWidth: 720, maxHeight: 'calc(100vh - 48px)',
  background: 'var(--neutral-0)', borderRadius: 16,
  boxShadow: 'var(--shadow-xl, 0 20px 60px rgba(6, 19, 63, 0.28))',
  display: 'flex', flexDirection: 'column', overflow: 'hidden',
};
const closeBtnStyle = {
  width: 32, height: 32, borderRadius: 8,
  background: 'transparent', border: 'none', cursor: 'pointer',
  color: 'var(--fg-2)',
  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
};
const fieldInputStyle = {
  width: '100%', padding: '10px 12px',
  border: '1px solid var(--border-default)', borderRadius: 8,
  fontSize: 13, fontFamily: 'var(--font-sans)', outline: 'none',
  background: 'var(--neutral-0)', color: 'var(--fg-1)', boxSizing: 'border-box',
};
const fieldErrorStyle = {
  marginTop: 4, fontSize: 11.5, color: 'var(--danger-500, #DC2E2E)',
};
const primaryBtnStyle = {
  padding: '9px 16px', background: 'var(--brand-500)', color: '#fff',
  border: 'none', borderRadius: 8, cursor: 'pointer',
  fontSize: 13, fontWeight: 700, fontFamily: 'var(--font-sans)',
  display: 'inline-flex', alignItems: 'center', gap: 6,
};
const secondaryBtnStyle = {
  padding: '8px 14px', background: 'var(--neutral-0)',
  border: '1px solid var(--border-strong)', borderRadius: 8, cursor: 'pointer',
  fontSize: 12.5, fontWeight: 600, fontFamily: 'var(--font-sans)',
  color: 'var(--fg-1)',
  display: 'inline-flex', alignItems: 'center', gap: 6,
};

window.JobPostingForm = JobPostingForm;
