/* ============================================================
   Modals — 기안하기 / 결재 / 재요청 / 최종본 업로드
   ============================================================ */
const { useState } = React;

function ModalShell({ title, onClose, children, foot, width }) {
  return (
    <div className="scrim" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" style={width ? { width } : null}>
        <div className="modal__head">
          <div className="modal__title">{title}</div>
          <button className="modal__x" onClick={onClose}><window.Icon name="x" size={20} /></button>
        </div>
        <div className="modal__body">{children}</div>
        <div className="modal__foot">{foot}</div>
      </div>
    </div>
  );
}

// ---------------- 기안하기 ----------------
function DraftModal({ onClose, onSubmit }) {
  const [title, setTitle] = useState("KODEX 반도체레버리지 리플렛에 대한 기획에 대한 기안");
  const [files, setFiles] = useState(["KODEX 반도체레버리지 상품 리플렛 기획.pptx"]);
  const [line, setLine] = useState(["pjh", "kms"]);
  const pool = ["pjh", "kms", "hgd"].filter((id) => !line.includes(id));

  return (
    <ModalShell title="기안하기" onClose={onClose}
      foot={<>
        <button className="btn btn--ghost" onClick={onClose}>취소</button>
        <button className="btn btn--dark" disabled={!title || line.length === 0}
          onClick={() => onSubmit({ title, files, line })}>기안하기</button>
      </>}>
      <div className="field">
        <div className="field__label">제목</div>
        <input className="input" value={title} onChange={(e) => setTitle(e.target.value)} />
      </div>

      <div className="field">
        <div className="field__label">파일</div>
        {files.map((f, i) => (
          <div key={i} style={{ marginBottom: 8 }}><window.FileChip name={f} /></div>
        ))}
        <button className="aprow" style={{ width: "100%", justifyContent: "center", color: "var(--text-3)", cursor: "pointer" }}
          onClick={() => setFiles([...files, "반도체 레버리지 상품 보조자료.pdf"])}>
          <window.Icon name="plus" size={18} />
        </button>
      </div>

      <div className="field">
        <div className="field__label">결재라인 <span style={{ color: "var(--text-4)", fontWeight: 500 }}>· 위에서부터 순차 결재됩니다</span></div>
        {line.map((id, i) => {
          const u = window.USERS[id];
          return (
            <div className="aprow" key={id}>
              <span className="aprow__grip"><window.Icon name="grip" size={16} /></span>
              <span className="aprow__seq">{i + 1}</span>
              <div>
                <div className="aprow__name">{u.name}</div>
                <div className="aprow__team">{u.team} · {u.role}</div>
              </div>
              <button className="aprow__x" onClick={() => setLine(line.filter((x) => x !== id))}>
                <window.Icon name="x" size={16} />
              </button>
            </div>
          );
        })}
        {pool.length > 0 && (
          <button className="aprow" style={{ width: "100%", justifyContent: "center", color: "var(--text-3)", cursor: "pointer", marginTop: 9 }}
            onClick={() => setLine([...line, pool[0]])}>
            <window.Icon name="plus" size={18} /> <span style={{ marginLeft: 6, fontWeight: 600 }}>결재자 추가</span>
          </button>
        )}
      </div>
    </ModalShell>
  );
}

// ---------------- 결재 ----------------
function ApprovalModal({ phase, onClose, onSubmit }) {
  const isCompliance = phase.kind === "compliance";
  const [choice, setChoice] = useState(null); // 'approve' | 'reject'
  const [comment, setComment] = useState("");
  const [reviewNo, setReviewNo] = useState("");
  const user = window.USERS[phase.user];

  const needNo = isCompliance && choice === "approve";
  const canSubmit = choice && (choice === "reject" ? comment.trim() : (!needNo || reviewNo.trim()));

  return (
    <ModalShell title={`결재 · ${phase.label}`} onClose={onClose}
      foot={<>
        <button className="btn btn--ghost" onClick={onClose}>취소</button>
        <button className={`btn ${choice === "reject" ? "btn--danger" : "btn--dark"}`} disabled={!canSubmit}
          onClick={() => onSubmit({ choice, comment, reviewNo })}>
          {choice === "reject" ? "반려하기" : "결재 제출"}
        </button>
      </>}>
      <div className="docpreview" style={{ marginBottom: 18 }}>
        <span className="filechip__icon" style={{ width: 40, height: 40, fontSize: 15 }}>P</span>
        <div>
          <div className="t">{phase.docTitle || "KODEX 반도체레버리지 상품 리플렛 기획"}</div>
          <div className="d">기안자 이정훈 · 상품기획팀{phase.revisedFile ? " · 수정본 반영됨" : ""}</div>
        </div>
      </div>

      <div className="field">
        <div className="field__label">결재 구분</div>
        <div className="seg">
          <div className={`segopt ${choice === "approve" ? "sel" : ""}`} onClick={() => setChoice("approve")}>
            <span className="segopt__radio" />
            <div>
              <div className="segopt__t">{isCompliance ? "최종 승인 (심의 통과)" : "승인"}</div>
              <div className="segopt__d">{isCompliance ? "심의번호를 부여하고 다음 단계로 진행합니다." : "다음 결재자에게 결재가 넘어갑니다."}</div>
            </div>
          </div>
          <div className={`segopt danger ${choice === "reject" ? "sel" : ""}`} onClick={() => setChoice("reject")}>
            <span className="segopt__radio" />
            <div>
              <div className="segopt__t">피드백 (반려)</div>
              <div className="segopt__d">기안자에게 반려되어 수정 후 재요청을 받습니다.</div>
            </div>
          </div>
        </div>
      </div>

      {needNo && (
        <div className="field">
          <div className="field__label">심의번호 <span className="field__req">*</span></div>
          <input className="input" placeholder="예: 준법감시 제2026-광고-0531호" value={reviewNo}
            onChange={(e) => setReviewNo(e.target.value)} />
          <div style={{ fontSize: 12.5, color: "var(--text-3)", marginTop: 7, display: "flex", gap: 6 }}>
            <window.Icon name="info" size={14} /> 심의번호 없이는 최종 승인할 수 없습니다.
          </div>
        </div>
      )}

      <div className="field">
        <div className="field__label">{choice === "reject" ? "반려 사유" : "의견"} {choice === "reject" && <span className="field__req">*</span>}</div>
        <textarea className="textarea" placeholder={choice === "reject" ? "수정이 필요한 내용을 적어주세요." : "결재 의견을 남겨주세요. (선택)"}
          value={comment} onChange={(e) => setComment(e.target.value)} />
      </div>
    </ModalShell>
  );
}

