// SMASH mobile — five core screens.
// Each takes a `nav` callback so the host App can route between them.

const PLAYERS = [
{ id: 'anton', name: 'Антон Кравцов', area: 'Хамовники', distance: '1,2 км', ntrp: '3.5', lastSeen: '2 ч' },
{ id: 'dmitry', name: 'Дмитрий Шалимов', area: 'Лужники', distance: '2,8 км', ntrp: '4.0', lastSeen: 'сейчас' },
{ id: 'anna', name: 'Анна Левчук', area: 'Крылатское', distance: '4,4 км', ntrp: '3.5', lastSeen: 'вчера', tone: 'yellow' },
{ id: 'lev', name: 'Лев Гордеев', area: 'Хамовники', distance: '0,9 км', ntrp: '4.5', lastSeen: '12 мин', tone: 'ink' },
{ id: 'marina', name: 'Марина Кириллова', area: 'Замоскворечье', distance: '3,1 км', ntrp: '3.0', lastSeen: '1 ч', tone: 'cream' },
{ id: 'igor', name: 'Игорь Тарасов', area: 'Лужники', distance: '2,9 км', ntrp: '4.0', lastSeen: '40 мин' }];


// ──────────────────────────────────────────────────────────────────────────
// Discover
// ──────────────────────────────────────────────────────────────────────────
function DiscoverScreen({ nav }) {
  const filters = ['NTRP 3.0–4.0', '< 5 км', 'Этой неделей', 'Утро'];
  return (
    <div>
      <AppHeader
        title="Discover"
        sub="12 игроков твоего уровня в Хамовниках"
        right={<>{Icon.filter(22)}{Icon.pin(22)}</>} />
      

      {/* Filter chips row */}
      <div style={{
        display: 'flex', gap: 8, padding: '4px 20px 16px',
        overflowX: 'auto'
      }}>
        {filters.map((f, i) =>
        <div key={f} style={{
          padding: '7px 12px',
          background: i === 0 ? SMASH.green : SMASH.cream,
          color: i === 0 ? SMASH.yellow : SMASH.ink,
          fontSize: 12.5, fontWeight: 500,
          borderRadius: 9999,
          whiteSpace: 'nowrap'
        }}>{f}</div>
        )}
      </div>

      {/* Featured / highlight card */}
      <div style={{ padding: '0 20px 16px' }}>
        <Card style={{ padding: 0, overflow: 'hidden', background: SMASH.green, border: 'none' }}>
          <CourtBackdrop height={120} />
          <div style={{ padding: '14px 16px 16px', color: SMASH.off }}>
            <Label color={SMASH.green200}>Подбор недели</Label>
            <div style={{ ...{
                fontFamily: SMASH.fontDisplay, fontWeight: 700, fontSize: 28,
                letterSpacing: '-0.5px', marginTop: 6, marginBottom: 4
              }, fontFamily: "\"Bebas Neue\"" }}>3 партнёра рядом</div>
            <div style={{ fontSize: 13, color: SMASH.green200, marginBottom: 12 }}>
              NTRP 3.5 в Хамовниках. Свободны Сб утром.
            </div>
            <Button kind="onDark" onClick={() => nav('player', 'anton')}>Смотреть</Button>
          </div>
        </Card>
      </div>

      <SectionHead action="Все">Игроки рядом</SectionHead>
      <div>
        {PLAYERS.map((p, i) =>
        <React.Fragment key={p.id}>
            <PlayerRow player={p} onTap={() => nav('player', p.id)} />
            {i < PLAYERS.length - 1 && <Divider inset={20} />}
          </React.Fragment>
        )}
      </div>
      <div style={{ height: 16 }} />
    </div>);

}

