<script lang="ts">
  import type { Mode, Color, CreateGameResponse } from '@blind-chess/shared';

  // Friend section state.
  let friendMode: Mode = $state('blind');
  let friendSide: Color | 'random' = $state('random');
  let friendHighlight = $state(false);
  let friendCreating = $state(false);
  let friendError: string | null = $state(null);

  // AI section state (separate so user can configure each independently).
  let aiMode: Mode = $state('blind');
  let aiSide: Color | 'random' = $state('random');
  let aiHighlight = $state(false);
  let aiCreating = $state(false);
  let aiError: string | null = $state(null);

  async function createWithFriend() {
    friendCreating = true; friendError = null;
    try {
      const res = await fetch('/api/games', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
          mode: friendMode, side: friendSide, highlightingEnabled: friendHighlight,
        }),
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const json: CreateGameResponse & { creatorColor: Color } = await res.json();
      localStorage.setItem(`bc:${json.gameId}`, json.creatorToken);
      location.hash = `#/g/${json.gameId}`;
    } catch (e) {
      friendError = e instanceof Error ? e.message : String(e);
    } finally {
      friendCreating = false;
    }
  }

  async function createVsCasual() {
    aiCreating = true; aiError = null;
    try {
      const res = await fetch('/api/games', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
          mode: aiMode, side: aiSide, highlightingEnabled: aiHighlight,
          vsAi: { brain: 'casual' },
        }),
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const json: CreateGameResponse & { creatorColor: Color } = await res.json();
      localStorage.setItem(`bc:${json.gameId}`, json.creatorToken);
      location.hash = `#/g/${json.gameId}`;
    } catch (e) {
      aiError = e instanceof Error ? e.message : String(e);
    } finally {
      aiCreating = false;
    }
  }
</script>

