// 영어문법학습 — 관리자 화면 (챕터/문제 등록·수정)

const { useState, useEffect, useMemo } = React;

// ----------------------------------------------------------------
// 토큰 입력 헬퍼: 콤마 또는 공백 구분 문자열 ↔ 배열
// ----------------------------------------------------------------
function tokenString(arr) { return (arr || []).join(" "); }
function parseTokens(str) {
  return (str || "").trim().split(/\s+/).filter(Boolean);
}
function parseDistractors(str) {
  // 콤마 또는 줄바꿈으로 구분 (각 항목은 한 개의 단어 또는 다단어 토큰 — 단, 우리 모델은 단일 토큰)
  // 단일 단어 위주이지만 don't 같은 줄임도 포함
  return (str || "")
    .split(/[,\n]+/)
    .map(s => s.trim())
    .filter(Boolean);
}

// ----------------------------------------------------------------
// 문제 편집 폼
// ----------------------------------------------------------------
function QuestionForm({ value, onChange, onDelete, onMoveUp, onMoveDown }) {
  const q = value;
  const update = (patch) => onChange({ ...q, ...patch });

  return (
    <div style={{
      border: "1px solid var(--border)",
      borderRadius: "var(--r-md)",
      padding: 16,
      background: "var(--surface)",
      marginBottom: 12
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
        <div style={{ fontWeight: 800, fontSize: 14, color: "var(--text-soft)" }}>
          문제 ID: <code style={{ color: "var(--brand-deep)" }}>{q.id}</code>
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          {onMoveUp && <button className="btn btn-soft btn-sm" onClick={onMoveUp}>↑</button>}
          {onMoveDown && <button className="btn btn-soft btn-sm" onClick={onMoveDown}>↓</button>}
          <button className="btn btn-soft btn-sm" onClick={onDelete} style={{ color: "var(--wrong)" }}>
            <Icon name="trash" size={14} />
          </button>
        </div>
      </div>

      <div className="admin-field">
        <label>한국어 문장 (학생에게 보이는 프롬프트)</label>
        <input
          type="text"
          value={q.ko || ""}
          onChange={(e) => update({ ko: e.target.value })}
          placeholder="예: 그는 학생이 아니다."
        />
      </div>

      <div className="row" style={{ alignItems: "stretch" }}>
        <div className="admin-field" style={{ flex: 1 }}>
          <label>빈칸 앞 단어 (공백 구분, 비워두면 문장 맨 앞)</label>
          <input
            type="text"
            value={tokenString(q.prefix)}
            onChange={(e) => update({ prefix: parseTokens(e.target.value) })}
            placeholder="예: He"
          />
        </div>
        <div className="admin-field" style={{ flex: 1 }}>
          <label>빈칸 뒤 단어 (공백 구분)</label>
          <input
            type="text"
            value={tokenString(q.suffix)}
            onChange={(e) => update({ suffix: parseTokens(e.target.value) })}
            placeholder="예: a student ."
          />
        </div>
      </div>

      <div className="admin-field">
        <label>★ 정답 단어 (공백 구분, 순서대로) — 핵심 문법 부분</label>
        <input
          type="text"
          value={tokenString(q.answer)}
          onChange={(e) => update({ answer: parseTokens(e.target.value) })}
          placeholder="예: is not"
          style={{ fontFamily: "var(--font-eng)", fontWeight: 700 }}
        />
      </div>

      <div className="admin-field">
        <label>낱말카드 오답 (콤마 또는 줄바꿈 구분, 각 항목이 카드 1개)</label>
        <input
          type="text"
          value={(q.distractors || []).join(", ")}
          onChange={(e) => update({ distractors: parseDistractors(e.target.value) })}
          placeholder="예: are, am, isn't, no"
          style={{ fontFamily: "var(--font-eng)" }}
        />
      </div>

      <div className="admin-field" style={{ marginBottom: 0 }}>
        <label>문법 설명 (HTML 허용: &lt;b&gt;, &lt;code&gt;, &lt;br&gt;)</label>
        <textarea
          value={q.explanation || ""}
          onChange={(e) => update({ explanation: e.target.value })}
          placeholder="예: be동사 부정은 <b>be + not</b>."
          rows={2}
        />
      </div>

      {/* 미리보기 */}
      <div style={{
        marginTop: 10,
        padding: 10,
        background: "var(--bg-elevated)",
        border: "1px dashed var(--border-strong)",
        borderRadius: 8,
        fontSize: 13,
        color: "var(--text-soft)"
      }}>
        <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-muted)", marginBottom: 4 }}>
          미리보기
        </div>
        <div>
          <b>{q.ko || "(한국어 문장)"}</b>
          {" → "}
          <span style={{ fontFamily: "var(--font-eng)" }}>
            {tokenString(q.prefix)}
            <span style={{
              background: "var(--correct-faint)",
              color: "var(--correct-deep)",
              padding: "0 6px",
              borderRadius: 4,
              fontWeight: 700,
              margin: "0 4px"
            }}>{tokenString(q.answer) || "___"}</span>
            {tokenString(q.suffix)}
          </span>
        </div>
      </div>
    </div>
  );
}

// ----------------------------------------------------------------
// 챕터 편집기
// ----------------------------------------------------------------
function ChapterEditor({ chapter, onSave, onCancel, onDelete }) {
  const [draft, setDraft] = useState(() => JSON.parse(JSON.stringify(chapter || {
    id: "", title: "", kind: "basic", blurb: "", summary: "", questions: []
  })));
  const [saving, setSaving] = useState(false);

  const updateField = (patch) => setDraft({ ...draft, ...patch });
  const updateQuestion = (idx, newQ) => {
    const next = [...draft.questions];
    next[idx] = newQ;
    setDraft({ ...draft, questions: next });
  };
  const addQuestion = () => {
    const newId = "q" + (draft.questions.length + 1) + "_" + Date.now().toString(36).slice(-3);
    setDraft({
      ...draft,
      questions: [
        ...draft.questions,
        { id: newId, ko: "", prefix: [], answer: [], suffix: [], distractors: [], explanation: "" }
      ]
    });
  };
  const deleteQuestion = (idx) => {
    if (!confirm("이 문제를 삭제할까요?")) return;
    setDraft({ ...draft, questions: draft.questions.filter((_, i) => i !== idx) });
  };
  const moveQuestion = (idx, dir) => {
    const next = [...draft.questions];
    const t = idx + dir;
    if (t < 0 || t >= next.length) return;
    [next[idx], next[t]] = [next[t], next[idx]];
    setDraft({ ...draft, questions: next });
  };

  async function handleSave() {
    if (!draft.id?.trim()) { alert("챕터 ID를 입력하세요."); return; }
    if (!draft.title?.trim()) { alert("챕터 제목을 입력하세요."); return; }
    setSaving(true);
    try {
      await QuizDB.saveChapter(draft);
      onSave(draft);
    } catch (err) {
      alert("저장 실패: " + (err.message || err));
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="fade-in">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 18 }}>
        <button className="btn btn-soft btn-sm" onClick={onCancel}>
          <Icon name="arrow-left" size={14} /> 취소
        </button>
        <div style={{ display: "flex", gap: 8 }}>
          {onDelete && (
            <button className="btn btn-soft btn-sm" onClick={onDelete} style={{ color: "var(--wrong)" }}>
              <Icon name="trash" size={14} /> 챕터 삭제
            </button>
          )}
          <button className="btn btn-primary btn-sm" onClick={handleSave} disabled={saving}>
            {saving ? "저장 중..." : "저장"}
          </button>
        </div>
      </div>

      <h1 style={{ fontSize: 24, fontWeight: 800, letterSpacing: "-0.02em", margin: "0 0 18px" }}>
        {chapter ? "챕터 편집" : "새 챕터"}
      </h1>

      <div className="card" style={{ padding: 18, marginBottom: 18 }}>
        <div className="row" style={{ alignItems: "stretch" }}>
          <div className="admin-field" style={{ flex: 1 }}>
            <label>챕터 ID (영문/하이픈, 한 번 만들면 바꾸지 마세요)</label>
            <input
              type="text"
              value={draft.id}
              onChange={(e) => updateField({ id: e.target.value.toLowerCase().replace(/[^a-z0-9\-]/g, "-") })}
              placeholder="예: be-aff"
              disabled={!!chapter}
              style={{ fontFamily: "var(--font-eng)" }}
            />
          </div>
          <div className="admin-field" style={{ width: 160 }}>
            <label>종류</label>
            <select
              value={draft.kind}
              onChange={(e) => updateField({ kind: e.target.value })}
            >
              <option value="basic">기초</option>
              <option value="review">통합정리 ✦</option>
              <option value="mega">대왕정리 ✦✦</option>
            </select>
          </div>
        </div>
        <div className="admin-field">
          <label>제목</label>
          <input
            type="text"
            value={draft.title}
            onChange={(e) => updateField({ title: e.target.value })}
            placeholder="예: be동사 부정"
          />
        </div>
        <div className="admin-field">
          <label>부제 (홈에서 카드 하단에 표시)</label>
          <input
            type="text"
            value={draft.blurb || ""}
            onChange={(e) => updateField({ blurb: e.target.value })}
            placeholder="예: be동사 + not"
          />
        </div>
        <div className="admin-field" style={{ marginBottom: 0 }}>
          <label>문법 정리 (HTML — &lt;h4&gt;, &lt;p&gt;, &lt;table&gt;, &lt;code&gt;, &lt;b&gt; 등)</label>
          <textarea
            value={draft.summary || ""}
            onChange={(e) => updateField({ summary: e.target.value })}
            rows={8}
            style={{ fontFamily: "var(--font-eng)", fontSize: 13 }}
          />
        </div>
      </div>

      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
        <h3 style={{ margin: 0, fontSize: 18, letterSpacing: "-0.02em" }}>
          문제 ({draft.questions.length}개)
        </h3>
        <button className="btn btn-primary btn-sm" onClick={addQuestion}>
          <Icon name="plus" size={14} /> 문제 추가
        </button>
      </div>

      {draft.questions.map((q, idx) => (
        <QuestionForm
          key={q.id}
          value={q}
          onChange={(newQ) => updateQuestion(idx, newQ)}
          onDelete={() => deleteQuestion(idx)}
          onMoveUp={idx > 0 ? () => moveQuestion(idx, -1) : null}
          onMoveDown={idx < draft.questions.length - 1 ? () => moveQuestion(idx, 1) : null}
        />
      ))}

      <div style={{ marginTop: 24, display: "flex", justifyContent: "flex-end", gap: 8 }}>
        <button className="btn btn-soft" onClick={onCancel}>취소</button>
        <button className="btn btn-primary" onClick={handleSave} disabled={saving}>
          {saving ? "저장 중..." : "챕터 저장"}
        </button>
      </div>
    </div>
  );
}