// ──────────────────────────────────────────────────────────────────────────
// Player Profile
// ──────────────────────────────────────────────────────────────────────────
function PlayerProfileScreen({ nav, playerId }) {
  const p = PLAYERS.find((x) => x.id === playerId) || PLAYERS[0];
  return (
    <div>
      <AppHeader
        title={null}
        left={<div onClick={() => nav('discover')}>{Icon.back(24)}</div>}
        right={<>{Icon.share(22)}{Icon.more(22)}</>} />
      

      {/* Hero */}
      <div style={{ padding: '0 20px 20px', textAlign: 'left' }}>
        <Avatar name={p.name} size={88} tone={p.tone || 'green'} />
        <div style={{ ...{
            fontFamily: SMASH.fontDisplay, fontWeight: 700, fontSize: 36,
            letterSpacing: '-0.03em', lineHeight: 1.05,
            color: SMASH.black, marginTop: 16
          }, fontFamily: "\"Bebas Neue\"" }}>{p.name.split(' ')[0].toUpperCase()}<br />{p.name.split(' ')[1]?.toUpperCase()}</div>
        <div style={{ fontSize: 14, color: SMASH.slate, marginTop: 8, display: 'flex', alignItems: 'center', gap: 6 }}>
          {Icon.pin(15)} {p.area} · {p.distance}
        </div>
      </div>

      {/* NTRP block */}
      <div style={{ padding: '0 20px 8px' }}>
        <Card style={{
          background: SMASH.green, border: 'none',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between'
        }}>
          <div>
            <Label color={SMASH.green200}>NTRP уровень</Label>
            <div style={{
              fontFamily: SMASH.fontMono, fontSize: 48, fontWeight: 500,
              color: SMASH.yellow, letterSpacing: '-1px', lineHeight: 1, marginTop: 4
            }}>{p.ntrp}</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <Label color={SMASH.green200}>За 30 дней</Label>
            <div style={{
              fontFamily: SMASH.fontMono, fontSize: 18, fontWeight: 500,
              color: SMASH.green200, marginTop: 6
            }}>+0,15 ▲</div>
          </div>
        </Card>
      </div>

      {/* Stats */}
      <div style={{ padding: '12px 20px 0' }}>
        <Label>Статистика</Label>
        <div style={{ marginTop: 4 }}>
          <StatRow label="Матчей в SMASH" value="24" mono />
          <StatRow label="Победы" value="14 — 10" mono color={SMASH.green400} />
          <StatRow label="Серия побед" value="3" mono color={SMASH.green400} />
          <StatRow label="Последний матч" value="3 дня назад" />
          <StatRow label="Любимый корт" value="Лужники · корт 4" />
        </div>
      </div>

      {/* CTAs */}
      <div style={{ padding: '24px 20px 24px', display: 'flex', gap: 10 }}>
        <Button kind="primary" full onClick={() => nav('chat', p.id)}>Написать</Button>
        <Button kind="secondary" onClick={() => nav('invite', p.id)}>Match invite</Button>
      </div>
    </div>);

}

// ──────────────────────────────────────────────────────────────────────────
// Chat
// ──────────────────────────────────────────────────────────────────────────
function ChatScreen({ nav, playerId }) {
  const p = PLAYERS.find((x) => x.id === playerId) || PLAYERS[0];

  const [msgs, setMsgs] = React.useState([
  { them: true, t: '10:32', text: 'Привет. Видел у тебя 3.5. Я в Хамовниках, ищу партнёра.' },
  { them: false, t: '10:34', text: 'Привет. Сыграем. Когда удобно?' },
  { them: true, t: '10:35', text: 'Сб 10:00 в Лужниках, корт 4. Я бронирую.' },
  { them: false, t: '10:36', text: 'Идёт. До встречи.' },
  { invite: true }]
  );
  const [draft, setDraft] = React.useState('');

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '8px 16px 12px', borderBottom: `1px solid ${SMASH.mist}`
      }}>
        <div onClick={() => nav('player', p.id)} style={{ padding: 4, color: SMASH.ink, cursor: 'pointer' }}>{Icon.back(24)}</div>
        <Avatar name={p.name} size={36} tone={p.tone || 'green'} />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 15, fontWeight: 500, color: SMASH.black }}>{p.name}</div>
          <div style={{ fontSize: 11.5, color: SMASH.slate, fontFamily: SMASH.fontMono }}>
            NTRP {p.ntrp} · {p.area}
          </div>
        </div>
        <div style={{ color: SMASH.ink, cursor: 'pointer' }}>{Icon.more(22)}</div>
      </div>

      <div style={{ flex: 1, padding: '14px 16px', display: 'flex', flexDirection: 'column', gap: 10, overflowY: 'auto' }}>
        {msgs.map((m, i) => m.invite ?
        <div key={i} style={{ alignSelf: 'stretch', margin: '4px 0' }}>
            <MatchInviteTile when="Сб · 10:00" where="Лужники · корт №4" duration="90 мин" status="confirmed" />
          </div> :

        <Bubble key={i} them={m.them} time={m.t}>{m.text}</Bubble>
        )}
      </div>

      <div style={{
        padding: '10px 12px 14px', borderTop: `1px solid ${SMASH.mist}`,
        display: 'flex', gap: 8, alignItems: 'center'
      }}>
        <div style={{
          width: 38, height: 38, borderRadius: 12,
          background: SMASH.cream, color: SMASH.ink,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer'
        }}>{Icon.plus(22)}</div>
        <input value={draft} onChange={(e) => setDraft(e.target.value)}
        placeholder="Напиши сообщение"
        style={{
          flex: 1, border: `1px solid ${SMASH.mist}`,
          background: SMASH.off, borderRadius: 22,
          padding: '10px 14px', fontSize: 14,
          fontFamily: SMASH.fontBody, outline: 'none', color: SMASH.black
        }} />
        <div onClick={() => {
          if (draft.trim()) {
            setMsgs([...msgs, { them: false, t: '10:42', text: draft }]);
            setDraft('');
          }
        }} style={{
          width: 38, height: 38, borderRadius: 12,
          background: SMASH.green, color: SMASH.yellow,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer'
        }}>{Icon.send(20)}</div>
      </div>
    </div>);

}

