const { useState, useEffect, useMemo } = React;

// ---------- Go board ----------
function GoBoard({ size = 19, stones, showCoords = true }) {
  const N = size;
  // generate grid lines via SVG
  const pad = 5; // % padding inside SVG viewBox
  const cell = (100 - pad * 2) / (N - 1);
  const lines = [];
  for (let i = 0; i < N; i++) {
    const p = pad + i * cell;
    lines.push(<line key={`h${i}`} x1={pad} y1={p} x2={100 - pad} y2={p} stroke="#3a2810" strokeWidth="0.13" />);
    lines.push(<line key={`v${i}`} x1={p} y1={pad} x2={p} y2={100 - pad} stroke="#3a2810" strokeWidth="0.13" />);
  }
  // star points (hoshi) for 19x19
  const stars = N === 19 ? [3, 9, 15] : N === 13 ? [3, 6, 9] : [2, 4, 6];
  const hoshi = [];
  for (const a of stars) for (const b of stars) {
    hoshi.push(<circle key={`s${a}-${b}`} cx={pad + a * cell} cy={pad + b * cell} r="0.45" fill="#3a2810" />);
  }
  const coordsX = "ABCDEFGHJKLMNOPQRST".slice(0, N).split("");

  return (
    <div className="gr-board-wrap">
      {showCoords && (
        <>
          <div className="gr-coords-top">
            {coordsX.map(c => <span key={`xt${c}`}>{c}</span>)}
          </div>
          <div className="gr-coords-bot">
            {coordsX.map(c => <span key={`xb${c}`}>{c}</span>)}
          </div>
          <div className="gr-coords-left">
            {Array.from({ length: N }, (_, i) => <span key={`yl${i}`}>{i + 1}</span>)}
          </div>
          <div className="gr-coords-right">
            {Array.from({ length: N }, (_, i) => <span key={`yr${i}`}>{i + 1}</span>)}
          </div>
        </>
      )}
      <div className="gr-board">
        <svg className="board-grid" viewBox="0 0 100 100" preserveAspectRatio="none">
          {lines}
          {hoshi}
        </svg>
        {stones.map((s, i) => {
          const x = pad + s.x * cell;
          const y = pad + (N - 1 - s.y) * cell;
          const r = cell * 0.46;
          return (
            <div
              key={i}
              className={`stone ${s.c}`}
              style={{
                left: `${x}%`,
                top: `${y}%`,
                width: `${r * 2}%`,
                height: `${r * 2}%`,
              }}
            />
          );
        })}
      </div>
    </div>
  );
}

// Generate a dense, plausible-looking endgame stone layout
function generateStones() {
  const stones = [];
  const seed = (n) => {
    let s = n;
    return () => {
      s = (s * 9301 + 49297) % 233280;
      return s / 233280;
    };
  };
  const rand = seed(42);
  const placed = new Set();
  const place = (x, y, c) => {
    const k = `${x},${y}`;
    if (placed.has(k)) return;
    if (x < 0 || x > 18 || y < 0 || y > 18) return;
    placed.add(k);
    stones.push({ x, y, c });
  };
  // Build clusters in 4 corners + center fight
  const clusters = [
    { cx: 3, cy: 15, r: 4, density: 0.55 },
    { cx: 15, cy: 15, r: 5, density: 0.6 },
    { cx: 4, cy: 3, r: 4, density: 0.5 },
    { cx: 15, cy: 4, r: 5, density: 0.55 },
    { cx: 9, cy: 9, r: 4, density: 0.45 },
    { cx: 12, cy: 10, r: 3, density: 0.5 },
  ];
  clusters.forEach((cl, idx) => {
    for (let dx = -cl.r; dx <= cl.r; dx++) {
      for (let dy = -cl.r; dy <= cl.r; dy++) {
        const x = cl.cx + dx, y = cl.cy + dy;
        if (Math.abs(dx) + Math.abs(dy) > cl.r + 1) continue;
        if (rand() < cl.density) {
          const c = rand() < 0.5 ? "b" : "w";
          place(x, y, c);
        }
      }
    }
  });
  // Add a few isolated stones
  for (let i = 0; i < 12; i++) {
    place(Math.floor(rand() * 19), Math.floor(rand() * 19), rand() < 0.5 ? "b" : "w");
  }
  return stones;
}