// ----------------------------------------------------------------
// 관리자 메인 화면
// ----------------------------------------------------------------
function AdminScreen({ chapters, user, onBack, onSignOut, onReload }) {
  const [editing, setEditing] = useState(null); // null | { isNew: true } | chapter
  const isLocalDev = user?._localDev;

  async function handleDeleteChapter(id) {
    if (!confirm(`'${id}' 챕터를 정말 삭제할까요? 되돌릴 수 없습니다.`)) return;
    try {
      await QuizDB.deleteChapter(id);
      setEditing(null);
      onReload && onReload();
    } catch (err) {
      alert("삭제 실패: " + err.message);
    }
  }

  if (editing) {
    return (
      <ChapterEditor
        chapter={editing.isNew ? null : editing}
        onSave={() => { setEditing(null); onReload && onReload(); }}
        onCancel={() => setEditing(null)}
        onDelete={editing.isNew ? null : () => handleDeleteChapter(editing.id)}
      />
    );
  }

  return (
    <div className="fade-in">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
        <button className="btn btn-soft btn-sm" onClick={onBack}>
          <Icon name="arrow-left" size={14} /> 홈으로
        </button>
        <button className="btn btn-soft btn-sm" onClick={onSignOut}>
          <Icon name="log-out" size={14} /> 로그아웃
        </button>
      </div>

      <div style={{ marginBottom: 18 }}>
        <div style={{
          fontSize: 12, fontWeight: 800, letterSpacing: "0.1em",
          textTransform: "uppercase", color: "var(--brand-deep)",
          marginBottom: 6
        }}>관리자 모드</div>
        <h1 style={{ margin: 0, fontSize: 28, fontWeight: 800, letterSpacing: "-0.03em" }}>
          챕터 관리
        </h1>
        <p style={{ color: "var(--text-soft)", fontSize: 14, margin: "8px 0 0" }}>
          {user.displayName || user.email}로 로그인됨
          {isLocalDev && <span style={{ color: "var(--gold)", marginLeft: 8 }}>· 개발 모드 (Firebase 미설정)</span>}
        </p>
      </div>

      {isLocalDev && (
        <div className="admin-banner" style={{
          background: "var(--gold-faint)",
          borderColor: "#E8D6AC",
          color: "#8B6A30"
        }}>
          <div style={{ fontSize: 13 }}>
            <b>개발 모드</b> — 데이터는 이 브라우저 localStorage에만 저장됩니다.
            <code style={{ marginLeft: 6 }}>firebase-config.js</code>를 채우면 Firestore가 자동 연결됩니다.
          </div>
        </div>
      )}

      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", margin: "22px 0 12px" }}>
        <div className="section-title" style={{ margin: 0 }}>챕터 목록 ({chapters.length})</div>
        <button className="btn btn-primary btn-sm" onClick={() => setEditing({ isNew: true })}>
          <Icon name="plus" size={14} /> 새 챕터
        </button>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {chapters.map((ch, idx) => (
          <div key={ch.id} className="card" style={{
            padding: "14px 16px",
            display: "flex",
            alignItems: "center",
            gap: 14
          }}>
            <div className="chapter-card-icon" style={{
              width: 40, height: 40, fontSize: 14,
              ...(ch.kind === "review" ? { background: "var(--gold-faint)", color: "#8B6A30" } : {}),
              ...(ch.kind === "mega" ? { background: "linear-gradient(135deg, #efe1c2, #e3cfa1)", color: "#6A4F1A" } : {})
            }}>
              {ch.kind === "review" ? "✦" : ch.kind === "mega" ? "✦✦" : (idx + 1)}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 700, fontSize: 15, letterSpacing: "-0.01em" }}>
                {ch.title}
                <code style={{
                  marginLeft: 8, fontSize: 11, color: "var(--text-muted)",
                  fontFamily: "var(--font-eng)"
                }}>{ch.id}</code>
              </div>
              <div style={{ fontSize: 12, color: "var(--text-muted)", marginTop: 2 }}>
                {ch.questions?.length || 0}문제 · {ch.blurb || ""}
              </div>
            </div>
            <button
              className="btn btn-soft btn-sm"
              onClick={() => setEditing(ch)}
            ><Icon name="edit" size={13} /> 편집</button>
          </div>
        ))}
      </div>

      <div style={{ marginTop: 32, padding: 16, background: "var(--surface)", borderRadius: "var(--r-md)", border: "1px solid var(--border)", fontSize: 13, color: "var(--text-soft)", lineHeight: 1.6 }}>
        <b>💡 Firebase 연결 안내</b><br/>
        <code>firebase-config.js</code> 파일에 본인 Firebase 프로젝트의 config를 채우고,
        <code>window.ADMIN_EMAILS</code>에 본인 Gmail을 추가하세요.
        그러면 자동으로 Google 로그인이 활성화되고, 등록·수정 권한이 본인에게만 부여됩니다.
      </div>
    </div>
  );
}

