// WeaveStudy — Alignment Hall (HIDDEN page)
// Dark, runic, character-select-style 9-cell alignment grid.

const { useState: useStateAH, useEffect: useEffectAH, useRef: useRefAH } = React;

function AlignmentHall({ navigate }) {
  const { ALIGNMENT_GRID, CHARACTERS } = window.WS_DATA;
  const [hoveredId, setHoveredId] = useStateAH(null);
  const [hoveredCell, setHoveredCell] = useStateAH(null);
  const [visited, setVisited] = useStateAH(() => {
    try { return JSON.parse(localStorage.getItem("ws-visited-chars") || "[]"); }
    catch { return []; }
  });
  const [achievementShown, setAchievementShown] = useStateAH(false);
  const [showWelcome, setShowWelcome] = useStateAH(true);

  // hide welcome after first hover
  const markVisited = (id) => {
    if (!visited.includes(id)) {
      const next = [...visited, id];
      setVisited(next);
      try { localStorage.setItem("ws-visited-chars", JSON.stringify(next)); } catch {}
      // Check achievement
      const totalChars = CHARACTERS.length;
      if (next.length >= totalChars && !achievementShown) {
        setTimeout(() => setAchievementShown(true), 600);
      }
    }
  };

  const hoveredChar = hoveredId ? CHARACTERS.find(c => c.id === hoveredId) : null;

  return (
    <div style={{
      minHeight: "100vh",
      background: "radial-gradient(ellipse 90% 70% at 50% 30%, #2A1A4E 0%, #14111C 50%, #0A0810 100%)",
      color: "white",
      position: "relative",
      overflow: "hidden",
      paddingBottom: 80
    }}>
      {/* Rune background */}
      <div style={{
        position: "absolute", inset: 0,
        backgroundImage:
          "radial-gradient(circle, rgba(125,94,247,0.10) 1px, transparent 1.5px)," +
          "radial-gradient(circle, rgba(111,213,200,0.08) 1px, transparent 1.5px)",
        backgroundSize: "28px 28px, 60px 60px",
        backgroundPosition: "0 0, 14px 14px",
        opacity: 0.7,
        pointerEvents: "none"
      }} />

      {/* Vignette */}
      <div style={{
        position: "absolute", inset: 0,
        background: "radial-gradient(ellipse 80% 60% at 50% 40%, transparent 0%, rgba(0,0,0,0.6) 100%)",
        pointerEvents: "none"
      }} />

      {/* Glowing runes around the page */}
      <RuneCorner pos={{ top: 40, left: 40 }} />
      <RuneCorner pos={{ top: 40, right: 40 }} flip />
      <RuneCorner pos={{ bottom: 100, left: 40 }} flip />
      <RuneCorner pos={{ bottom: 100, right: 40 }} />

      {/* Back chrome */}
      <div style={{
        position: "relative",
        maxWidth: 1200, margin: "0 auto",
        padding: "32px 48px"
      }}>
        <button onClick={() => navigate({ name: "camp" })}
                style={{
                  display: "inline-flex", alignItems: "center", gap: 6,
                  fontSize: 13, color: "rgba(255,255,255,0.65)",
                  fontWeight: 600,
                  padding: "8px 12px",
                  border: "1px solid rgba(255,255,255,0.15)",
                  borderRadius: 99,
                  background: "rgba(255,255,255,0.05)"
                }}>
          <Icon name="chevron-left" size={14} color="rgba(255,255,255,0.65)" /> 캠프로 돌아가기
        </button>
      </div>

      {/* Header */}
      <div style={{ position: "relative", maxWidth: 1200, margin: "0 auto", padding: "0 48px 32px", textAlign: "center" }}>
        <div style={{
          display: "inline-flex", alignItems: "center", gap: 12,
          padding: "8px 16px",
          background: "rgba(125,94,247,0.18)",
          border: "1px solid rgba(125,94,247,0.35)",
          borderRadius: 999,
          fontSize: 11, fontWeight: 700,
          color: "var(--weave-violet-bright)",
          letterSpacing: "0.15em", textTransform: "uppercase",
          marginBottom: 20
        }}>
          <span style={{ width: 6, height: 6, borderRadius: 99, background: "var(--weave-violet-bright)", boxShadow: "0 0 8px var(--weave-violet-bright)" }} />
          Hidden · 내츄럴 20 진입자에게만 열림
        </div>

        <h1 style={{
          fontSize: 64, fontWeight: 800, margin: 0,
          letterSpacing: "-0.04em",
          fontFamily: "var(--font-serif-display)",
          background: "linear-gradient(180deg, white 0%, #B8A8FF 100%)",
          WebkitBackgroundClip: "text",
          color: "transparent",
          lineHeight: 1.05
        }}>성향 정렬소</h1>
        <div style={{ fontSize: 16, fontStyle: "italic", color: "rgba(255,255,255,0.6)", marginTop: 8, letterSpacing: "0.04em" }}>
          ALIGNMENT HALL
        </div>
        <p style={{ fontSize: 14, color: "rgba(255,255,255,0.55)", maxWidth: 540, margin: "20px auto 0", lineHeight: 1.6 }}>
          모든 모험가의 성향을 9개 좌표에 정렬한 비밀의 방.<br />
          캐릭터 위에 커서를 올려 그 이유를 확인하고, 클릭으로 캐릭터 시트를 여세요.
        </p>
      </div>

      {/* Grid + tooltip */}
      <div style={{ position: "relative", maxWidth: 880, margin: "0 auto", padding: "0 48px" }}>
        {/* Compass labels — top */}
        <div style={{ display: "grid", gridTemplateColumns: "120px 1fr 1fr 1fr", marginBottom: 12, alignItems: "end" }}>
          <div />
          <CompassLabel>질서<br /><span style={{ opacity: 0.5, fontWeight: 500 }}>LAWFUL</span></CompassLabel>
          <CompassLabel>중립<br /><span style={{ opacity: 0.5, fontWeight: 500 }}>NEUTRAL</span></CompassLabel>
          <CompassLabel>혼돈<br /><span style={{ opacity: 0.5, fontWeight: 500 }}>CHAOTIC</span></CompassLabel>
        </div>

        <div className="alignment-grid" style={{ display: "grid", gridTemplateColumns: "120px 1fr 1fr 1fr", gap: 8 }}>
          {[0, 1, 2].map(row => (
            <React.Fragment key={row}>
              <CompassRowLabel>
                {row === 0 && "선"}
                {row === 1 && "중립"}
                {row === 2 && "악"}
                <br /><span style={{ opacity: 0.5, fontWeight: 500, fontSize: 11 }}>
                  {row === 0 && "GOOD"}
                  {row === 1 && "NEUTRAL"}
                  {row === 2 && "EVIL"}
                </span>
              </CompassRowLabel>
              {[0, 1, 2].map(col => {
                const cell = ALIGNMENT_GRID.find(g => g.row === row && g.col === col);
                return (
                  <AlignmentCell
                    key={`${row}-${col}`}
                    cell={cell}
                    characters={CHARACTERS}
                    hoveredId={hoveredId}
                    setHoveredId={(id) => { setHoveredId(id); if (id) markVisited(id); }}
                    setHoveredCell={setHoveredCell}
                    isCenter={row === 1 && col === 1}
                    navigate={navigate}
                  />
                );
              })}
            </React.Fragment>
          ))}
        </div>
      </div>

      {/* Tooltip drawer at bottom — for hovered char */}
      <div style={{
        position: "fixed",
        bottom: 24, left: "50%",
        transform: `translateX(-50%) translateY(${hoveredChar ? 0 : 100}px)`,
        opacity: hoveredChar ? 1 : 0,
        transition: "transform 220ms cubic-bezier(0.4,0,0.2,1), opacity 220ms",
        pointerEvents: hoveredChar ? "auto" : "none",
        zIndex: 50
      }}>
        {hoveredChar && (
          <div style={{
            background: "rgba(20,15,30,0.92)",
            backdropFilter: "blur(20px)",
            border: "1px solid rgba(125,94,247,0.4)",
            borderRadius: 16,
            padding: 20,
            display: "flex", gap: 16, alignItems: "center",
            minWidth: 460,
            boxShadow: "0 20px 60px rgba(0,0,0,0.6), 0 0 0 1px rgba(125,94,247,0.2)"
          }}>
            <div style={{
              width: 64, height: 80, borderRadius: 10,
              background: `linear-gradient(135deg, ${hoveredChar.portraitColors[0]}, ${hoveredChar.portraitColors[1]})`,
              flexShrink: 0,
              position: "relative", overflow: "hidden",
              display: "flex", alignItems: "center", justifyContent: "center"
            }}>
              <span style={{ fontSize: 32, fontWeight: 800, color: "rgba(255,255,255,0.35)", fontFamily: "var(--font-serif-display)" }}>{hoveredChar.name[0]}</span>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                <span style={{ fontSize: 18, fontWeight: 800, color: "white", letterSpacing: "-0.015em" }}>{hoveredChar.name}</span>
                <span style={{ fontSize: 12, color: "rgba(255,255,255,0.4)" }}>{hoveredChar.nameEn}</span>
              </div>
              <div style={{ fontSize: 12, color: "var(--weave-teal)", marginTop: 2, fontWeight: 700, letterSpacing: "0.04em" }}>
                {hoveredChar.race} · {hoveredChar.class} · {hoveredChar.alignment}
              </div>
              <div style={{ fontSize: 13, color: "rgba(255,255,255,0.7)", marginTop: 6, lineHeight: 1.5, fontStyle: "italic" }}>
                "{hoveredChar.catchphrase}"
              </div>
            </div>
            <button onClick={() => navigate({ name: "character", id: hoveredChar.id })}
                    className="btn"
                    style={{
                      background: "var(--weave-violet-bright)",
                      color: "white",
                      padding: "10px 16px",
                      fontSize: 13
                    }}>
              캐릭터 시트 →
            </button>
          </div>
        )}
      </div>

      {/* Progress strip — how many discovered */}
      <div style={{ position: "relative", maxWidth: 880, margin: "48px auto 0", padding: "0 48px" }}>
        <div style={{
          background: "rgba(255,255,255,0.05)",
          border: "1px solid rgba(255,255,255,0.1)",
          borderRadius: 14,
          padding: "16px 20px",
          display: "flex", alignItems: "center", gap: 16
        }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: "0.08em", fontWeight: 700 }}>도전과제 · 모든 동료의 성향 확인</div>
            <div style={{ marginTop: 8, height: 6, background: "rgba(255,255,255,0.08)", borderRadius: 999 }}>
              <div style={{
                height: "100%",
                width: `${(visited.length / CHARACTERS.length) * 100}%`,
                background: "linear-gradient(90deg, var(--weave-violet-bright), var(--weave-teal))",
                borderRadius: 999,
                transition: "width 300ms"
              }} />
            </div>
          </div>
          <div style={{ fontSize: 13, fontWeight: 700, fontFamily: "var(--font-mono)", color: "white" }}>
            {visited.length} / {CHARACTERS.length}
          </div>
        </div>
      </div>

      {/* Achievement toast */}
      {achievementShown && (
        <div style={{
          position: "fixed",
          top: 32, right: 32,
          background: "linear-gradient(135deg, var(--weave-violet-bright), var(--weave-teal))",
          color: "white", borderRadius: 14, padding: "18px 22px",
          display: "flex", alignItems: "center", gap: 14,
          boxShadow: "0 20px 40px rgba(0,0,0,0.4)",
          maxWidth: 360,
          zIndex: 100,
          animation: "slideInRight 400ms cubic-bezier(0.4,0,0.2,1)"
        }}>
          <div style={{
            width: 44, height: 44,
            background: "rgba(255,255,255,0.18)",
            borderRadius: 99,
            display: "flex", alignItems: "center", justifyContent: "center",
            flexShrink: 0
          }}>
            <Icon name="star-fill" size={22} color="white" />
          </div>
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.08em", opacity: 0.85 }}>ACHIEVEMENT UNLOCKED</div>
            <div style={{ fontSize: 15, fontWeight: 800, marginTop: 2 }}>모든 동료의 성향을 확인했습니다</div>
          </div>
          <button onClick={() => setAchievementShown(false)} style={{ color: "rgba(255,255,255,0.7)", marginLeft: "auto", padding: 4 }}>
            <Icon name="close" size={16} color="rgba(255,255,255,0.7)" />
          </button>
        </div>
      )}

      <style dangerouslySetInnerHTML={{ __html: `
        @keyframes slideInRight {
          from { transform: translateX(120%); opacity: 0; }
          to   { transform: translateX(0); opacity: 1; }
        }
        @keyframes runeFloat {
          0%, 100% { transform: translateY(0) rotate(0deg); }
          50% { transform: translateY(-6px) rotate(2deg); }
        }
      ` }} />
    </div>
  );
}