// ---------------- 재요청 ----------------
function RedoModal({ phase, onClose, onSubmit }) {
  const [file, setFile] = useState("KODEX 반도체레버리지 상품 리플렛 기획_1차 수정_20260526.pptx");
  const [comment, setComment] = useState("");
  return (
    <ModalShell title="수정본 업로드 후 재요청" onClose={onClose}
      foot={<>
        <button className="btn btn--ghost" onClick={onClose}>취소</button>
        <button className="btn btn--dark" disabled={!file}
          onClick={() => onSubmit({ file, comment })}>재요청하기</button>
      </>}>
      <div className="pcard__note reject" style={{ marginTop: 0, marginBottom: 18 }}>
        <b>{window.USERS[phase.user].name}</b> 결재자의 반려 사유 · {phase.rejectNote}
      </div>
      <div className="field">
        <div className="field__label">수정본 파일</div>
        <window.FileChip name={file} />
        <button className="aprow" style={{ width: "100%", justifyContent: "center", color: "var(--text-3)", cursor: "pointer", marginTop: 9 }}
          onClick={() => setFile("KODEX 반도체레버리지 상품 리플렛 기획_2차 수정.pptx")}>
          <window.Icon name="upload" size={16} /> <span style={{ marginLeft: 6, fontWeight: 600 }}>다른 파일로 교체</span>
        </button>
      </div>
      <div className="field">
        <div className="field__label">반영 내용</div>
        <textarea className="textarea" placeholder="피드백을 어떻게 반영했는지 적어주세요."
          value={comment} onChange={(e) => setComment(e.target.value)} />
      </div>
    </ModalShell>
  );
}

// ---------------- 최종본 업로드 ----------------
function FinalUploadModal({ reviewNo, onClose, onSubmit }) {
  const [file, setFile] = useState("KODEX 반도체레버리지 상품 리플렛_최종_20260601.pptx");
  return (
    <ModalShell title="최종본 업로드" onClose={onClose}
      foot={<>
        <button className="btn btn--ghost" onClick={onClose}>취소</button>
        <button className="btn btn--primary" disabled={!file}
          onClick={() => onSubmit({ file })}>업로드하고 종결</button>
      </>}>
      <div className="field">
        <div className="field__label">심의번호 (자동 반영)</div>
        <div className="docpreview" style={{ alignItems: "center" }}>
          <span style={{ width: 36, height: 36, borderRadius: 9, background: "var(--success-weak)", display: "grid", placeItems: "center" }}>
            <window.Icon name="shield" size={18} color="var(--success)" />
          </span>
          <div><div className="t" style={{ letterSpacing: ".01em" }}>{reviewNo}</div>
          <div className="d">컴플라이언스 심의에서 부여된 번호가 최종본에 반영됩니다.</div></div>
        </div>
      </div>
      <div className="field">
        <div className="field__label">최종 산출물 파일</div>
        <window.FileChip name={file} />
        <button className="aprow" style={{ width: "100%", justifyContent: "center", color: "var(--text-3)", cursor: "pointer", marginTop: 9 }}
          onClick={() => setFile("KODEX 반도체레버리지 상품 리플렛_최종본_v2.pptx")}>
          <window.Icon name="upload" size={16} /> <span style={{ marginLeft: 6, fontWeight: 600 }}>다른 파일로 교체</span>
        </button>
      </div>
      <div className="hint" style={{ margin: "4px 0 6px" }}>
        <span className="ic"><window.Icon name="info" size={16} /></span>
        <span>업로드가 완료되면 이 채널의 진행 현황은 <b>종결</b>되고, 심의번호와 최종 산출물이 보관됩니다.</span>
      </div>
    </ModalShell>
  );
}

Object.assign(window, { ModalShell, DraftModal, ApprovalModal, RedoModal, FinalUploadModal });
