/* ============================================================
   loading.jsx — 월하 공용 로딩 화면 컴포넌트
   <window.LoadingScreen variant="orbit|manse|moon" />
   - 4단계 메시지를 스스로 순환하며 진행바를 채운다
   - .main(앱바·탭바 사이) 안에 그대로 넣어 쓰면 됨
   ============================================================ */
(function () {
  const { useState, useEffect } = React;

  const STEPS = [
    { msg: "천간과 지지를 세우는 중", sub: "사주 네 기둥 四柱" },
    { msg: "오행의 기운을 살피는 중", sub: "木 火 土 金 水" },
    { msg: "대운의 흐름을 읽는 중",   sub: "10년 단위 큰 흐름" },
    { msg: "당신의 사주를 매듭짓는 중", sub: "거의 다 왔어요" },
  ];

  /* 오행 데이터 (각도·색·글자) */
  const ELEMENTS = [
    { han: "木", c: "#2FA36A", ang: "0deg" },
    { han: "火", c: "#EF6B5E", ang: "72deg" },
    { han: "土", c: "#D9A441", ang: "144deg" },
    { han: "金", c: "#8A97A3", ang: "216deg" },
    { han: "水", c: "#4E6FD6", ang: "288deg" },
  ];

  /* 만세력 네 기둥 (예시 간지) */
  const PILLARS = [
    { label: "年", stem: "甲", branch: "子", sk: "갑", bk: "자", hc: "#2FA36A" },
    { label: "月", stem: "丙", branch: "寅", sk: "병", bk: "인", hc: "#EF6B5E" },
    { label: "日", stem: "戊", branch: "午", sk: "무", bk: "오", hc: "#D9A441", day: true },
    { label: "時", stem: "庚", branch: "申", sk: "경", bk: "신", hc: "#8A97A3" },
  ];

  /* 별자리 점 */
  const STARS = [
    { ang: "8deg", s: "4px", d: "0s" },
    { ang: "66deg", s: "2.5px", d: "0.5s" },
    { ang: "128deg", s: "3.5px", d: "1s" },
    { ang: "192deg", s: "2.5px", d: "0.3s" },
    { ang: "250deg", s: "4px", d: "0.8s" },
    { ang: "312deg", s: "3px", d: "1.3s" },
  ];

  function OrbitStage() {
    return (
      <div className="wl-orbit">
        <div className="wl-orbit-glow"></div>
        <div className="wl-orbit-ring"></div>
        <div className="wl-orbit-ring inner"></div>
        <div className="wl-orbit-spin">
          {ELEMENTS.map((e, i) => (
            <div className="wl-arm" style={{ "--ang": e.ang }} key={i}>
              <div className="wl-deg" style={{ "--ang": e.ang }}>
                <div className="wl-elem-chip" style={{ "--ec": e.c, animationDelay: `0s, ${i * 0.9}s` }}>{e.han}</div>
              </div>
            </div>
          ))}
        </div>
        <div className="wl-orbit-core serif">月</div>
      </div>
    );
  }

  function ManseStage() {
    return (
      <div className="wl-manse">
        <div className="wl-pillars">
          {PILLARS.map((p, i) => (
            <div className={"wl-pillar" + (p.day ? " day" : "")} style={{ animationDelay: `${i * 0.32}s` }} key={i}>
              {p.day && <div className="wl-day-mark">日干</div>}
              <div className="wl-p-label">{p.label}</div>
              <div className="wl-p-cell">
                <div className="wl-p-han" style={{ "--hc": p.hc }}>{p.stem}</div>
                <div className="wl-p-ko">{p.sk}</div>
              </div>
              <div className="wl-p-cell">
                <div className="wl-p-han">{p.branch}</div>
                <div className="wl-p-ko">{p.bk}</div>
              </div>
            </div>
          ))}
        </div>
        <div className="wl-brush"><span></span></div>
      </div>
    );
  }

  function MoonStage() {
    return (
      <div className="wl-moonwrap">
        <div className="wl-constel">
          {STARS.map((s, i) => (
            <div className="wl-star" style={{ "--ang": s.ang, "--s": s.s, "--d": s.d }} key={i}></div>
          ))}
        </div>
        <div className="wl-halo"></div>
        <div className="wl-halo h2"></div>
        <div className="wl-halo h3"></div>
        <div className="wl-moon"></div>
      </div>
    );
  }

  const STAGES = { orbit: OrbitStage, manse: ManseStage, moon: MoonStage };

  /*
   * props
   *  variant   : "orbit" | "manse" | "moon"   (확정안: "orbit")
   *  step      : 0~3 — 실제 진행 단계를 넘기면 controlled 모드.
   *              생략하면 데모용으로 스스로 순환(loop).
   *  steps     : 단계 메시지 배열 override (기본 STEPS)
   *  showSteps : 하단 문구·진행바 표시 여부
   */
  window.LoadingScreen = function LoadingScreen({ variant = "orbit", step: stepProp, steps, showSteps = true, style }) {
    const SEQ = steps || STEPS;
    const controlled = typeof stepProp === "number";
    const [autoStep, setAutoStep] = useState(0);
    const Stage = STAGES[variant] || OrbitStage;

    useEffect(() => {
      if (controlled) return;
      const t = setInterval(() => setAutoStep((s) => (s + 1) % SEQ.length), 1500);
      return () => clearInterval(t);
    }, [controlled, SEQ.length]);

    const step = controlled ? Math.max(0, Math.min(SEQ.length - 1, stepProp)) : autoStep;
    const last = controlled && step >= SEQ.length - 1;
    const cur = SEQ[step];

    return (
      <div className={"wl-load" + (showSteps ? "" : " no-steps")} style={style}>
        <div className="wl-stage"><Stage /></div>
        <div className="wl-meta">
          <div className="wl-eyebrow">命理 · 만세력 분석</div>
          <div className="wl-msg" key={step}>{cur.msg}</div>
          <div className="wl-sub">{cur.sub}</div>
          <div className="wl-steps">
            {SEQ.map((_, i) => (
              <div className={"wl-seg" + (i < step ? " done" : i === step ? (last ? " done" : " active") : "")} key={i}></div>
            ))}
          </div>
          <div className="wl-count">{String(step + 1).padStart(2, "0")} / {String(SEQ.length).padStart(2, "0")} 단계</div>
        </div>
      </div>
    );
  };
})();
