/* BeatEnemy.jsx — 軍法處置 v2 (Public Enemy Wall + Slap Mechanic)
   - Admin-curated queue of up to 10 enemies (each has hits + maxHP 500)
   - Front-end shows ONLY the top 3 active enemies for selection
   - Click an enemy card to select; slap them with 「軍法伺候·掌摑面門」
   - Avatar filter intensifies past 35% / 75% damage
   - 10% crit chance produces giant gold floating text + bumps CRIT counter
   - Real-time battle log scrolls to bottom
   - When an enemy's hits == maxHP they cycle out, #4 slides in
   - All state in localStorage for demo. Real backend would use Firebase/Supabase. */

const MAX_HP = 500;
const LS_QUEUE_KEY = "sw_martial_queue_v2";
const LS_LOG_KEY   = "sw_martial_log_v2";
const LS_STATS_KEY = "sw_martial_stats_v2";

// Mock queue (in production, this is populated by admin via Firebase/Supabase)
const SEED_QUEUE = [
  { id: "SW-66666", nickname: "曹賊·孟德",     avatar: null, hits: 120 },
  { id: "SW-88888", nickname: "袁紹·本初",     avatar: null, hits: 380 },
  { id: "SW-44444", nickname: "呂奉先",         avatar: null, hits: 240 },
  { id: "SW-22222", nickname: "董卓·仲穎",     avatar: null, hits: 0 },
  { id: "SW-33333", nickname: "司馬懿·仲達",   avatar: null, hits: 0 },
  { id: "SW-55555", nickname: "夏侯惇",         avatar: null, hits: 0 },
  { id: "SW-77777", nickname: "張遼·文遠",     avatar: null, hits: 0 },
];

const ATTACK_LINES = [
  "吃我一拳！", "叫你夜襲！", "戰犯納命來！",
  "敢犯吾盟？", "看招！", "受死吧！",
];
const BEG_LINES = [
  "將軍饒命！", "再也不敢了！", "主公救我！",
  "饒了我吧！", "罪該萬死！", "求求您…",
];

// Attack methods (frontend-selectable)
const ATTACK_KINDS = {
  slap: {
    cn: "掌 摑 面 門",
    en: "SLAP",
    eyebrow: "軍 法 伺 候",
    logVerb: "掴掌",
    floaters: ["掴！", "啦！", "昋！", "拍！", "損！"],
  },
  spit: {
    cn: "吞 口 水",
    en: "SPIT",
    eyebrow: "變 隸 之 辱",
    logVerb: "吞液",
    floaters: ["吞！", "峨峨！", "不潔！", "呆走！", "商！"],
  },
  egg: {
    cn: "丟 雞 蛋",
    en: "EGG",
    eyebrow: "群 愁 炸 面",
    logVerb: "雞蛋砸面",
    floaters: ["砸！", "象漾！", "滾！", "蛋黃滾滾！", "潝！"],
  },
};

// ─── Storage helpers ───────────────────────────────────────
const readJSON = (key, fallback) => {
  try { return JSON.parse(localStorage.getItem(key) || "null") ?? fallback; }
  catch { return fallback; }
};
const writeJSON = (key, val) => {
  try { localStorage.setItem(key, JSON.stringify(val)); } catch {}
};

// ─── Mock real-time backend (replace with Firebase/Supabase) ──
//
// async function syncQueue() {
//   // const snap = await firebase.firestore().collection("martial_queue").get();
//   // return snap.docs.map(d => d.data());
// }
//
// async function pushHit(enemyId) {
//   // await firebase.firestore().collection("martial_queue").doc(enemyId)
//   //   .update({ hits: firebase.firestore.FieldValue.increment(1) });
// }

