// 영어문법학습 — 공용 컴포넌트
// 다른 .jsx 파일에서 사용할 수 있도록 window 전역에 등록

const { useEffect, useRef, useState, useMemo, useCallback } = React;

// ============================================================
// 아이콘 — 단순한 stroke SVG
// ============================================================
function Icon({ name, size = 18 }) {
  const stroke = "currentColor";
  const sw = 2;
  const common = {
    width: size, height: size, viewBox: "0 0 24 24", fill: "none",
    stroke, strokeWidth: sw, strokeLinecap: "round", strokeLinejoin: "round"
  };
  switch (name) {
    case "check": return <svg {...common}><polyline points="20 6 9 17 4 12" /></svg>;
    case "x": return <svg {...common}><path d="M18 6L6 18M6 6l12 12" /></svg>;
    case "arrow-left": return <svg {...common}><path d="M19 12H5M12 19l-7-7 7-7" /></svg>;
    case "arrow-right": return <svg {...common}><path d="M5 12h14M12 5l7 7-7 7" /></svg>;
    case "book": return <svg {...common}><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2zM22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/></svg>;
    case "flame": return <svg {...common}><path d="M12 2s4 4 4 8a4 4 0 0 1-8 0c0-1 .5-2 1-3-1 1-3 3-3 6a6 6 0 0 0 12 0c0-5-6-11-6-11z" /></svg>;
    case "trophy": return <svg {...common}><path d="M8 21h8M12 17v4M7 4h10v4a5 5 0 0 1-10 0V4zM4 4h3v3a3 3 0 0 1-3-3zM20 4h-3v3a3 3 0 0 0 3-3z" /></svg>;
    case "sparkles": return <svg {...common}><path d="M12 3l1.5 4.5L18 9l-4.5 1.5L12 15l-1.5-4.5L6 9l4.5-1.5zM19 14l.7 2.1L22 17l-2.3.9L19 20l-.7-2.1L16 17l2.3-.9zM5 14l.5 1.5L7 16l-1.5.5L5 18l-.5-1.5L3 16l1.5-.5z" fill="currentColor" stroke="none"/></svg>;
    case "settings": return <svg {...common}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>;
    case "plus": return <svg {...common}><path d="M12 5v14M5 12h14"/></svg>;
    case "edit": return <svg {...common}><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>;
    case "trash": return <svg {...common}><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>;
    case "log-out": return <svg {...common}><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9"/></svg>;
    case "lock": return <svg {...common}><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>;
    case "google": return <svg width={size} height={size} viewBox="0 0 24 24"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.07 5.07 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.27-4.74 3.27-8.1z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.99.67-2.26 1.06-3.71 1.06-2.86 0-5.29-1.93-6.15-4.53H2.18v2.84A11 11 0 0 0 12 23z"/><path fill="#FBBC05" d="M5.85 14.1A6.6 6.6 0 0 1 5.5 12c0-.73.13-1.44.35-2.1V7.06H2.18A11 11 0 0 0 1 12c0 1.77.43 3.45 1.18 4.94l3.67-2.84z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.07.56 4.21 1.65l3.15-3.15C17.45 2.1 14.97 1 12 1A11 11 0 0 0 2.18 7.06l3.67 2.84C6.71 7.3 9.14 5.38 12 5.38z"/></svg>;
    case "list": return <svg {...common}><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>;
    default: return null;
  }
}

// ============================================================
// 상단 바
// ============================================================
function TopBar({ user, onTitleClick, rightSlot, streak }) {
  return (
    <div className="topbar">
      <button className="topbar-brand" onClick={onTitleClick} style={{ background: "none", cursor: "pointer" }}>
        <span className="topbar-brand-mark">A</span>
        <span>영어문법 학습</span>
      </button>
      <div className="topbar-stats">
        {rightSlot}
      </div>
    </div>
  );
}

