// GlobalSupportWave — 사이트 전반에 흐르는 응원 물결
// Hero/About/Vision 등 모든 섹션 뒤로 떠다니는 인터랙티브 백드롭
// • 작은 응원 메시지 칩들이 사이트 좌→우로 천천히 흘러감 (CSS keyframes)
// • 클릭/탭 시 ❤👍👏 이모지 폭죽
// • 마우스 hover 시 일시정지
// • prefers-reduced-motion 시 비활성

// 메시지 풀 — 실제 SW_SEED를 활용하되, 추가로 짧은 응원구 풀
const GW_PHRASES = [
  "곡성에서 시작된 변화, 통합특별시에서 이어가 주세요.",
  "현장의 목소리가 정책이 되는 모습, 처음 봅니다.",
  "근자열 원자래 — 가까운 곳부터 기뻐하게.",
  "AI 진학 상담, 정말 절실했습니다.",
  "민주주의 교육, 광주에서 시작된 약속을 잊지 않습니다.",
  "아이들이 행복한 학교를 기대합니다.",
  "학생교육수당, 전국이 따라갑니다.",
  "통합도 착착, 교육도 착착.",
  "K-교육특별시, 함께 만들어 갑니다.",
  "한 명도 놓치지 않는 책임교육 응원합니다.",
  "교사가 자랑스러운 학교, 가능합니다.",
  "전남광주 교육의 새로운 100년.",
];

const GW_REGIONS = [
  "곡성", "목포", "여수", "순천", "광주 동구", "광주 광산", "고흥", "장흥", "해남", "보성", "나주", "담양",
];

const GW_NICKS = [
  "전남교육지기", "곡성학부모", "광산구 교사", "여수 시민", "고3 자녀 엄마", "5·18을 기억",
  "K-EDU FAN", "교육의 길", "내일을 응원", "초록의 봄",
];

const GW_EMOJIS = ["❤️", "👍", "👏", "🌱", "✨"];

// 한 번에 떠다니는 칩 개수
const GW_CHIP_COUNT = 8;