<div class="page">
  <div class="hero">
    <h1>blind <span class="accent">chess</span></h1>
    <p class="tagline">A two-player chess variant where each player sees only their own pieces. The server is the moderator.</p>
  </div>

  <div class="card">
    <h2>Play with a friend</h2>
    <p class="card-sub muted">Get a shareable link, send it to someone, play together.</p>

    <div class="field">
      <span class="lbl">Mode</span>
      <div class="opts">
        <label class="opt" class:active={friendMode === 'blind'}>
          <input type="radio" bind:group={friendMode} value="blind" />
          <span class="opt-title">Blind</span>
          <span class="opt-sub">Each player sees only their own pieces.</span>
        </label>
        <label class="opt" class:active={friendMode === 'vanilla'}>
          <input type="radio" bind:group={friendMode} value="vanilla" />
          <span class="opt-title">Vanilla</span>
          <span class="opt-sub">Normal chess. Both players see everything.</span>
        </label>
      </div>
    </div>

    <div class="field">
      <span class="lbl">You play as</span>
      <div class="row">
        <label><input type="radio" bind:group={friendSide} value="w" /> White</label>
        <label><input type="radio" bind:group={friendSide} value="b" /> Black</label>
        <label><input type="radio" bind:group={friendSide} value="random" /> Random</label>
      </div>
    </div>

    <div class="field">
      <label class="toggle">
        <input type="checkbox" bind:checked={friendHighlight} />
        <span>Highlight reachable squares</span>
        {#if friendMode === 'blind'}
          <span class="hint muted">(geometric only — no opponent info)</span>
        {/if}
      </label>
    </div>

    <button class="primary big" disabled={friendCreating} onclick={createWithFriend}>
      {friendCreating ? 'Creating…' : 'Create game'}
    </button>
    {#if friendError}<p class="error">Error: {friendError}</p>{/if}
  </div>

  <div class="card">
    <h2>Play vs computer</h2>
    <p class="card-sub muted">Always-available opponent. No link to share — game starts immediately.</p>

    <div class="field">
      <span class="lbl">Mode</span>
      <div class="opts">
        <label class="opt" class:active={aiMode === 'blind'}>
          <input type="radio" bind:group={aiMode} value="blind" />
          <span class="opt-title">Blind</span>
          <span class="opt-sub">Each player sees only their own pieces.</span>
        </label>
        <label class="opt" class:active={aiMode === 'vanilla'}>
          <input type="radio" bind:group={aiMode} value="vanilla" />
          <span class="opt-title">Vanilla</span>
          <span class="opt-sub">Normal chess. Both players see everything.</span>
        </label>
      </div>
    </div>

    <div class="field">
      <span class="lbl">You play as</span>
      <div class="row">
        <label><input type="radio" bind:group={aiSide} value="w" /> White</label>
        <label><input type="radio" bind:group={aiSide} value="b" /> Black</label>
        <label><input type="radio" bind:group={aiSide} value="random" /> Random</label>
      </div>
    </div>

    <div class="field">
      <label class="toggle">
        <input type="checkbox" bind:checked={aiHighlight} />
        <span>Highlight reachable squares</span>
        {#if aiMode === 'blind'}
          <span class="hint muted">(geometric only — no opponent info)</span>
        {/if}
      </label>
    </div>

    <div class="ai-buttons">
      <button class="primary" disabled={aiCreating} onclick={createVsCasual}>
        {aiCreating ? 'Creating…' : 'Casual bot'}
      </button>
      <button class="secondary" disabled title="Coming soon">
        gemma4 recon (coming soon)
      </button>
    </div>
    <p class="card-sub muted small">
      Casual: fast, plays simple moves, makes mistakes. Good for a quick game.
    </p>
    {#if aiError}<p class="error">Error: {aiError}</p>{/if}
  </div>

  <a class="card card-link" href="/duplicate/">
    <h2>
      Duplicate Chess
      <span class="badge">under development</span>
    </h2>
    <p class="card-sub muted">
      A four-player chess variant invented by Andrew Freiberg. Perfect information —
      every player sees all four boards. Local sandbox; open it and play around.
    </p>
    <span class="open-cue">Open →</span>
  </a>

  <footer class="muted">
    <span class="mono">git.sethpc.xyz/Seth/blind_chess</span>
  </footer>
</div>

<style>
  .page {
    max-width: 540px;
    margin: 0 auto;
    padding: 32px 20px 80px;
    min-height: 100%;
  }
  .hero { text-align: center; margin-bottom: 32px; }
  h1 {
    font-size: 48px;
    font-weight: 800;
    letter-spacing: -0.02em;
    margin: 0 0 12px;
  }
  .accent { color: var(--accent); }
  .tagline {
    color: var(--text-dim);
    font-size: 15px;
    line-height: 1.5;
    max-width: 420px;
    margin: 0 auto;
  }
  .card {
    background: var(--panel);
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 22px;
    margin-bottom: 20px;
  }
  .card-sub { font-size: 13px; margin: -10px 0 16px; }
  .card-sub.small { margin-top: 12px; font-size: 12px; }
  h2 { font-size: 18px; margin: 0 0 8px; }

  .field { margin-bottom: 20px; }
  .lbl {
    display: block;
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    color: var(--text-dim);
    margin-bottom: 8px;
  }

  .opts { display: grid; gap: 8px; }
  .opt {
    display: flex;
    flex-direction: column;
    padding: 12px;
    border: 1px solid var(--border);
    border-radius: 8px;
    cursor: pointer;
    transition: border 0.15s, background 0.15s;
  }
  .opt:hover { border-color: var(--accent-dim); }
  .opt.active { border-color: var(--accent); background: rgba(211,84,0,0.07); }
  .opt input { display: none; }
  .opt-title { font-weight: 600; }
  .opt-sub { color: var(--text-dim); font-size: 13px; margin-top: 2px; }

  .row { display: flex; gap: 16px; flex-wrap: wrap; }
  .row label { display: flex; align-items: center; gap: 6px; cursor: pointer; }

  .toggle { display: flex; align-items: center; gap: 8px; cursor: pointer; flex-wrap: wrap; }
  .hint { font-size: 13px; }

  button.big {
    width: 100%;
    padding: 14px;
    font-size: 16px;
    font-weight: 600;
    margin-top: 8px;
  }

  .ai-buttons { display: grid; gap: 8px; grid-template-columns: 1fr 1fr; }
  @media (max-width: 480px) { .ai-buttons { grid-template-columns: 1fr; } }
  .secondary {
    background: transparent;
    border: 1px solid var(--border);
    color: var(--text-dim);
  }
  .secondary:disabled { cursor: not-allowed; opacity: 0.6; }

  .error { color: #f87171; margin-top: 12px; }
  footer { text-align: center; margin-top: 24px; font-size: 12px; }

  .card-link {
    display: block;
    text-decoration: none;
    color: inherit;
    cursor: pointer;
    transition: border 0.15s, background 0.15s;
  }
  .card-link:hover { border-color: var(--accent-dim); background: rgba(211,84,0,0.05); }
  .card-link h2 { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
  .badge {
    display: inline-block;
    font-size: 11px;
    font-weight: 600;
    letter-spacing: 0.06em;
    text-transform: uppercase;
    padding: 3px 8px;
    border-radius: 999px;
    color: var(--accent);
    background: rgba(211,84,0,0.10);
    border: 1px solid var(--accent-dim);
  }
  .open-cue {
    display: inline-block;
    margin-top: 8px;
    font-size: 13px;
    color: var(--accent);
    font-weight: 600;
  }
</style>