// ---------- Icons ----------
const BrandMark = (props) => (
  <svg viewBox="0 0 40 40" className="brand-mark" {...props}>
    <circle cx="20" cy="20" r="18.5" fill="none" stroke="#15110a" strokeWidth="1.4" />
    <path
      d="M20 1.5
         A 9.25 9.25 0 0 1 20 20
         A 9.25 9.25 0 0 0 20 38.5
         A 18.5 18.5 0 0 1 20 1.5 Z"
      fill="#15110a"
    />
  </svg>
);

const Icon = {
  Arrow: (p) => <svg className="btn-arrow" {...p} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M3 8h10M9 4l4 4-4 4"/></svg>,
  Play: (p) => <svg {...p} viewBox="0 0 16 16" fill="currentColor"><path d="M5 3.5v9l7-4.5z"/></svg>,
  Bolt: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M13 2L4 14h7l-1 8 9-12h-7l1-8z"/></svg>,
  Trophy: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M8 21h8M12 17v4M7 4h10v4a5 5 0 0 1-10 0V4zM17 5h3v3a3 3 0 0 1-3 3M7 5H4v3a3 3 0 0 0 3 3"/></svg>,
  Eye: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></svg>,
  Book: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20V3H6.5A2.5 2.5 0 0 0 4 5.5v14zM4 19.5A2.5 2.5 0 0 0 6.5 22H20"/></svg>,
  Users: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="9" cy="8" r="3.2"/><path d="M3 20c0-3.3 2.7-6 6-6s6 2.7 6 6"/><circle cx="17" cy="9" r="2.5"/><path d="M15 14c1-.6 2-1 3-1 2.8 0 5 2.2 5 5"/></svg>,
  Send: (p) => <svg {...p} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"><path d="M2 8l12-5-5 12-2-5-5-2z"/></svg>,
  Skip: (dir, p) => <svg {...p} viewBox="0 0 16 16" fill="currentColor">{dir === "back" ? <><path d="M3 4h1.5v8H3zM13 4l-7 4 7 4z"/></> : <><path d="M11.5 4H13v8h-1.5zM3 4l7 4-7 4z"/></>}</svg>,
  StepBack: (p) => <svg {...p} viewBox="0 0 16 16" fill="currentColor"><path d="M11 4l-5 4 5 4zM4 4h1v8H4z"/></svg>,
  StepFwd: (p) => <svg {...p} viewBox="0 0 16 16" fill="currentColor"><path d="M5 4l5 4-5 4zM11 4h1v8h-1z"/></svg>,
  Reset: (p) => <svg {...p} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"><path d="M3 8a5 5 0 1 0 5-5"/><path d="M3 3v3h3"/></svg>,
  Bars: (p) => <svg {...p} viewBox="0 0 16 16" fill="currentColor"><rect x="2" y="9" width="2.5" height="5"/><rect x="6.75" y="6" width="2.5" height="8"/><rect x="11.5" y="3" width="2.5" height="11"/></svg>,
  Grid: (p) => <svg {...p} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4"><rect x="2" y="2" width="12" height="12" rx="1.5"/><path d="M2 6h12M2 10h12M6 2v12M10 2v12"/></svg>,
  List: (p) => <svg {...p} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"><path d="M3 4h10M3 8h10M3 12h10"/></svg>,
  Chat: (p) => <svg {...p} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"><path d="M2 11.5V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1H6l-4 2.5z"/></svg>,
  Twitter: (p) => <svg {...p} viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>,
  Discord: (p) => <svg {...p} viewBox="0 0 24 24" fill="currentColor"><path d="M20.317 4.37a19.79 19.79 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.249a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.249.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128c.126-.094.252-.192.372-.291a.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.009c.12.099.246.198.373.292a.077.077 0 0 1-.006.127c-.598.349-1.22.645-1.873.891a.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.84 19.84 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.331c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z"/></svg>,
  Youtube: (p) => <svg {...p} viewBox="0 0 24 24" fill="currentColor"><path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z"/></svg>,
  Github: (p) => <svg {...p} viewBox="0 0 24 24" fill="currentColor"><path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0 0 24 12c0-6.63-5.37-12-12-12z"/></svg>,
};

