import { expect, test, type Page } from './fixtures';

// Social / account / history surfaces against the mock transport (no backend).
// The mock profile is a durable account, so friends, invitations, stats and the GCG
// export are reachable from the seeded fixture.

async function loginLobby(page: Page): Promise<void> {
  await page.goto('/');
  await page.getByRole('button', { name: /guest/i }).click();
  await expect(page.getByText('Your turn')).toBeVisible();
}

// The Settings hub (the lobby ⚙️ tab) hosts Settings / Profile / Friends / About as in-place
// tabs; the back control always returns to the lobby. Tabs are icon-only with an aria-label.
async function openSettingsTab(page: Page, tab: 'Profile' | 'Friends' | 'Info'): Promise<void> {
  await page.getByRole('button', { name: /Settings/ }).click(); // lobby ⚙️ tab
  await expect(page.locator('.pane')).toHaveCount(1); // let the slide settle
  await page.getByRole('button', { name: tab, exact: true }).click();
}
function openFriends(page: Page): Promise<void> {
  return openSettingsTab(page, 'Friends');
}
function openProfile(page: Page): Promise<void> {
  return openSettingsTab(page, 'Profile');
}

test('friends: issue a code, accept an incoming request, redeem a code', async ({ page }) => {
  await loginLobby(page);
  await openFriends(page);

  // Issue a one-time code — it is shown to share, with a copy control.
  await page.getByRole('button', { name: /Show my code/i }).click();
  await expect(page.getByTestId('friend-code')).toContainText('246813');
  await expect(page.getByRole('button', { name: 'Copy' })).toBeVisible();

  // The seeded incoming request (Rick) can be accepted; the requests section clears.
  await expect(page.getByText('Friend requests')).toBeVisible();
  await page.getByRole('button', { name: /^Accept$/ }).click();
  await expect(page.getByText('Friend requests')).toBeHidden();

  // Redeeming a code adds a new friend to the list.
  await page.locator('.codein').fill('111111');
  await page.getByRole('button', { name: /^Add$/ }).click();
  await expect(page.locator('.who', { hasText: 'Friend 111111' })).toBeVisible();
});

test('friends: the row kebab reveals block/remove and an outside tap closes it', async ({ page }) => {
  await loginLobby(page);
  await openFriends(page);

  // A friend row slides open on its kebab (like the lobby), exposing two icon actions.
  const kaya = page.locator('.rowwrap', { hasText: 'Kaya' });
  await kaya.locator('.kebab').click();
  await expect(kaya).toHaveClass(/revealed/);
  await expect(kaya.locator('.acts').getByRole('button', { name: 'Block' })).toBeVisible();
  await expect(kaya.locator('.acts').getByRole('button', { name: 'Remove' })).toBeVisible();

  // A tap anywhere outside the action buttons collapses the row again.
  await page.getByRole('heading', { name: 'Your friends' }).click();
  await expect(kaya).not.toHaveClass(/revealed/);
});

test('friends: blocking from the list confirms (naming the friend) and moves them to Blocked', async ({ page }) => {
  await loginLobby(page);
  await openFriends(page);

  const kaya = page.locator('.rowwrap', { hasText: 'Kaya' });
  await kaya.locator('.kebab').click();
  await kaya.locator('.acts').getByRole('button', { name: 'Block' }).click();

  // The confirmation keeps a generic title and names the friend in the body.
  const dialog = page.getByRole('dialog');
  await expect(dialog.getByText('Block this player?')).toBeVisible();
  await expect(dialog.locator('.confirm-name')).toHaveText('Kaya');
  await dialog.getByRole('button', { name: 'Block' }).click();

  // The block applied: Kaya leaves the friends list and shows under Blocked players.
  await expect(page.getByText('No friends yet.')).toBeVisible();
  const blocked = page.locator('.rowwrap', { hasText: 'Kaya' });
  await expect(blocked.getByRole('button', { name: 'Unblock' })).toBeVisible();
});

test('friends: removing from the list confirms (naming the friend) and drops them', async ({ page }) => {
  await loginLobby(page);
  await openFriends(page);

  const kaya = page.locator('.rowwrap', { hasText: 'Kaya' });
  await kaya.locator('.kebab').click();
  await kaya.locator('.acts').getByRole('button', { name: 'Remove' }).click();

  const dialog = page.getByRole('dialog');
  await expect(dialog.getByText('Remove from friends?')).toBeVisible();
  await expect(dialog.locator('.confirm-name')).toHaveText('Kaya');
  await dialog.getByRole('button', { name: 'Remove' }).click();

  // Unfriending just drops the friendship — Kaya is gone and not blocked.
  await expect(page.getByText('No friends yet.')).toBeVisible();
  await expect(page.locator('.rowwrap', { hasText: 'Kaya' })).toHaveCount(0);
});