function CompassLabel({ children }) {
  return (
    <div style={{
      fontSize: 13, fontWeight: 800,
      color: "rgba(255,255,255,0.8)",
      textAlign: "center",
      letterSpacing: "0.06em",
      paddingBottom: 8,
      lineHeight: 1.3
    }}>{children}</div>
  );
}

function CompassRowLabel({ children }) {
  return (
    <div style={{
      fontSize: 13, fontWeight: 800,
      color: "rgba(255,255,255,0.8)",
      letterSpacing: "0.06em",
      display: "flex", alignItems: "center",
      paddingRight: 8,
      lineHeight: 1.3
    }}>{children}</div>
  );
}

function AlignmentCell({ cell, characters, hoveredId, setHoveredId, setHoveredCell, isCenter, navigate }) {
  const chars = (cell.ids || []).map(id => characters.find(c => c.id === id)).filter(Boolean);
  const empty = chars.length === 0;
  const tint = cell.tint;

  return (
    <div style={{
      position: "relative",
      aspectRatio: "1 / 1",
      borderRadius: 16,
      background: empty
        ? "rgba(255,255,255,0.02)"
        : `radial-gradient(circle at 50% 30%, ${tint}26 0%, ${tint}08 60%, transparent 100%), rgba(255,255,255,0.03)`,
      border: empty ? "1px dashed rgba(255,255,255,0.08)" : `1px solid ${tint}40`,
      boxShadow: empty ? "none" : `inset 0 0 30px ${tint}18`,
      overflow: "hidden",
      transition: "border-color 160ms"
    }}>
      {/* Cell label */}
      <div style={{
        position: "absolute", top: 8, left: 12, right: 12,
        fontSize: 10, fontWeight: 800,
        color: empty ? "rgba(255,255,255,0.25)" : tint,
        letterSpacing: "0.1em",
        textTransform: "uppercase",
        textAlign: "center",
        opacity: 0.9
      }}>
        {cell.label}
      </div>

      {/* glow ring */}
      {!empty && (
        <div style={{
          position: "absolute",
          width: 80, height: 80,
          top: "55%", left: "50%",
          transform: "translate(-50%, -50%)",
          background: `radial-gradient(circle, ${tint}40 0%, transparent 60%)`,
          pointerEvents: "none"
        }} />
      )}

      {/* Char busts */}
      <div style={{
        position: "absolute", inset: 0,
        display: "flex", alignItems: "center", justifyContent: "center",
        gap: 8, padding: "28px 12px 12px"
      }}>
        {empty && (
          <div style={{ textAlign: "center" }}>
            <div style={{ fontSize: 22, color: "rgba(255,255,255,0.18)", fontFamily: "var(--font-serif-display)", fontWeight: 800 }}>
              {isCenter ? "·" : ""}
            </div>
            <div style={{ fontSize: 10, color: "rgba(255,255,255,0.3)", letterSpacing: "0.04em", fontStyle: "italic" }}>
              합류 대기
            </div>
          </div>
        )}
        {chars.map(c => (
          <CharBust key={c.id} character={c} active={hoveredId === c.id}
                    onHover={(h) => { setHoveredId(h ? c.id : null); setHoveredCell(h ? cell.key : null); }}
                    onClick={() => navigate({ name: "character", id: c.id })} />
        ))}
      </div>

      {/* Corner runes for non-empty */}
      {!empty && <>
        <RuneTick pos={{ top: 6, left: 6 }} color={tint} />
        <RuneTick pos={{ top: 6, right: 6 }} color={tint} flip />
        <RuneTick pos={{ bottom: 6, left: 6 }} color={tint} flipV />
        <RuneTick pos={{ bottom: 6, right: 6 }} color={tint} flip flipV />
      </>}
    </div>
  );
}