// ─── Palm SVG (slap overlay) ───────────────────────────────
const PalmSVG = () => (
  <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid meet">
    {/* Stylised hand/palm in red-orange — simplified silhouette */}
    <g fill="rgba(220, 80, 60, 0.78)" stroke="rgba(120,30,20,0.85)" strokeWidth="1.5" strokeLinejoin="round">
      {/* palm */}
      <path d="M30,52 C28,42 32,32 38,30 C40,24 46,22 50,26 C52,18 58,16 62,22 C66,14 74,16 76,24 C78,18 86,20 84,32 C88,38 86,48 80,55 C82,62 78,72 70,76 L40,76 C32,72 28,62 30,52 Z" />
      {/* fingers — 5 columns */}
      <ellipse cx="38" cy="28" rx="5" ry="11" />
      <ellipse cx="50" cy="24" rx="5" ry="13" />
      <ellipse cx="62" cy="22" rx="5" ry="14" />
      <ellipse cx="74" cy="26" rx="5" ry="12" />
      <ellipse cx="83" cy="36" rx="5" ry="9" transform="rotate(35 83 36)" />
    </g>
    {/* impact streaks */}
    <g stroke="rgba(255,200,80,0.7)" strokeWidth="2.5" strokeLinecap="round" fill="none">
      <line x1="14" y1="30" x2="24" y2="36" />
      <line x1="10" y1="48" x2="22" y2="48" />
      <line x1="14" y1="66" x2="24" y2="60" />
      <line x1="86" y1="14" x2="80" y2="22" />
      <line x1="92" y1="32" x2="84" y2="34" />
    </g>
  </svg>
);

// ─── Spit SVG (saliva globs + spray streaks) ───────────────
const SpitSVG = () => (
  <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid meet">
    {/* central glob */}
    <g fill="rgba(220, 235, 240, 0.82)" stroke="rgba(120,170,180,0.85)" strokeWidth="1.2">
      <ellipse cx="50" cy="52" rx="22" ry="16" />
      <ellipse cx="42" cy="46" rx="5" ry="3" fill="rgba(255,255,255,0.6)" stroke="none" />
      {/* drips */}
      <circle cx="34" cy="72" r="4.5" />
      <circle cx="62" cy="76" r="3.5" />
      <circle cx="50" cy="80" r="2.5" />
      {/* satellite droplets */}
      <circle cx="22" cy="40" r="3" />
      <circle cx="78" cy="36" r="3.5" />
      <circle cx="86" cy="56" r="2.5" />
      <circle cx="16" cy="58" r="2.5" />
    </g>
    {/* spray streaks */}
    <g stroke="rgba(190,225,235,0.7)" strokeWidth="2" strokeLinecap="round" fill="none">
      <line x1="14" y1="32" x2="28" y2="42" />
      <line x1="90" y1="26" x2="76" y2="40" />
      <line x1="10" y1="62" x2="22" y2="58" />
      <line x1="92" y1="64" x2="80" y2="58" />
    </g>
  </svg>
);

// ─── Egg SVG (yolk splat + cracked shell) ──────────────────
const EggSVG = () => (
  <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid meet">
    {/* egg-white splat — irregular blob */}
    <path
      d="M50,18 C68,14 86,28 84,46 C92,52 90,66 78,72 C82,84 68,90 58,84 C52,92 40,92 36,82 C24,86 14,76 18,64 C10,58 14,44 26,42 C24,28 38,20 50,18 Z"
      fill="rgba(255, 248, 220, 0.88)" stroke="rgba(180,150,80,0.7)" strokeWidth="1.2"
    />
    {/* yolk */}
    <ellipse cx="50" cy="50" rx="18" ry="15" fill="rgba(255, 195, 60, 0.95)" stroke="rgba(190,130,30,0.85)" strokeWidth="1.5" />
    <ellipse cx="44" cy="44" rx="5" ry="3.5" fill="rgba(255, 235, 150, 0.85)" />
    {/* shell shards */}
    <g fill="rgba(245, 230, 200, 0.9)" stroke="rgba(150,120,70,0.7)" strokeWidth="1">
      <polygon points="16,30 24,22 28,30 22,34" />
      <polygon points="80,28 88,32 84,40 76,36" />
      <polygon points="78,72 86,78 80,84 74,78" />
      <polygon points="20,76 28,72 30,80 22,82" />
    </g>
    {/* yolk drips */}
    <g fill="rgba(255, 195, 60, 0.85)">
      <circle cx="34" cy="74" r="3" />
      <circle cx="66" cy="76" r="3.5" />
      <circle cx="52" cy="86" r="2" />
    </g>
  </svg>
);