test('invitations: the lobby shows an invitation and accepting clears it', async ({ page }) => {
  await loginLobby(page);
  await expect(page.getByText('Invitations')).toBeVisible();
  await expect(page.getByText(/From Kaya/)).toBeVisible();
  await expect(page.getByText('One word per turn')).toBeVisible(); // the single-word-rule line on the card
  await page.getByRole('button', { name: /^Accept$/ }).click();
  await expect(page.getByText(/From Kaya/)).toBeHidden();
});

test('stats screen shows the metrics and the per-variant best move', async ({ page }) => {
  await loginLobby(page);
  await page.getByRole('button', { name: /Stats/ }).click();
  await expect(page.getByText('Win rate')).toBeVisible();
  await expect(page.getByText('Best move')).toBeVisible();
  // The Moves count and the derived Hint share (12 hints / 248 plays = 4.8%, one decimal).
  await expect(page.getByText('Moves', { exact: true })).toBeVisible();
  await expect(page.getByText('Hint share')).toBeVisible();
  await expect(page.getByText('4.8%')).toBeVisible();
  // The best move breaks down per played variant, each row labelled by the variant and
  // ending in the play's score (the word itself renders as game tiles).
  await expect(page.getByText('Scrabble', { exact: true })).toBeVisible();
  await expect(page.getByText('134')).toBeVisible();
});

test('settings hub: tabs switch in place and back returns to the lobby', async ({ page }) => {
  await loginLobby(page);
  await page.getByRole('button', { name: /Settings/ }).click(); // lobby ⚙️ tab
  await expect(page.locator('.pane')).toHaveCount(1);
  await expect(page.locator('.seg').first()).toBeVisible(); // default Settings tab

  // Switching tabs is in place (no navigation): the Friends body appears, still one pane.
  await page.getByRole('button', { name: 'Friends', exact: true }).click();
  await expect(page.getByText('Friend requests')).toBeVisible();
  await expect(page.locator('.pane')).toHaveCount(1);

  await page.getByRole('button', { name: 'Info', exact: true }).click();
  await expect(page.getByText(/Version/)).toBeVisible();

  // Back returns to the lobby from any tab.
  await page.locator('.back').click();
  await expect(page.getByText('Your turn')).toBeVisible();
});

test('profile edit saves a new display name', async ({ page }) => {
  await loginLobby(page);
  await openProfile(page);
  await page.locator('.edit input').first().fill('Kaya Test');
  await page.getByRole('button', { name: /^Save$/ }).click();
  await expect(page.locator('.name')).toHaveText('Kaya Test');
});

test('GCG export appears only for a finished game', async ({ page }) => {
  await loginLobby(page);
  // The finished game vs Kaya exposes export 📤 in the history header.
  await page.getByRole('button', { name: /Kaya/ }).click();
  await page.locator('.scoreboard').click(); // open the history
  await expect(page.getByRole('button', { name: 'Export GCG' })).toBeVisible();
});

test('GCG export is hidden for an active game', async ({ page }) => {
  await loginLobby(page);
  await page.getByRole('button', { name: /Ann/ }).click();
  await page.locator('.scoreboard').click(); // open the history (shows 🏁 leave, not 📤 export)
  await expect(page.getByRole('button', { name: 'Export GCG' })).toHaveCount(0);
});

test('finished game draws an inert footer and trims live-only controls', async ({ page }) => {
  await loginLobby(page);
  await page.getByRole('button', { name: /Kaya/ }).click(); // finished game vs Kaya
  await expect(page.locator('[data-cell]').first()).toBeVisible();
  // The footer (tab bar) is drawn but its controls are disabled in a finished game.
  await expect(page.locator('.tab').first()).toBeDisabled();
  // The history header offers Export GCG, not Drop game, once the game is over.
  await page.locator('.scoreboard').click();
  await expect(page.getByRole('button', { name: 'Export GCG' })).toBeVisible();
  await expect(page.getByRole('button', { name: 'Drop game' })).toHaveCount(0);
  // The comms hub offers Chat only — the Dictionary tab is hidden for a finished game.
  await page.getByRole('button', { name: 'Chat' }).click(); // 💬
  await expect(page.locator('.pane')).toHaveCount(1);
  await expect(page.getByRole('button', { name: 'Dictionary' })).toHaveCount(0);
  // A finished game is read-only: neither the message field nor the nudge is offered.
  await expect(page.getByRole('button', { name: 'Send' })).toHaveCount(0);
  await expect(page.getByRole('button', { name: 'Nudge' })).toHaveCount(0);
});