function GlobalSupportWave() {
  const [reduced, setReduced] = React.useState(false);
  // 정치/공공 톤 유지를 위해 기본 OFF. 캠페인 모드(이벤트/행사)에서만 ON.
  // 토글: window.__KDJ_CONFIG__.globalWaveEnabled = true (config.js로 주입) 또는
  //       관리자 콘솔 > 설정 > 글로벌 웨이브 (Step 7).
  const initialEnabled = (typeof window !== "undefined"
    && window.__KDJ_CONFIG__
    && window.__KDJ_CONFIG__.globalWaveEnabled === true);
  const [enabled, setEnabled] = React.useState(initialEnabled);
  const [bursts, setBursts] = React.useState([]); // 클릭 폭죽
  const [chips, setChips] = React.useState(() => generateChips(GW_CHIP_COUNT));

  React.useEffect(() => {
    const mq = window.matchMedia("(prefers-reduced-motion: reduce)");
    const upd = () => setReduced(mq.matches);
    upd();
    mq.addEventListener?.("change", upd);
    return () => mq.removeEventListener?.("change", upd);
  }, []);

  // 12초마다 일부 chips 재생성 (계속 새로운 응원이 흐르도록)
  React.useEffect(() => {
    if (reduced || !enabled) return;
    const t = setInterval(() => {
      setChips((cur) => {
        const next = [...cur];
        const idx = Math.floor(Math.random() * next.length);
        next[idx] = makeChip(idx);
        return next;
      });
    }, 4500);
    return () => clearInterval(t);
  }, [reduced, enabled]);

  // 포인터/자동 폭죽. 실제 액션은 방해하지 않고 배경 반응만 만든다.
  const pushBurst = (x, y) => {
    if (reduced || !enabled) return;
    const newBursts = [];
    for (let i = 0; i < 6; i++) {
      newBursts.push({
        id: "b-" + Math.random().toString(36).slice(2),
        emoji: GW_EMOJIS[Math.floor(Math.random() * GW_EMOJIS.length)],
        x, y,
        dx: (Math.random() - 0.5) * 200,
        dy: -(120 + Math.random() * 100),
        rot: (Math.random() - 0.5) * 360,
        size: 22 + Math.random() * 16,
      });
    }
    setBursts((cur) => [...cur, ...newBursts]);
    setTimeout(() => {
      setBursts((cur) => cur.filter((b) => !newBursts.find((n) => n.id === b.id)));
    }, 1500);
  };

  // 글로벌 포인터 리스너 (단, 인터랙티브 element는 제외)
  React.useEffect(() => {
    if (reduced || !enabled) return;
    const onPointerDown = (e) => {
      const t = e.target;
      // 버튼/링크/input/textarea/select 클릭은 무시 (사이트 인터랙션 방해 방지)
      if (t.closest("button, a, input, textarea, select, label, [data-no-burst]")) return;
      pushBurst(e.clientX, e.clientY);
    };
    window.addEventListener("pointerdown", onPointerDown, { passive: true });
    return () => window.removeEventListener("pointerdown", onPointerDown);
  }, [reduced, enabled]);

  // 손대지 않아도 배경이 아주 약하게 반응. globalWaveEnabled=true일 때만 동작.
  React.useEffect(() => {
    if (reduced || !enabled) return;
    let stop = false;
    let t;
    const tick = () => {
      if (stop) return;
      if (!document.hidden) {
        pushBurst(window.innerWidth * (0.18 + Math.random() * 0.64), window.innerHeight * (0.22 + Math.random() * 0.5));
      }
      t = window.setTimeout(tick, 9000 + Math.random() * 6000);
    };
    t = window.setTimeout(tick, 2500);
    return () => { stop = true; window.clearTimeout(t); };
  }, [reduced, enabled]);

  if (reduced || !enabled) return null;

  return (
    <div className="gw-layer" aria-hidden="true">
      {/* Floating chips */}
      <div className="gw-chips">
        {chips.map((c) => (
          <span
            key={c.id}
            className="gw-chip"
            style={{
              top: `${c.top}%`,
              animationDuration: `${c.duration}s`,
              animationDelay: `${c.delay}s`,
              opacity: c.opacity,
              fontSize: `${c.size}px`,
            }}
          >
            <span className="gw-chip-emoji">{c.emoji}</span>
            <span className="gw-chip-text">"{c.text}"</span>
            <span className="gw-chip-meta">— {c.nick} · {c.region}</span>
          </span>
        ))}
      </div>

      {/* Click bursts */}
      <div className="gw-bursts">
        {bursts.map((b) => (
          <span
            key={b.id}
            className="gw-burst"
            style={{
              left: b.x + "px",
              top: b.y + "px",
              fontSize: b.size + "px",
              "--dx": b.dx + "px",
              "--dy": b.dy + "px",
              "--rot": b.rot + "deg",
            }}
          >
            {b.emoji}
          </span>
        ))}
      </div>
    </div>
  );
}

function generateChips(n) {
  return Array.from({ length: n }).map((_, i) => makeChip(i));
}

function makeChip(i) {
  const text = GW_PHRASES[Math.floor(Math.random() * GW_PHRASES.length)];
  const nick = GW_NICKS[Math.floor(Math.random() * GW_NICKS.length)];
  const region = GW_REGIONS[Math.floor(Math.random() * GW_REGIONS.length)];
  const emoji = GW_EMOJIS[Math.floor(Math.random() * GW_EMOJIS.length)];
  return {
    id: "c-" + i + "-" + Math.random().toString(36).slice(2, 6),
    text, nick, region, emoji,
    top: 5 + Math.random() * 88,                  // %
    duration: 28 + Math.random() * 22,             // s — 천천히
    delay: -Math.random() * 30,                    // 음수 delay → 미리 진행된 상태로 시작
    opacity: 0.18 + Math.random() * 0.18,
    size: 11 + Math.random() * 3,
  };
}

Object.assign(window, { GlobalSupportWave });
