/* Surgr App — AI Trainer Chat Screen
   Recreates surgr/app/trainer/page.js — chat thread, ice-breakers, composer. */

const {
  AppH1: TAppH1,
  PrimaryButton: TPrimaryButton,
  SectionLabel: TSectionLabel,
  PulseDot: TPulseDot,
  Icons: TIcons,
} = window.SurgrAppKit;

const { useState: tUseState, useRef: tUseRef, useEffect: tUseEffect } = React;

function MessageBubble({ from, children }) {
  if (from === 'user') {
    return (
      <div style={{
        alignSelf: 'flex-end',
        background: 'rgba(255,255,255,0.05)',
        border: '1px solid rgba(255,255,255,0.06)',
        borderRadius: '18px 4px 18px 18px',
        padding: '12px 16px',
        maxWidth: '80%',
        fontSize: 14,
        color: 'var(--surgr-text)',
        lineHeight: 1.55,
        fontFamily: 'var(--surgr-font-body)',
        fontWeight: 500,
      }}>{children}</div>
    );
  }
  return (
    <div style={{ alignSelf: 'flex-start', maxWidth: '85%' }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6,
        fontSize: 11, fontWeight: 800, letterSpacing: 2,
        textTransform: 'uppercase', color: 'var(--surgr-accent)',
        fontFamily: 'var(--surgr-font-body)',
      }}>
        <TPulseDot/>SURGR TREINADOR
      </div>
      <div style={{
        background: 'rgba(200,255,0,0.05)',
        border: '1px solid rgba(200,255,0,0.12)',
        borderRadius: '4px 18px 18px 18px',
        padding: '14px 18px',
        fontSize: 14,
        lineHeight: 1.6,
        color: 'var(--surgr-text)',
        fontFamily: 'var(--surgr-font-body)',
        fontWeight: 500,
      }}>{children}</div>
    </div>
  );
}

const ICE_BREAKERS = [
  'Como aumentar carga sem sair de 8–10 reps?',
  'Tô com dor no ombro lateral, o que faço?',
  'Substituir agachamento por hoje',
  'Avalia minha forma no peso morto',
];