// ============================================================
// 컨페티 (챕터 클리어 시)
// ============================================================
function Confetti({ trigger, duration = 2400 }) {
  const [pieces, setPieces] = useState([]);

  useEffect(() => {
    if (!trigger) return;
    const colors = ["#6B9D80", "#C9A26B", "#5C8478", "#C77A6C", "#7CAE93", "#E0C896"];
    const newPieces = Array.from({ length: 60 }, (_, i) => ({
      id: Date.now() + "-" + i,
      left: Math.random() * 100,
      bg: colors[Math.floor(Math.random() * colors.length)],
      duration: 1.6 + Math.random() * 1.4,
      delay: Math.random() * 0.3,
      rotate: Math.random() * 360
    }));
    setPieces(newPieces);
    const t = setTimeout(() => setPieces([]), duration + 600);
    return () => clearTimeout(t);
  }, [trigger]);

  if (!pieces.length) return null;
  return (
    <div className="confetti-layer">
      {pieces.map((p) => (
        <div
          key={p.id}
          className="confetti-piece"
          style={{
            left: p.left + "%",
            background: p.bg,
            animationDuration: p.duration + "s",
            animationDelay: p.delay + "s",
            transform: `rotate(${p.rotate}deg)`
          }}
        />
      ))}
    </div>
  );
}

// ============================================================
// 진행도 바
// ============================================================
function ProgressBar({ value, max }) {
  const pct = Math.max(0, Math.min(100, (value / Math.max(1, max)) * 100));
  return (
    <div className="progress-track">
      <div className="progress-fill" style={{ width: pct + "%" }} />
    </div>
  );
}

// ============================================================
// 챕터 카드 (홈)
// ============================================================
function ChapterCard({ chapter, progress, onClick, index }) {
  const isReview = chapter.kind === "review";
  const isMega = chapter.kind === "mega";
  const klass = "chapter-card" +
    (isReview ? " review" : "") +
    (isMega ? " mega-review" : "") +
    (progress?.completed ? " completed" : "");

  const ratio = progress && progress.total
    ? Math.round((progress.score / progress.total) * 100)
    : 0;

  let kicker = `CHAPTER ${index + 1}`;
  if (isReview) kicker = "✦ 통합정리";
  if (isMega) kicker = "✦✦ 대왕정리";

  const icon = isReview ? "✦" : isMega ? "✦✦" : String(index + 1);

  return (
    <button className={klass} onClick={onClick}>
      <div className="chapter-card-icon">{icon}</div>
      <div className="chapter-card-body">
        <div className="chapter-card-kicker">{kicker}</div>
        <div className="chapter-card-title">{chapter.title}</div>
        <div className="chapter-card-meta">
          {chapter.questions?.length || 0}문제
          {chapter.blurb && <span className="chapter-card-meta-sep">·</span>}
          {chapter.blurb && <span>{chapter.blurb}</span>}
        </div>
        {progress?.total > 0 && (
          <div className="chapter-progress-track">
            <div className="chapter-progress-fill" style={{ width: ratio + "%" }} />
          </div>
        )}
      </div>
      {progress?.completed && (
        <div className="chapter-card-checkmark"><Icon name="check" size={14} /></div>
      )}
    </button>
  );
}

// ============================================================
// 모달 (어드민 + 다이얼로그)
// ============================================================
function Modal({ open, onClose, title, children, footer, wide }) {
  if (!open) return null;
  return (
    <div className="modal-backdrop" onClick={onClose} style={{
      position: "fixed", inset: 0, background: "#2a262299",
      zIndex: 100, display: "grid", placeItems: "center", padding: 16
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: "var(--bg-elevated)",
        borderRadius: "var(--r-lg)",
        boxShadow: "var(--shadow-lift)",
        border: "1px solid var(--border)",
        width: "100%",
        maxWidth: wide ? 720 : 480,
        maxHeight: "90vh",
        overflow: "auto",
        display: "flex",
        flexDirection: "column"
      }}>
        <div style={{
          padding: "18px 22px",
          borderBottom: "1px solid var(--border)",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between"
        }}>
          <div style={{ fontWeight: 800, fontSize: 17, letterSpacing: "-0.02em" }}>{title}</div>
          <button onClick={onClose} style={{
            width: 32, height: 32, borderRadius: 8,
            background: "var(--surface)", border: "1px solid var(--border)",
            display: "grid", placeItems: "center"
          }}><Icon name="x" size={16} /></button>
        </div>
        <div style={{ padding: "20px 22px", flex: 1 }}>{children}</div>
        {footer && (
          <div style={{
            padding: "14px 22px",
            borderTop: "1px solid var(--border)",
            display: "flex",
            justifyContent: "flex-end",
            gap: 10
          }}>{footer}</div>
        )}
      </div>
    </div>
  );
}

// 전역 노출
Object.assign(window, {
  Icon, TopBar, Confetti, ProgressBar, ChapterCard, Modal
});