// ---------- Game Room mock ----------
function GameRoom({ showCoords }) {
  const stones = useMemo(() => generateStones(), []);
  return (
    <div className="gameroom">
      <div className="gr-top">
        <div className="gr-tag"><span className="gr-dot" /> Game Room</div>
        <div className="gr-tabs">
          <div className="gr-tab active"><Icon.Grid /> Board</div>
          <div className="gr-tab"><Icon.List /> Move List</div>
          <div className="gr-tab"><Icon.Chat /> Chat</div>
        </div>
      </div>

      {/* Left side */}
      <div className="gr-side">
        <div className="gr-player">
          <div className="gr-pavatar" />
          <div>
            <div className="gr-pname">HanaKim</div>
            <div className="gr-prank">3d</div>
          </div>
        </div>
        <div className="gr-pmeta"><span className="gr-stone b" /> 1857</div>
        <div className="gr-clock">
          <div className="t">28<span className="colon">:</span>47</div>
          <div className="sub">2 × 30 sec</div>
        </div>
        <div className="gr-divider" />
        <div className="gr-cap">
          <div>Captured</div>
          <div className="gr-cap-row">
            <div className="gr-cap-stones">
              <span className="gr-cap-stone b" /><span className="gr-cap-stone b" /><span className="gr-cap-stone b" /><span className="gr-cap-stone b" />
            </div>
            <span style={{ color: "var(--ink)", fontWeight: 600 }}>5</span>
          </div>
          <div className="gr-cap-row">
            <div className="gr-cap-stones">
              <span className="gr-cap-stone w" /><span className="gr-cap-stone w" />
            </div>
            <span style={{ color: "var(--ink)", fontWeight: 600 }}>2</span>
          </div>
        </div>
        <div className="gr-divider" />
        <div className="gr-player">
          <div className="gr-pavatar p2" />
          <div>
            <div className="gr-pname">ZenMaster</div>
            <div className="gr-prank">3d</div>
          </div>
        </div>
        <div className="gr-pmeta"><span className="gr-stone w" /> 1874</div>
        <div className="gr-clock">
          <div className="t">24<span className="colon">:</span>13</div>
          <div className="sub">2 × 30 sec</div>
        </div>
      </div>

      {/* Board */}
      <GoBoard size={19} stones={stones} showCoords={showCoords} />

      {/* Right side */}
      <div className="gr-side right">
        <div className="gr-movelist">
          <div className="gr-movelist-head"><span>#</span><span>Black</span><span>White</span></div>
          {[
            ["121", "Q4", "D4"], ["122", "R4", "C4"], ["123", "P3", "D3"],
            ["124", "O3", "D2"], ["125", "Q3", "C3"], ["126", "R3", "P16"],
            ["127", "N17", "C16"], ["128", "Q16", "D16"], ["129", "P17", "E16"],
            ["130", "R17", "F16"], ["131", "Q17", "Pass"],
          ].map((r, i) => (
            <div key={i} className="gr-movelist-row"><span className="num">{r[0]}</span><span>{r[1]}</span><span>{r[2]}</span></div>
          ))}
        </div>
        <div className="gr-turn"><span className="gr-stone b" /> Black to play</div>
        <div className="gr-chat">
          <div className="gr-chat-msg">
            <div className="gr-chat-avatar" />
            <div>
              <div className="gr-chat-name">HanaKim</div>
              <div className="gr-chat-text">Great move!</div>
            </div>
            <div className="gr-chat-time">10:21</div>
          </div>
          <div className="gr-chat-msg">
            <div className="gr-chat-avatar p2" />
            <div>
              <div className="gr-chat-name">ZenMaster</div>
              <div className="gr-chat-text">Thank you!</div>
            </div>
            <div className="gr-chat-time">10:22</div>
          </div>
          <div className="gr-chat-msg">
            <div className="gr-chat-avatar" />
            <div>
              <div className="gr-chat-name">HanaKim</div>
              <div className="gr-chat-text">This is getting exciting.</div>
            </div>
            <div className="gr-chat-time">10:23</div>
          </div>
          <div className="gr-input"><span>Say something…</span><Icon.Send /></div>
        </div>
      </div>

      {/* Bottom controls */}
      <div className="gr-bottom">
        <div className="gr-controls">
          <button className="gr-ctrl"><Icon.Skip dir="back" /></button>
          <button className="gr-ctrl"><Icon.StepBack /></button>
          <button className="gr-ctrl"><Icon.Reset /></button>
          <button className="gr-ctrl"><Icon.StepFwd /></button>
          <button className="gr-ctrl"><Icon.Skip dir="fwd" /></button>
          <span className="gr-ctrl live">Live</span>
        </div>
        <div className="gr-actions">
          <button className="gr-action danger">Resign</button>
          <button className="gr-action">Pass</button>
          <button className="gr-action dark"><Icon.Bars /> Review</button>
        </div>
      </div>
    </div>
  );
}

