/* 온보딩 단계 — 인라인 익스플로러 (좌: 7개 카드 / 우: 상세) */
const { CrewBlock: JECrewBlock } = window.MISOComponents;

function JECheckIcon() {
  return (
    <svg width="11" height="11" viewBox="0 0 12 12" fill="none">
      <path d="M2.5 6.2 L5 8.5 L9.5 3.5" stroke="white" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function JEExternalIcon() {
  return (
    <svg className="check-ext-icon" width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true">
      <path d="M5 2.5H3.2C2.54 2.5 2 3.04 2 3.7v5.1C2 9.46 2.54 10 3.2 10h5.1c.66 0 1.2-.54 1.2-1.2V7.5M7 2h3v3M5.5 6.5L10 2" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function JEChecklistItem({ item, sub = false, checked, onToggle }) {
  const text = typeof item === "string" ? item : item.text;
  const href = typeof item === "object" ? item.href : null;
  const note = typeof item === "object" ? item.note : null;

  return (
    <div className={"checklist-item" + (sub ? " checklist-sub" : "") + (checked ? " is-checked" : "")}>
      <button
        type="button"
        className={"check-box" + (checked ? " checked" : "")}
        onClick={onToggle}
        aria-pressed={checked}
        aria-label={checked ? `${text} 완료 취소` : `${text} 완료 표시`}
      >
        <JECheckIcon />
      </button>
      <div className="check-body">
        {href ? (
          <a
            className="check-text check-link"
            href={href}
            target="_blank"
            rel="noopener noreferrer"
          >
            <span>{text}</span>
            <JEExternalIcon />
            <span className="sr-only"> (새 탭에서 열림)</span>
          </a>
        ) : (
          <button type="button" className="check-text-btn" onClick={onToggle}>
            {text}
          </button>
        )}
        {note && <p className="check-note">{note}</p>}
      </div>
    </div>
  );
}

/* ---------- 좌측 카드 (한 줄 카드) ---------- */
function JECard({ step, active, onPick, index }) {
  return (
    <button
      className={"je-card" + (active ? " active" : "")}
      onClick={() => onPick(step.id)}
      style={{ "--hue": `var(--hue-${step.id})` }}
    >
      <div className="je-card-rail">
        <div className="je-card-num">{String(step.id + 1).padStart(2, "0")}</div>
        {index < STEPS.length - 1 && <div className="je-card-line" />}
      </div>
      <div className="je-card-body">
        <div className="je-card-eb">
          <span className="je-card-label">{step.label}</span>
          <span className="je-card-dot">·</span>
          <span className="je-card-short">{step.short}</span>
        </div>
        <div className="je-card-name">{step.name}</div>
      </div>
      <div className="je-card-chev" aria-hidden>
        <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
          <path d="M5 3 L9 7 L5 11" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </div>
    </button>
  );
}

/* ---------- 우측 상세 ---------- */
function JEDetail({ step, onPrev, onNext }) {
  const [checked, setChecked] = React.useState(new Set());

  React.useEffect(() => { setChecked(new Set()); }, [step?.id]);

  if (!step) return null;

  function toggle(key) {
    setChecked(prev => {
      const next = new Set(prev);
      if (next.has(key)) next.delete(key); else next.add(key);
      return next;
    });
  }

  const stripeColor = `var(--hue-${step.id})`;
  const totalItems = step.groups.reduce((sum, g) => {
    return sum + g.items.reduce((s, it) => s + 1 + (typeof it === "object" && it.subs ? it.subs.length : 0), 0);
  }, 0);
  const progress = checked.size / Math.max(totalItems, 1);

  const prevStep = STEPS[step.id - 1];
  const nextStep = STEPS[step.id + 1];

  return (
    <React.Fragment>
    <article className="je-detail" key={step.id}>
      <div className="je-detail-stripe" style={{ background: `linear-gradient(90deg, ${stripeColor}, var(--miso))` }} />

      <header className="je-detail-head">
        <div className="je-detail-eb-row">
          <div className="je-detail-num" style={{ background: `linear-gradient(135deg, ${stripeColor}, var(--miso))` }}>
            {String(step.id + 1).padStart(2, "0")}
          </div>
          <div className="je-detail-eb">
            {step.label} · {step.short}{step.week ? ` · ${step.week}` : ""}
          </div>
        </div>
        <h2 className="je-detail-title">{step.name}</h2>
        <p className="je-detail-desc">{step.desc}</p>

        {step.goals && (
          <div className="je-goals">
            {step.goals.map((g, i) => (
              <span key={i} className="je-goal-chip">✓ {g}</span>
            ))}
          </div>
        )}

        <div className="je-progress">
          <div className="je-progress-track">
            <div className="je-progress-fill" style={{ width: `${progress * 100}%` }} />
          </div>
          <div className="je-progress-text">{checked.size} / {totalItems}</div>
        </div>
      </header>

      <div className="je-detail-body">
        <section className="je-section">
          <div className="je-section-title">이 단계에서 만나게 될 사람</div>
          <JECrewBlock owners={step.owners} />
        </section>

        {step.tip && (
          <section className="je-section">
            <div className="je-section-title">PO 팁</div>
            <div className="je-tip">
              <div className="je-tip-mark">!</div>
              <div className="je-tip-text">{step.tip}</div>
            </div>
          </section>
        )}

        <section className="je-section">
          <div className="je-section-title">할 일 · 받게 될 것</div>
          {step.groups.map((g, gi) => (
            <div key={gi} className="checklist-group">
              <div className="checklist-group-title">
                <span>{g.title}</span>
                <span className="checklist-group-pill">{g.items.length} items</span>
              </div>
              <div className="checklist">
                {g.items.map((it, ii) => {
                  const key = `${gi}-${ii}`;
                  const hasSubs = typeof it === "object" && it.subs;
                  return (
                    <React.Fragment key={key}>
                      <JEChecklistItem item={it} checked={checked.has(key)} onToggle={() => toggle(key)} />
                      {hasSubs && it.subs.map((sub, si) => {
                        const subkey = `${key}-${si}`;
                        return (
                          <JEChecklistItem
                            key={subkey}
                            item={sub}
                            sub
                            checked={checked.has(subkey)}
                            onToggle={() => toggle(subkey)}
                          />
                        );
                      })}
                    </React.Fragment>
                  );
                })}
              </div>
            </div>
          ))}
        </section>

        <section className="je-section">
          <div className="je-section-title">완료 지표</div>
          <div className="done-list">
            {step.done.map((d, i) => (
              <div className="done-row" key={i}>
                <div className="done-num">0{i + 1}</div>
                <div className="done-text">{d}</div>
              </div>
            ))}
          </div>
        </section>

        {step.success && (
          <section className="je-section">
            <div className="je-section-title">성공 지표</div>
            <div className="done-list" style={{ background: "linear-gradient(180deg, #FCFBFE, #F4F7FB)", borderColor: "var(--ice-200)" }}>
              {step.success.map((d, i) => (
                <div className="done-row" key={i} style={{ borderColor: "var(--ice-200)" }}>
                  <div className="done-num" style={{ color: "var(--ink-700)" }}>★</div>
                  <div className="done-text">{d}</div>
                </div>
              ))}
            </div>
          </section>
        )}

      </div>
    </article>

    <div className="je-nav je-nav-floating">
      <button onClick={onPrev} disabled={!prevStep}>
        <span className="arrow">←</span>
        <span className="label-block">
          <span className="label-eb">이전</span>
          <span className="label-name">{prevStep ? prevStep.name : "처음 단계"}</span>
        </span>
      </button>
      <button onClick={onNext} disabled={!nextStep} className="next">
        <span className="label-block">
          <span className="label-eb">다음</span>
          <span className="label-name">{nextStep ? nextStep.name : "마지막 단계"}</span>
        </span>
        <span className="arrow">→</span>
      </button>
    </div>
    </React.Fragment>
  );
}



/* ---------- 메인 익스플로러 ---------- */
function JourneyExplorer({ initialId = 0 }) {
  const [activeId, setActiveIdRaw] = React.useState(initialId);
  const [isMobile, setIsMobile] = React.useState(() =>
    typeof window !== "undefined" && window.matchMedia("(max-width: 880px)").matches
  );
  const [mobileOpen, setMobileOpen] = React.useState(false);

  React.useEffect(() => {
    const mq = window.matchMedia("(max-width: 880px)");
    const handler = (e) => setIsMobile(e.matches);
    if (mq.addEventListener) mq.addEventListener("change", handler);
    else mq.addListener(handler);
    return () => {
      if (mq.removeEventListener) mq.removeEventListener("change", handler);
      else mq.removeListener(handler);
    };
  }, []);

  const setActiveId = React.useCallback((id) => {
    setActiveIdRaw(id);
    setMobileOpen(false);
    // 페이지 최상단으로 이동 — 실제 스크롤 컨테이너(.main 또는 window) 찾아서 스크롤
    const targets = [
      document.querySelector(".main"),
      document.scrollingElement,
      document.documentElement,
      document.body,
      window,
    ];
    for (const t of targets) {
      if (!t) continue;
      try {
        if (t === window) {
          t.scrollTo({ top: 0, left: 0, behavior: "smooth" });
        } else if (t.scrollTo) {
          t.scrollTo({ top: 0, left: 0, behavior: "smooth" });
          t.scrollTop = 0;
        } else {
          t.scrollTop = 0;
        }
      } catch (e) {}
    }
  }, []);
  React.useEffect(() => {
    function onKey(e) {
      if (e.target.matches("input, textarea")) return;
      if (e.key === "Escape" && mobileOpen) {
        setMobileOpen(false);
        return;
      }
      if (e.key === "ArrowDown" || e.key === "ArrowRight") {
        if (activeId < STEPS.length - 1) setActiveId(activeId + 1);
      } else if (e.key === "ArrowUp" || e.key === "ArrowLeft") {
        if (activeId > 0) setActiveId(activeId - 1);
      }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [activeId, mobileOpen, setActiveId]);

  React.useEffect(() => {
    const newHash = `#step=${activeId}`;
    if (window.location.hash !== newHash) {
      history.replaceState(null, "", newHash);
    }
  }, [activeId]);

  React.useEffect(() => {
    document.body.classList.toggle("je-sidebar-mobile", isMobile);
    document.body.classList.toggle("je-sidebar-mobile-open", isMobile && mobileOpen);
    document.body.classList.add("je-sidebar-active");
    return () => {
      document.body.classList.remove("je-sidebar-mobile");
      document.body.classList.remove("je-sidebar-mobile-open");
      document.body.classList.remove("je-sidebar-active");
    };
  }, [isMobile, mobileOpen]);

  const active = STEPS[activeId];
  const wrapClass =
    "je-section-wrap" +
    (isMobile ? " mobile" : "") +
    (isMobile && mobileOpen ? " mobile-open" : "");
  const sidebarClass =
    "je-sidebar" +
    (isMobile ? " mobile" : "") +
    (isMobile && mobileOpen ? " mobile-open" : "");

  return (
    <section className={wrapClass} id="journey">
      <aside className={sidebarClass} aria-label="온보딩 단계 단계 목록" aria-hidden={isMobile && !mobileOpen}>
        <nav className="je-list">
          {STEPS.map((s, i) => (
            <JECard
              key={s.id}
              step={s}
              active={s.id === activeId}
              onPick={setActiveId}
              index={i}
            />
          ))}
        </nav>
      </aside>

      {isMobile && mobileOpen && (
        <button
          className="je-backdrop"
          onClick={() => setMobileOpen(false)}
          aria-label="메뉴 닫기"
        />
      )}

      {isMobile && (
        <button
          className={"je-mobile-fab" + (mobileOpen ? " hidden" : "")}
          onClick={() => setMobileOpen(true)}
          aria-label="단계 메뉴 열기"
          aria-expanded={mobileOpen}
          title="단계 메뉴"
        >
          <svg width="18" height="18" viewBox="0 0 18 18" fill="none" aria-hidden>
            <path d="M3 5 H15 M3 9 H15 M3 13 H15" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
          </svg>
        </button>
      )}

      <div className="je-main">
        <div className="je-detail-wrap">
          <JEDetail
            step={active}
            onPrev={activeId > 0 ? () => setActiveId(activeId - 1) : null}
            onNext={activeId < STEPS.length - 1 ? () => setActiveId(activeId + 1) : null}
          />
        </div>
      </div>
    </section>
  );
}

window.JourneyExplorer = JourneyExplorer;
window.JEDetail = JEDetail;