// ─── Component ─────────────────────────────────────────────
const BeatEnemy = () => {
  // Queue state — seeded from localStorage or SEED_QUEUE
  const [queue, setQueue] = React.useState(() => readJSON(LS_QUEUE_KEY, SEED_QUEUE).map((e) => ({ ...e, hits: Math.min(Number(e.hits) || 0, MAX_HP) })));
  const [selectedId, setSelectedId] = React.useState(null);
  const [isHit, setIsHit] = React.useState(false);
  const [floaters, setFloaters] = React.useState([]); // [{id, x, y, text, kind}]
  const [slaps, setSlaps] = React.useState([]);       // [{id, x, y, rot}]
  const [log, setLog] = React.useState(() => readJSON(LS_LOG_KEY, []));
  const [stats, setStats] = React.useState(() => readJSON(LS_STATS_KEY, { totalHits: 0, crit: 0, wrath: 0 }));
  const nextId = React.useRef(0);
  const logEndRef = React.useRef(null);

  // Persist on change
  React.useEffect(() => writeJSON(LS_QUEUE_KEY, queue), [queue]);
  React.useEffect(() => writeJSON(LS_LOG_KEY, log.slice(-50)), [log]);
  React.useEffect(() => writeJSON(LS_STATS_KEY, stats), [stats]);

  // Active enemies — only show top 3 alive (hits < MAX_HP), in queue order
  const activeQueue = queue.filter((e) => e.hits < MAX_HP).slice(0, 3);

  // Default selection: first active enemy
  React.useEffect(() => {
    if (!selectedId && activeQueue.length > 0) {
      setSelectedId(activeQueue[0].id);
    } else if (selectedId && !activeQueue.find((e) => e.id === selectedId)) {
      setSelectedId(activeQueue[0]?.id || null);
    }
  }, [queue, selectedId, activeQueue]);

  const selected = activeQueue.find((e) => e.id === selectedId) || activeQueue[0];

  // Auto-scroll log
  React.useEffect(() => {
    if (logEndRef.current) {
      logEndRef.current.scrollTop = logEndRef.current.scrollHeight;
    }
  }, [log]);

  const pushLog = (text, kind) => {
    const t = new Date().toLocaleTimeString("zh-Hant", { hour12: false });
    setLog((l) => [...l, { t, text, kind: kind || "" }].slice(-50));
  };

  const onStrike = (kind = "slap") => {
    if (!selected) return;
    setIsHit(true);
    setTimeout(() => setIsHit(false), 400);

    const meta = ATTACK_KINDS[kind] || ATTACK_KINDS.slap;
    const isCrit = Math.random() < 0.1;
    const fid = nextId.current++;

    // Floating text
    if (isCrit) {
      setFloaters((arr) => [...arr, {
        id: fid,
        x: 0, y: 0,
        text: "暴擊 !!!  -999",
        kind: "crit",
      }]);
    } else {
      // 50% kind-specific yell, 30% generic taunt, 20% beg
      const r = Math.random();
      let pool, sub;
      if (r < 0.5)      { pool = meta.floaters; sub = kind; }
      else if (r < 0.8) { pool = ATTACK_LINES;  sub = "attack"; }
      else              { pool = BEG_LINES;     sub = "beg"; }
      setFloaters((arr) => [...arr, {
        id: fid,
        x: (Math.random() * 160 - 80),
        y: (Math.random() * 30 - 15),
        text: pool[Math.floor(Math.random() * pool.length)],
        kind: sub,
      }]);
    }
    setTimeout(() => setFloaters((arr) => arr.filter((f) => f.id !== fid)), 1300);

    // Attack overlay — random position
    const sid = nextId.current++;
    setSlaps((arr) => [...arr, {
      id: sid,
      kind,
      x: 20 + Math.random() * 60,
      y: 20 + Math.random() * 60,
      rot: Math.random() * 80 - 40,
      scale: 0.8 + Math.random() * 0.4,
    }]);
    setTimeout(() => setSlaps((arr) => arr.filter((s) => s.id !== sid)), 700);

    // Increment hits + stats
    const newHits = selected.hits + 1;
    const reachedMax = newHits >= MAX_HP;

    setQueue((q) => q.map((e) => e.id === selected.id ? { ...e, hits: newHits } : e));
    setStats((s) => ({
      totalHits: s.totalHits + 1,
      crit: s.crit + (isCrit ? 1 : 0),
      wrath: Math.min(9999, s.wrath + 1),
    }));

    // Log
    if (isCrit) {
      pushLog(`「${selected.nickname}」面門中暴擊 ── 金光迸現，三軍喝采！`, "crit");
    } else if (newHits % 25 === 0 || newHits < 5) {
      pushLog(`「${selected.nickname}」遵受 ${meta.logVerb} · 受刑進度 ${newHits.toLocaleString()} / ${MAX_HP.toLocaleString()}。`);
    }
    if (reachedMax) {
      pushLog(`敵將「${selected.nickname}」不堪羞辱，痛哭流涕，已被打暈抬走！`, "evict");
    }
  };

  // Damage progress for selected
  const progress = selected ? selected.hits / MAX_HP : 0;
  const tilt =
    progress >= 0.75 ? -8 :
    progress >= 0.35 ? -3 : 0;

  return (
    <div className="wrap">
      <div className="martial2">
        <div className="martial2__header">
          <div className="martial2__eyebrow">PUBLIC ENEMY WALL · 軍法處置</div>
          <h3 className="martial2__title">敵 將 名 冊</h3>
          <div className="martial2__sub">
            ・ 同盟公敵 · 衆怒所向 · 三人並列 · 打盡再續 ・
          </div>
        </div>

        {/* === Top 3 enemy cards === */}
        <div className="enemy-grid">
          {activeQueue.length === 0 && (
            <div className="enemy-empty">
              名冊空缺 · 暫無敵將── 待管理員押解。
            </div>
          )}
          {activeQueue.map((e) => {
            const p = e.hits / MAX_HP;
            const isSelected = e.id === selectedId;
            return (
              <button
                key={e.id}
                className={`enemy-card ${isSelected ? "enemy-card--selected" : ""}`}
                onClick={() => setSelectedId(e.id)}
              >
                <div className="enemy-card__avatar-frame">
                  <div
                    className={`enemy-card__avatar ${p >= 0.75 ? "enemy-card__avatar--severe" : p >= 0.35 ? "enemy-card__avatar--red" : ""}`}
                    style={e.avatar ? { backgroundImage: `url(${e.avatar})` } : {}}
                  >
                    {!e.avatar && <span>{e.nickname[0]}</span>}
                  </div>
                </div>
                <div className="enemy-card__name">{e.nickname}</div>
                <div className="enemy-card__hp">
                  <div className="enemy-card__hp-bar" style={{ width: `${p * 100}%` }} />
                </div>
                <div className="enemy-card__hp-text">
                  <span>{e.hits.toLocaleString()}</span>
                  <span className="dim">/ {MAX_HP.toLocaleString()}</span>
                </div>
              </button>
            );
          })}
        </div>

        {/* === Selected enemy — large slap arena + actions === */}
        {selected && (
          <div className="slap-arena">
            <div className="slap-arena__left">
              <div className="slap-arena__eyebrow">CURRENT TARGET · 當前受刑</div>
              <div className="slap-arena__name">{selected.nickname}</div>

              <div className={`slap-stage ${isHit ? "slap-stage--hit" : ""}`}>
                <div
                  className={`slap-face ${progress >= 0.75 ? "slap-face--severe" : progress >= 0.35 ? "slap-face--red" : ""}`}
                  style={{
                    transform: `rotate(${tilt}deg)`,
                    backgroundImage: selected.avatar ? `url(${selected.avatar})` : "none",
                  }}
                >
                  {!selected.avatar && <span className="slap-face__initial">{selected.nickname[0]}</span>}
                </div>

                {/* Attack overlays (slap / spit / egg) */}
                {slaps.map((s) => (
                  <div
                    key={s.id}
                    className={`slap-palm slap-palm--${s.kind || "slap"}`}
                    style={{
                      left: `${s.x}%`,
                      top: `${s.y}%`,
                      "--rot": `${s.rot}deg`,
                      "--scl": s.scale,
                      transform: `translate(-50%, -50%) rotate(${s.rot}deg) scale(${s.scale})`,
                    }}
                  >
                    {(s.kind === "spit") ? <SpitSVG />
                      : (s.kind === "egg") ? <EggSVG />
                      : <PalmSVG />}
                  </div>
                ))}

                {/* Floating text */}
                {floaters.map((f) => (
                  <span
                    key={f.id}
                    className={`floater floater--${f.kind}`}
                    style={{
                      left: `calc(50% + ${f.x}px)`,
                      top: `calc(28% + ${f.y}px)`,
                    }}
                  >
                    {f.text}
                  </span>
                ))}
              </div>

              <div className="strike-row">
                {Object.entries(ATTACK_KINDS).map(([k, meta]) => (
                  <button
                    key={k}
                    className={`strike-btn-v2 strike-btn-v2--${k}`}
                    onClick={() => onStrike(k)}
                  >
                    <span className="strike-btn-v2__cn">{meta.cn}</span>
                  </button>
                ))}
              </div>
            </div>

            <div className="slap-arena__right">
              <div className="counter-v2">
                <div className="counter-v2__label">TOTAL LASHES<br/>當將累積</div>
                <div className="counter-v2__num">{selected.hits.toLocaleString()}</div>
                <div className="counter-v2__hp">
                  <div className="counter-v2__hp-bar" style={{ width: `${progress * 100}%` }} />
                </div>
                <div className="counter-v2__sub">
                  剩餘 <b style={{color: "#f3c370"}}>{(MAX_HP - selected.hits).toLocaleString()}</b> 掌 · 即可打退
                </div>
              </div>

              <div className="stat-row">
                <div className="stat-box">
                  <div className="stat-box__lbl">CRIT</div>
                  <div className="stat-box__num">{stats.crit.toLocaleString()}</div>
                  <div className="stat-box__cn">暴 擊 次 數</div>
                </div>
                <div className="stat-box">
                  <div className="stat-box__lbl">WRATH</div>
                  <div className="stat-box__num stat-box__num--wrath">{stats.wrath.toLocaleString()}</div>
                  <div className="stat-box__cn">同 盟 怒 氣</div>
                </div>
              </div>

              <div className="war-log">
                <div className="war-log__head">
                  <span className="war-log__lbl">BATTLE LOG · 戰 報</span>
                  <span className="war-log__live"><span className="dot" />LIVE</span>
                </div>
                <div className="war-log__feed" ref={logEndRef}>
                  {log.length === 0 ? (
                    <div className="war-log__empty">尚無軍法紀錄 …</div>
                  ) : log.map((l, i) => (
                    <div key={i} className={`war-log__row ${l.kind ? "war-log__row--" + l.kind : ""}`}>
                      <span className="war-log__t">{l.t}</span>
                      <span className="war-log__txt">{l.text}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

window.BeatEnemy = BeatEnemy;