// ---------- Page ----------
function Page() {
  const [t, setTweak] = useTweaks(window.TWEAKS_DEFAULTS || { accentHue: 70, headlineWeight: 500, showBoardCoords: true });

  return (
    <div className="page">
      {/* NAV */}
      <nav className="nav">
        <div className="brand">
          <BrandMark />
          <span>Niwa</span>
        </div>
        <div className="nav-links">
          <a href="#">Play</a>
          <a href="#">Tournaments</a>
          <a href="#">Puzzles</a>
          <a href="#">Community</a>
        </div>
        <div className="nav-cta">
          <a href="Player Dashboard.html" className="btn btn-primary" onClick={(event) => window.NiwaMetrics?.trackThenNavigate(event, "clickstartplaying", "Player Dashboard.html")}>Start Playing</a>
        </div>
      </nav>

      {/* HERO */}
      <section className="hero">
        <div className="hero-text" style={{ position: "relative", zIndex: 1 }}>
          <h1 style={{ fontWeight: t.headlineWeight }}>
            A beautiful place<br />
            <span style={{ whiteSpace: "nowrap" }}>to play <span className="accent">Go</span> online.</span>
          </h1>
          <p className="lede">
            Play live or by correspondence. Compete in ranked games and tournaments.
            Review, learn, and connect with the global Go community.
          </p>
          <div className="hero-ctas">
            <a href="Player Dashboard.html" className="btn btn-primary btn-hero" onClick={(event) => window.NiwaMetrics?.trackThenNavigate(event, "clickstartplaying", "Player Dashboard.html")}>Start Playing <Icon.Arrow /></a>
            <a href="Live Games.html?autowatch=1" className="btn btn-ghost btn-hero" onClick={(event) => window.NiwaMetrics?.trackThenNavigate(event, "clickwatchalivegame", "Live Games.html?autowatch=1")}><Icon.Play /> Watch a Live Game</a>
          </div>
        </div>
        <div className="hero-art">
          <img src="uploads/gameroom.png" alt="Niwa Game Room" style={{ display: "block", width: "100%", height: "auto" }} />
        </div>
      </section>

      {/* TWEAKS PANEL */}
      <TweaksPanel title="Tweaks">
        <TweakSection label="Hero">
          <TweakSlider label="Headline weight" min={300} max={700} step={100} value={t.headlineWeight} onChange={v => setTweak("headlineWeight", v)} />
        </TweakSection>
        <TweakSection label="Board">
          <TweakToggle label="Show coordinates" value={t.showBoardCoords} onChange={v => setTweak("showBoardCoords", v)} />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

// expose tweak defaults globally so script-tag order is robust
window.TWEAKS_DEFAULTS = { accentHue: 70, headlineWeight: 500, showBoardCoords: true };

ReactDOM.createRoot(document.getElementById("root")).render(<Page />);