function CharBust({ character, active, onHover, onClick }) {
  return (
    <button onClick={onClick}
            onMouseEnter={() => onHover(true)}
            onMouseLeave={() => onHover(false)}
            className="char-bust"
            style={{
              width: 64, height: 80,
              background: `linear-gradient(180deg, transparent 35%, rgba(0,0,0,0.45) 100%), linear-gradient(135deg, ${character.portraitColors[0]}, ${character.portraitColors[1]})`,
              borderRadius: 10,
              cursor: "pointer", position: "relative", overflow: "hidden",
              border: active ? "2px solid var(--weave-violet-bright)" : "2px solid rgba(255,255,255,0.12)",
              transform: active ? "scale(1.08) translateY(-4px)" : "scale(1)",
              transition: "transform 180ms cubic-bezier(0.4,0,0.2,1), border-color 160ms, box-shadow 160ms",
              boxShadow: active ? "0 12px 24px rgba(125,94,247,0.4), 0 0 0 1px rgba(125,94,247,0.3)" : "none",
              padding: 0
            }}>
      <span style={{
        position: "absolute", top: "50%", left: "50%",
        transform: "translate(-50%, -58%)",
        fontSize: 28, fontWeight: 800,
        fontFamily: "var(--font-serif-display)",
        color: "rgba(255,255,255,0.35)",
        letterSpacing: "-0.04em"
      }}>{character.name[0]}</span>
      <div style={{
        position: "absolute", left: 4, right: 4, bottom: 4,
        fontSize: 9, fontWeight: 800,
        color: "white",
        textAlign: "center",
        letterSpacing: "-0.01em"
      }}>{character.name}</div>
    </button>
  );
}