test('lobby: hiding a finished game removes it (kebab → ❌), keeping the others', async ({ page }) => {
  await loginLobby(page);

  // Both seeded finished games are listed; the active row carries the inert chevron, not a kebab.
  await expect(page.locator('.rowwrap', { hasText: 'Kaya' })).toBeVisible();
  await expect(page.locator('.rowwrap', { hasText: 'Rick' })).toBeVisible();
  const annRow = page.locator('.rowwrap', { hasText: 'Ann' });
  await expect(annRow.locator('.kebab')).toHaveCount(0);
  await expect(annRow.locator('.chev')).toBeVisible();

  // The kebab reveals the delete action in place (no dropdown menu); tapping ❌ hides the game.
  const kayaRow = page.locator('.rowwrap', { hasText: 'Kaya' });
  await kayaRow.locator('.kebab').click();
  await expect(kayaRow).toHaveClass(/revealed/);
  await kayaRow.locator('.del').click();

  // The hidden game is gone from the list; the other finished game remains.
  await expect(page.locator('.rowwrap', { hasText: 'Kaya' })).toHaveCount(0);
  await expect(page.locator('.rowwrap', { hasText: 'Rick' })).toBeVisible();
});

test('lobby: the active-row chevron opens the game (not a no-op)', async ({ page }) => {
  await loginLobby(page);
  // The inert-looking '>' on an active row is a tap target that opens the game, like the row.
  await page.locator('.rowwrap', { hasText: 'Ann' }).locator('.chev').click();
  await expect(page.locator('[data-cell]').first()).toBeVisible();
});

test('lobby ⚙️ tab shows the pending friend-request count', async ({ page }) => {
  await loginLobby(page);
  // The ⚙️ badge counts incoming friend requests only (Rick = 1); invitations have their
  // own lobby section, so they are not summed into it.
  await expect(page.getByRole('button', { name: /Settings/ }).locator('.badge')).toHaveText('1');
});

test('play with friends: a game type is required to send an invitation', async ({ page }) => {
  await loginLobby(page);
  await page.getByRole('button', { name: /🎲/ }).click(); // lobby tab bar (New Game tab, by its 🎲 icon — the label is themeable)
  await page.getByRole('button', { name: 'Play with friends' }).click();

  const send = page.getByRole('button', { name: 'Send invitation' });
  await expect(send).toBeDisabled();

  await page.getByRole('checkbox').first().check(); // pick a friend
  await expect(send).toBeDisabled(); // still no game type

  await page.locator('.field select').first().selectOption('scrabble_en');
  await expect(send).toBeEnabled();

  await send.click(); // the mock creates it and returns to the lobby
  await expect(page.getByText('Your turn')).toBeVisible();
});

test('game: the add-friend 🤝 confirms with a tap and then reads as sent', async ({ page }) => {
  await loginLobby(page);
  await page.getByRole('button', { name: /Ann/ }).click(); // active game vs Ann
  await page.locator('.scoreboard').click(); // open the history -> 🤝 appears on Ann's card
  const add = page.getByRole('button', { name: 'Add to friends' });
  await add.click(); // arm: 🤝 -> a fading ✅
  await add.click(); // tap the ✅ to confirm within the window
  // The request is sent, so the control is now disabled.
  await expect(add).toBeDisabled();
});

