/* ============================================================
   shared.jsx — 공통 컴포넌트
   ============================================================ */
const { useState, useRef, useEffect } = React;

/* ---- 변동유형 색 뱃지 ---- */
function TypeBadge({ typeId, size, showHint }) {
  const t = window.typeById(typeId);
  if (!t) return null;
  return (
    <span className={`badge ${t.cls} ${size === "lg" ? "badge-lg" : ""}`}>
      <span className="badge-no">{t.id}</span>
      {t.label}{showHint ? ` · ${t.hint}` : ""}
    </span>);

}

/* ---- 진행 게이지 ○/5 ---- */
function Gauge({ done, total, dark }) {
  total = total || 5;
  return (
    <div className="gauge">
      <div className="gauge-track">
        {Array.from({ length: total }, (_, i) =>
        <span key={i} className={`gauge-dot ${i < done ? "on" : ""}`}
        style={dark && i < done ? { background: "#fff" } : null} />
        )}
      </div>
      <span className="gauge-label" style={dark ? { color: "rgba(255,255,255,.65)" } : null}>
        <b style={dark ? { color: "#fff" } : null}>{done}</b>/{total} 곳 탐험
      </span>
    </div>);

}

/* ---- 모둠 칩 ---- */
function GroupChip({ group, big }) {
  if (!group) return null;
  return (
    <span className="gchip" style={big ? { fontSize: 15, padding: "7px 16px 7px 7px" } : null}>
      <span className="dot" style={{ background: group.color, width: big ? 18 : 14, height: big ? 18 : 14 }} />
      {group.label}
    </span>);

}

/* ---- 토글 섹션 ---- */
function Toggle({ icon, title, children, defaultOpen, accent }) {
  const [open, setOpen] = useState(!!defaultOpen);
  return (
    <div className={`toggle ${open ? "open" : ""}`} style={accent ? { borderColor: "var(--c)" } : null}>
      <button className="toggle-head" onClick={() => setOpen(!open)}
      style={accent ? { background: "var(--c-soft)", color: "var(--c-ink)" } : null}>
        {icon ? <span style={{ fontSize: 16 }}>{icon}</span> : null}
        {title}
        <span className="chev">▾</span>
      </button>
      <div className="toggle-body">
        <div style={{ paddingTop: 12, fontSize: 14, color: "var(--slate)", lineHeight: 1.6 }}>{children}</div>
      </div>
    </div>);

}

/* ---- 출처 캡션 ---- */
function Source({ children }) {
  return <p className="src">출처: {children}</p>;
}

/* ============================================================
   목업 지도 — 일러스트풍 베이스맵 + 핀 오버레이
   ============================================================ */