function RuneTick({ pos, color, flip, flipV }) {
  return (
    <div style={{
      position: "absolute",
      width: 10, height: 10,
      ...pos,
      borderLeft: `1px solid ${color}`,
      borderTop: `1px solid ${color}`,
      transform: `${flip ? "scaleX(-1)" : ""} ${flipV ? "scaleY(-1)" : ""}`,
      opacity: 0.5
    }} />
  );
}

function RuneCorner({ pos, flip }) {
  return (
    <div style={{
      position: "absolute",
      ...pos,
      width: 80, height: 80,
      opacity: 0.18,
      pointerEvents: "none",
      animation: "runeFloat 8s ease-in-out infinite"
    }}>
      <svg width="80" height="80" viewBox="0 0 80 80" style={{ transform: flip ? "scaleX(-1)" : "" }}>
        <circle cx="40" cy="40" r="32" fill="none" stroke="var(--weave-violet-bright)" strokeWidth="1" />
        <circle cx="40" cy="40" r="22" fill="none" stroke="var(--weave-teal)" strokeWidth="1" strokeDasharray="2 3" />
        <path d="M40 8 L46 32 L70 30 L52 46 L62 70 L40 56 L18 70 L28 46 L10 30 L34 32 Z" fill="none" stroke="var(--weave-violet-bright)" strokeWidth="1" />
        <text x="40" y="44" textAnchor="middle" fontSize="9" fill="var(--weave-teal)" fontFamily="ui-monospace, monospace">d20</text>
      </svg>
    </div>
  );
}

window.AlignmentHall = AlignmentHall;