test('game: the block ✖️ confirms in red, then hides both controls and strikes the name', async ({ page }) => {
  await loginLobby(page);
  await page.getByRole('button', { name: /Ann/ }).click(); // active game vs Ann
  await page.locator('.scoreboard').click(); // open the history -> 🤝 and ✖️ appear on Ann's card
  const block = page.getByRole('button', { name: 'Block player' });
  await expect(block).toBeVisible();
  await block.click(); // arm: ✖️ -> a fading ✅, the score caption turns to a red "Block?"
  await expect(page.locator('.sc.blockprompt')).toHaveText('Block?');
  // While confirming a block the add-friend control is hidden so the two never overlap.
  await expect(page.getByRole('button', { name: 'Add to friends' })).toHaveCount(0);
  await block.click(); // confirm within the window
  // The block applied (optimistically): both controls disappear and the name is struck.
  await expect(page.getByRole('button', { name: 'Block player' })).toHaveCount(0);
  await expect(page.getByRole('button', { name: 'Add to friends' })).toHaveCount(0);
  await expect(page.locator('.nm.struck')).toBeVisible();

  // The chat composer is hidden for a blocked opponent — only the log remains, as in a
  // finished game.
  await page.getByRole('button', { name: 'Chat' }).click(); // 💬 -> comms hub
  await expect(page.getByRole('button', { name: 'Send' })).toHaveCount(0);
  await expect(page.getByRole('button', { name: 'Nudge' })).toHaveCount(0);
});

test('game: an opponent who is already a friend shows no add-friend 🤝', async ({ page }) => {
  await loginLobby(page);
  await page.getByRole('button', { name: /Kaya/ }).click(); // finished game vs Kaya, a seeded friend
  await page.locator('.scoreboard').click(); // open the history
  // Kaya is already a friend, so no add-friend control is offered on her card.
  await expect(page.getByRole('button', { name: 'Add to friends' })).toHaveCount(0);
});

test('profile edit disables Save and flags an invalid display name', async ({ page }) => {
  await loginLobby(page);
  await openProfile(page);

  const name = page.locator('.edit input').first();
  const save = page.getByRole('button', { name: /^Save$/ });
  await name.fill('Bad__Name'); // adjacent specials — invalid
  await expect(save).toBeDisabled();
  await expect(name).toHaveClass(/invalid/);

  await name.fill('Good Name');
  await expect(save).toBeEnabled();
});

// Account linking is hidden in Profile.svelte while we target provider sign-in (the anonymous
// /app/ guest who upgrades by linking comes later). The flow is kept wired; re-enable these two
// specs together with the `.emailbox` section.
test.skip('link account: a taken email opens the irreversible merge confirmation', async ({ page }) => {
  await loginLobby(page);
  await openProfile(page);

  // The linking section is shown to everyone (guests upgrade by linking).
  await expect(page.getByRole('heading', { name: 'Link an account' })).toBeVisible();
  // An address containing "merge" stands in (in the mock) for one already owned by
  // another account, so the confirm step reveals a required merge.
  await page.locator('.emailbox input[type="email"]').fill('merge@example.com');
  await page.getByRole('button', { name: 'Send code' }).click();
  await page.locator('.emailbox .codein').fill('123456');
  await page.getByRole('button', { name: 'OK' }).click();

  // The reveal happens only after the code, and names the other account.
  await expect(page.getByText('Merge accounts?')).toBeVisible();
  await expect(page.getByText(/Ann/)).toBeVisible();
  await page.getByRole('button', { name: 'Merge' }).click();
  await expect(page.getByText('Merge accounts?')).toBeHidden();
});

test.skip('link account: the Telegram web sign-in control is offered in a browser', async ({ page }) => {
  await loginLobby(page);
  await openProfile(page);
  await expect(page.getByRole('button', { name: 'Link Telegram' })).toBeVisible();
});

test('chat: one message per turn — the field shows, then a caption replaces it after sending', async ({ page }) => {
  await loginLobby(page);
  await page.getByRole('button', { name: /Ann/ }).click(); // g1: your turn
  await page.locator('.scoreboard').click(); // open the history
  await page.getByRole('button', { name: 'Chat' }).click(); // 💬 -> comms hub
  await expect(page.locator('.pane')).toHaveCount(1);
  // On your turn the message field + Send are shown and the nudge is hidden;
  // chat and nudge are mutually exclusive by turn. Icon-only controls expose their action
  // through the aria-label.
  await expect(page.getByRole('button', { name: 'Send' })).toBeVisible();
  await expect(page.getByRole('button', { name: 'Nudge' })).toHaveCount(0);
  // The limit is one message per turn: after sending, the field is hidden behind a caption.
  // It is still your turn, so the nudge does not appear either.
  await page.getByPlaceholder(/Quick message/).fill('hi there');
  await page.getByRole('button', { name: 'Send' }).click();
  await expect(page.getByText('You can write again next turn.')).toBeVisible();
  await expect(page.getByRole('button', { name: 'Send' })).toHaveCount(0);
  await expect(page.getByRole('button', { name: 'Nudge' })).toHaveCount(0);
});