// ──────────────────────────────────────────────────────────────────────────
// Record Match
// ──────────────────────────────────────────────────────────────────────────
function RecordMatchScreen({ nav, playerId }) {
  const p = PLAYERS.find((x) => x.id === playerId) || PLAYERS[0];
  const [sets, setSets] = React.useState([[6, 4], [6, 3], [null, null]]);
  const [winner, setWinner] = React.useState(0); // 0 = me

  return (
    <div>
      <AppHeader
        title="Запись матча"
        left={<div onClick={() => nav('discover')}>{Icon.back(24)}</div>} />
      

      {/* Players */}
      <div style={{ padding: '0 20px 16px' }}>
        <Card style={{ padding: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <Avatar name="Я" size={40} tone="green" />
            <div style={{ flex: 1, fontSize: 15, fontWeight: 500 }}>Ты</div>
            <NTRPBadge value="3.50" />
          </div>
          <div style={{ height: 1, background: SMASH.mist, margin: '12px 0' }} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <Avatar name={p.name} size={40} tone={p.tone || 'green'} />
            <div style={{ flex: 1, fontSize: 15, fontWeight: 500 }}>{p.name}</div>
            <NTRPBadge value={p.ntrp} />
          </div>
        </Card>
      </div>

      {/* Set grid */}
      <div style={{ padding: '0 20px' }}>
        <Label>Счёт по сетам</Label>
        <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div style={{ display: 'flex', gap: 8 }}>
            <div style={{ width: 88, alignSelf: 'center', fontSize: 13, color: SMASH.slate }}>Сет 1</div>
            <ScoreCell value={sets[0][0]} active={winner === 0} />
            <ScoreCell value={sets[0][1]} />
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <div style={{ width: 88, alignSelf: 'center', fontSize: 13, color: SMASH.slate }}>Сет 2</div>
            <ScoreCell value={sets[1][0]} active={winner === 0} />
            <ScoreCell value={sets[1][1]} />
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <div style={{ width: 88, alignSelf: 'center', fontSize: 13, color: SMASH.stone }}>Сет 3</div>
            <ScoreCell value="—" dim />
            <ScoreCell value="—" dim />
          </div>
        </div>
      </div>

      {/* Meta */}
      <div style={{ padding: '20px 20px 0' }}>
        <Label>Когда и где</Label>
        <div style={{ marginTop: 4 }}>
          <StatRow label="Дата" value="12 окт · Сб" mono />
          <StatRow label="Корт" value="Лужники · №4" />
          <StatRow label="Длительность" value="1 ч 42 мин" mono />
        </div>
      </div>

      {/* Rating preview */}
      <div style={{ padding: '20px 20px 0' }}>
        <Card style={{
          background: SMASH.yellow100, border: `1px solid ${SMASH.yellow}`,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between'
        }}>
          <div>
            <Label color={SMASH.green700}>После победы</Label>
            <div style={{
              fontFamily: SMASH.fontMono, fontSize: 28, fontWeight: 500,
              color: SMASH.green700, marginTop: 4, letterSpacing: '-0.5px'
            }}>3,50 → 3,65</div>
          </div>
          <div style={{
            fontFamily: SMASH.fontMono, fontSize: 18, fontWeight: 500,
            color: SMASH.green400
          }}>+0,15</div>
        </Card>
      </div>

      <div style={{ padding: '24px 20px 24px' }}>
        <Button kind="primary" full icon={Icon.check(20)} onClick={() => nav('discover')}>
          Записать результат
        </Button>
      </div>
    </div>);

}

// ──────────────────────────────────────────────────────────────────────────
// Welcome / NTRP result (onboarding)
// ──────────────────────────────────────────────────────────────────────────
function WelcomeScreen({ nav }) {
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: SMASH.green }}>
      <CourtBackdrop height={240} />
      <div style={{ flex: 1, padding: '0 24px 16px', display: 'flex', flexDirection: 'column', color: SMASH.off }}>
        <div style={{ marginTop: -110, marginBottom: 24 }}>
          <Wordmark size={96} color={SMASH.off} dot={SMASH.yellow} />
        </div>
        <div style={{
          fontFamily: SMASH.fontDisplay, fontWeight: 700, fontSize: 56,
          lineHeight: 0.95, letterSpacing: '-2px', color: SMASH.yellow
        }}>СЫГРАЙ<br />БОЛЬШЕ.</div>
        <div style={{ fontSize: 15, lineHeight: 1.5, color: SMASH.green200, marginTop: 18, maxWidth: 300 }}>
          Найди партнёра твоего уровня в Лужниках и Крылатском. Договорись о матче в 3 клика.
        </div>
        <div style={{ flex: 1 }} />
        <Button kind="accent" full onClick={() => nav('quiz')}>Начать</Button>
        <div style={{
          marginTop: 12, textAlign: 'center', fontSize: 13, color: SMASH.green200
        }}>У меня уже есть аккаунт</div>
      </div>
    </div>);

}