// 로그인 화면
function AdminLoginScreen({ onBack, onSignIn, useFirebase }) {
  return (
    <div className="fade-in" style={{ paddingTop: 8 }}>
      <button className="btn btn-soft btn-sm" onClick={onBack}>
        <Icon name="arrow-left" size={14} /> 홈으로
      </button>
      <div style={{
        marginTop: 60,
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        textAlign: "center",
        gap: 18
      }}>
        <div style={{
          width: 80, height: 80, borderRadius: 24,
          background: "var(--brand-faint)",
          display: "grid", placeItems: "center",
          color: "var(--brand-deep)"
        }}>
          <Icon name="lock" size={36} />
        </div>
        <div>
          <h1 style={{ margin: 0, fontSize: 26, fontWeight: 800, letterSpacing: "-0.03em" }}>
            관리자 로그인
          </h1>
          <p style={{ color: "var(--text-soft)", margin: "10px 0 0", maxWidth: 320 }}>
            챕터를 등록·수정하려면 등록된 Google 계정으로 로그인하세요.
          </p>
        </div>

        <button className="btn btn-soft btn-lg" onClick={onSignIn} style={{ minWidth: 260 }}>
          <Icon name="google" size={18} /> Google로 로그인
        </button>

        {!useFirebase && (
          <div style={{
            fontSize: 12, color: "var(--text-muted)",
            background: "var(--gold-faint)",
            border: "1px solid #E8D6AC",
            padding: "10px 14px",
            borderRadius: "var(--r-md)",
            maxWidth: 360,
            lineHeight: 1.6,
            color: "#8B6A30"
          }}>
            현재 <b>개발 모드</b>입니다 (Firebase 미설정).<br />
            클릭하면 이 브라우저에서만 관리자로 로그인됩니다.
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { AdminScreen, AdminLoginScreen, ChapterEditor });