function TrainerScreen({ onBack }) {
  const [msgs, setMsgs] = tUseState([
    { from: 'bot', text: 'E aí, atleta. Hoje é seu Pull Day. Bora treinar com inteligência ou tem dúvida em algo?' },
  ]);
  const [input, setInput] = tUseState('');
  const [typing, setTyping] = tUseState(false);
  const endRef = tUseRef(null);
  tUseEffect(() => { endRef.current?.scrollTo({ top: 99999 }); }, [msgs, typing]);

  const send = (text) => {
    if (!text.trim()) return;
    setMsgs(m => [...m, { from: 'user', text }]);
    setInput('');
    setTyping(true);
    setTimeout(() => {
      setTyping(false);
      setMsgs(m => [...m, { from: 'bot', text: 'Isso indica atrito subacromial. Faz a elevação no plano escapular, ~30° à frente da linha dos ombros. Ajustei seu treino no app.' }]);
    }, 1300);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      {/* Header */}
      <header style={{
        position: 'sticky', top: 0,
        background: 'rgba(10,10,15,0.85)',
        backdropFilter: 'blur(10px)',
        WebkitBackdropFilter: 'blur(10px)',
        borderBottom: '1px solid var(--surgr-border)',
        padding: '14px 20px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        zIndex: 10,
      }}>
        <button onClick={onBack} style={{ background: 'none', border: 'none', color: 'var(--surgr-text)', display: 'flex', alignItems: 'center', cursor: 'pointer', padding: 0 }}>
          <TIcons.ArrowLeft size={20}/>
        </button>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontFamily: 'var(--surgr-font-heading)', fontWeight: 700, fontSize: 16, letterSpacing: 1.5, textTransform: 'uppercase', color: 'var(--surgr-text-strong)' }}>TREINADOR</div>
          <div style={{ fontSize: 10, color: 'var(--surgr-accent)', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, fontFamily: 'var(--surgr-font-body)', fontWeight: 700, letterSpacing: 1 }}>
            <span style={{ width: 6, height: 6, borderRadius: 3, background: 'var(--surgr-accent)', boxShadow: '0 0 6px var(--surgr-accent)' }}/>online
          </div>
        </div>
        <div style={{ width: 24 }}/>
      </header>

      {/* Messages */}
      <div ref={endRef} style={{
        flex: 1,
        overflowY: 'auto',
        padding: '20px 18px',
        display: 'flex',
        flexDirection: 'column',
        gap: 16,
      }}>
        {msgs.map((m, i) => <MessageBubble key={i} from={m.from}>{m.text}</MessageBubble>)}
        {typing && (
          <div style={{ alignSelf: 'flex-start', display: 'flex', gap: 6, padding: '12px 16px', background: 'rgba(200,255,0,0.05)', border: '1px solid rgba(200,255,0,0.12)', borderRadius: '4px 18px 18px 18px' }}>
            {[0,1,2].map(i => <span key={i} style={{ width: 6, height: 6, borderRadius: 3, background: 'var(--surgr-accent)', animation: `surgr-typing 1.2s ${i*0.15}s ease-in-out infinite` }}/>)}
          </div>
        )}

        {msgs.length === 1 && (
          <div style={{ marginTop: 8, display: 'flex', flexDirection: 'column', gap: 8 }}>
            <TSectionLabel style={{ marginBottom: 4 }}>SUGESTÕES</TSectionLabel>
            {ICE_BREAKERS.map(q => (
              <button key={q} onClick={() => send(q)} style={{
                textAlign: 'left',
                background: 'transparent',
                border: '1px solid var(--surgr-border)',
                borderRadius: 12,
                padding: '12px 14px',
                color: 'var(--surgr-text-muted)',
                fontSize: 13,
                cursor: 'pointer',
                fontFamily: 'var(--surgr-font-body)',
                fontWeight: 500,
                lineHeight: 1.4,
                transition: 'border-color var(--surgr-dur-fast)',
              }}
              onMouseEnter={e => e.currentTarget.style.borderColor = 'rgba(200,255,0,0.3)'}
              onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--surgr-border)'}
              >{q}</button>
            ))}
          </div>
        )}
      </div>

      {/* Composer */}
      <div style={{
        padding: '12px 16px 20px',
        borderTop: '1px solid var(--surgr-border)',
        background: 'var(--surgr-bg)',
      }}>
        <form onSubmit={(e) => { e.preventDefault(); send(input); }} style={{
          display: 'flex',
          alignItems: 'center',
          gap: 8,
          background: 'rgba(255,255,255,0.04)',
          border: '1px solid var(--surgr-border)',
          borderRadius: 14,
          padding: '8px 8px 8px 14px',
        }}>
          <button type="button" style={{ background: 'none', border: 'none', color: 'var(--surgr-text-muted)', display: 'flex', cursor: 'pointer', padding: 4 }}>
            <TIcons.Camera size={20}/>
          </button>
          <input
            value={input}
            onChange={e => setInput(e.target.value)}
            placeholder="Pergunta pro treinador…"
            style={{
              flex: 1,
              background: 'transparent',
              border: 'none',
              color: 'var(--surgr-text)',
              fontFamily: 'var(--surgr-font-body)',
              fontSize: 14,
              outline: 'none',
              padding: '8px 0',
            }}
          />
          <button type="submit" disabled={!input.trim()} style={{
            background: input.trim() ? 'var(--surgr-accent)' : 'rgba(200,255,0,0.2)',
            color: '#000',
            border: 'none',
            borderRadius: 10,
            width: 36, height: 36,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: input.trim() ? 'pointer' : 'not-allowed',
            transition: 'background var(--surgr-dur-fast)',
          }}>
            <TIcons.Send size={16}/>
          </button>
        </form>
      </div>
    </div>
  );
}

window.SurgrAppKit.TrainerScreen = TrainerScreen;