function NTRPQuizResult({ nav }) {
  return (
    <div>
      <AppHeader title="Твой уровень" left={<div onClick={() => nav('welcome')}>{Icon.back(24)}</div>} />
      <div style={{ padding: '20px 24px 0' }}>
        <div style={{ fontSize: 14, color: SMASH.slate, marginBottom: 14 }}>
          По 12 ответам мы оценили твой уровень. Можно скорректировать перед стартом.
        </div>

        <Card style={{
          background: SMASH.green, border: 'none', padding: 20, textAlign: 'center'
        }}>
          <Label color={SMASH.green200}>Стартовый NTRP</Label>
          <div style={{
            fontFamily: SMASH.fontMono, fontSize: 96, fontWeight: 500,
            color: SMASH.yellow, letterSpacing: '-3px', lineHeight: 1, marginTop: 12
          }}>3.5</div>
          <div style={{ marginTop: 10, fontSize: 13, color: SMASH.green200 }}>
            Уверенная подача, контролируемый длинный обмен ударами.
          </div>
        </Card>

        <div style={{ marginTop: 18, display: 'flex', gap: 10, justifyContent: 'center' }}>
          <Button kind="secondary" onClick={() => {}}>Ниже · 3.0</Button>
          <Button kind="secondary" onClick={() => {}}>Выше · 4.0</Button>
        </div>

        <div style={{ marginTop: 22 }}>
          <Label>Что дальше</Label>
          <StatRow label="Район" value="Хамовники" />
          <StatRow label="Когда играешь" value="Сб утром · Ср вечером" />
          <StatRow label="Тип матчей" value="Одиночный" />
        </div>
      </div>

      <div style={{ padding: '24px 20px 24px' }}>
        <Button kind="primary" full onClick={() => nav('discover')}>Перейти к партнёрам</Button>
      </div>
    </div>);

}

Object.assign(window, {
  DiscoverScreen, PlayerProfileScreen, ChatScreen, RecordMatchScreen,
  WelcomeScreen, NTRPQuizResult
});