function BaseMap() {
  // 구로·영등포 권역을 단순화한 일러스트 지도. 실제 지도가 아닌 목업.
  return (
    <svg className="basemap" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid slice"
    style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
      <defs>
        <linearGradient id="land" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="#eceae3" />
          <stop offset="1" stopColor="#e4e1d8" />
        </linearGradient>
        <pattern id="blocks" width="9" height="9" patternUnits="userSpaceOnUse" patternTransform="rotate(2)">
          <rect width="9" height="9" fill="none" />
          <path d="M0 9 H9 M9 0 V9" stroke="#d7d3c8" strokeWidth="0.5" />
        </pattern>
      </defs>

      {/* 육지 */}
      <rect width="100" height="100" fill="url(#land)" />
      <rect width="100" height="100" fill="url(#blocks)" />

      {/* 안양천 (상단 가로 — 도림천이 북쪽에서 여기로 합류) */}
      <path d="M-5 14 C 20 8, 45 18, 70 9 S 105 4, 105 4 L 105 -5 L -5 -5 Z" fill="#bcd4dc" />
      <path d="M-5 14 C 20 8, 45 18, 70 9 S 105 4, 105 4" fill="none" stroke="#a7c4cd" strokeWidth="0.6" />
      <text x="50" y="6.5" fontSize="2.6" fill="#6f93a0" fontWeight="700" textAnchor="middle" letterSpacing="0.4">안양천</text>

      {/* 도림천 (구로/영등포 경계, 세로 — 북쪽에서 안양천에 합류) */}
      <path d="M50 14 C 47 35, 53 55, 48 78 S 50 100, 50 100" fill="none" stroke="#bcd4dc" strokeWidth="3.2" strokeLinecap="round" />
      <path d="M50 14 C 47 35, 53 55, 48 78 S 50 100, 50 100" fill="none" stroke="#a7c4cd" strokeWidth="0.5" />
      <text x="53.5" y="48" fontSize="2.2" fill="#6f93a0" fontWeight="700" textAnchor="middle" letterSpacing="0.3" transform="rotate(88 53.5 48)">도림천</text>

      {/* 주요 도로 */}
      <g stroke="#cdc9bd" strokeWidth="1.1" fill="none" strokeLinecap="round">
        <path d="M2 30 H98" />
        <path d="M2 62 H98" />
        <path d="M24 16 V96" />
        <path d="M76 16 V96" />
        <path d="M6 84 C 30 70, 60 76, 96 58" />
      </g>
      <g stroke="#dcd8cc" strokeWidth="0.55" fill="none">
        <path d="M2 46 H98" /><path d="M2 78 H98" />
        <path d="M38 16 V96" /><path d="M62 16 V96" /><path d="M12 16 V96" /><path d="M88 16 V96" />
      </g>

      {/* 철길 (항동철길 암시, 좌하단 점선) */}
      <path d="M4 60 C 10 70, 8 84, 18 92" fill="none" stroke="#9aa190" strokeWidth="0.9" strokeDasharray="1.4 1.4" />

      {/* 녹지 패치 (좌측) */}
      <path d="M6 50 C 12 46, 20 48, 22 56 C 24 66, 16 72, 9 70 C 3 68, 2 56, 6 50 Z" fill="#cdddb9" opacity="0.85" />

      {/* 구역 라벨 */}
      <text x="26" y="24" fontSize="3.1" fill="#9a958a" fontWeight="800" textAnchor="middle" letterSpacing="0.6">구로구</text>
      <text x="76" y="24" fontSize="3.1" fill="#9a958a" fontWeight="800" textAnchor="middle" letterSpacing="0.6">영등포구</text>
    </svg>);

}

/* 핀 마커 (지도 위 HTML 오버레이) */
function PinMarker({ pin, done, onClick, dim }) {
  const t = window.typeById(pin.typeId);
  return (
    <button
      className={`pin ${t.cls} ${done ? "done" : ""}`}
      style={{ left: `${pin.x}%`, top: `${pin.y}%`, opacity: dim ? 0.35 : 1 }}
      onClick={onClick}>
      
      <span className="pin-head">
        {done ?
        <span className="pin-check">✓</span> :
        <span className="pin-no">{t.id}</span>}
      </span>
      <span className="pin-label">{pin.name}</span>
    </button>);

}

/* 우리 학교 마커 (핀과 구분되는 별도 표시) */
function SchoolMarker({ compact }) {
  const s = window.SCHOOL;
  if (!s) return null;
  return (
    <div className={`school-marker ${compact ? "compact" : ""}`} style={{ left: `${s.x}%`, top: `${s.y}%` }}
    title={`${s.name} · ${s.addr}`}>
      <span className="school-pin">
        <svg viewBox="0 0 24 24" width="15" height="15" aria-hidden="true">
          <path d="M12 3 L21 8 L12 13 L3 8 Z" fill="#fff" />
          <path d="M6 10.5 V15 C6 16.6 8.7 18 12 18 C15.3 18 18 16.6 18 15 V10.5" fill="none" stroke="#fff" strokeWidth="1.8" />
          <line x1="21" y1="8" x2="21" y2="12.5" stroke="#fff" strokeWidth="1.8" strokeLinecap="round" />
        </svg>
      </span>
      {!compact ? <span className="school-label">{s.name}</span> : null}
    </div>);

}

Object.assign(window, { TypeBadge, Gauge, GroupChip, Toggle, Source, BaseMap, PinMarker, SchoolMarker });