// Login + Home screens

window.LoginScreen = function LoginScreen() {
  const { login, go } = useApp();
  const theme = useTheme();
  const [phone, setPhone] = useState('');
  const [pin, setPin] = useState('');
  const [err, setErr] = useState('');
  const [attempts, setAttempts] = useState(0);
  const [locked, setLocked] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  const formatPhone = (v) => {
    const d = v.replace(/\D/g, '').slice(0, 10);
    if (d.length < 4) return d;
    if (d.length < 7) return `${d.slice(0,3)}-${d.slice(3)}`;
    return `${d.slice(0,3)}-${d.slice(3,6)}-${d.slice(6)}`;
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    if (locked || submitting) return;
    setErr('');
    setSubmitting(true);
    try {
      const res = await login(phone, pin);
      if (!res.ok) {
        const n = attempts + 1;
        setAttempts(n);
        if (n >= 5) {
          setLocked(true);
          setErr('คุณพยายามเข้าเกินจำนวนครั้ง กรุณารอ 5 นาที');
        } else {
          setErr(res.error || 'เข้าสู่ระบบไม่สำเร็จ');
        }
      }
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <PhoneShell showBottomNav={false} bg="#FAF7F2">
      <div style={{ padding: '44px 28px 28px', minHeight: '100%', display: 'flex', flexDirection: 'column', fontFamily: "'Noto Sans Thai', sans-serif" }}>
        {/* Logo */}
        <div style={{ textAlign: 'center', marginTop: 28 }}>
          <div style={{
            width: 88, height: 88, borderRadius: 22, margin: '0 auto 14px',
            background: `linear-gradient(135deg, ${theme.accent}, ${theme.accentDark})`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: `0 10px 24px ${theme.accent}33`,
          }}>
            <div style={{ color: '#fff', fontSize: 40, fontWeight: 800, letterSpacing: -1 }}>฿</div>
          </div>
          <div style={{ fontSize: 24, fontWeight: 800, color: '#1A1A1A' }}>สุ่มเลข</div>
          <div style={{ fontSize: 13, color: '#8C8678', marginTop: 4 }}>แอปวิเคราะห์หวยด้วย AI เพื่อความบันเทิง</div>
        </div>

        <form onSubmit={onSubmit} style={{ marginTop: 36, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div>
            <label style={{ fontSize: 13, color: '#5A5546', fontWeight: 600, marginBottom: 6, display: 'block' }}>เบอร์โทรศัพท์</label>
            <input
              value={formatPhone(phone)}
              onChange={e => setPhone(e.target.value)}
              placeholder="0xx-xxx-xxxx"
              inputMode="numeric"
              autoComplete="tel"
              style={inputStyle}
            />
          </div>

          <div>
            <label style={{ fontSize: 13, color: '#5A5546', fontWeight: 600, marginBottom: 6, display: 'block' }}>รหัส PIN (6 หลัก)</label>
            <input
              type="password"
              value={pin}
              onChange={e => setPin(e.target.value.replace(/\D/g,'').slice(0, 6))}
              placeholder="••••••"
              inputMode="numeric"
              autoComplete="current-password"
              maxLength={6}
              style={{ ...inputStyle, letterSpacing: pin ? '0.4em' : 0 }}
            />
          </div>

          {err && (
            <div style={{ background: '#FEF2F2', color: '#B91C1C', padding: '10px 14px', borderRadius: 10, fontSize: 13, fontWeight: 500, border: '1px solid #FECACA' }}>
              {err}
            </div>
          )}

          <button type="submit" disabled={locked || submitting} style={{
            marginTop: 6, padding: '16px', borderRadius: 14,
            background: (locked || submitting) ? '#C4BEB0' : theme.accent, color: '#fff',
            border: 0, fontSize: 17, fontWeight: 700, cursor: (locked || submitting) ? 'not-allowed' : 'pointer',
            fontFamily: 'inherit',
            boxShadow: (locked || submitting) ? 'none' : `0 6px 16px ${theme.accent}33`,
          }}>
            {submitting ? 'กำลังเข้าสู่ระบบ...' : 'เข้าสู่ระบบ'}
          </button>

          <div style={{ textAlign: 'center', fontSize: 13, color: theme.accent, fontWeight: 600, marginTop: 4 }}>
            ต้องการสมัคร? ติดต่อผู้ดูแล
          </div>
        </form>

        <div style={{ marginTop: 'auto', background: '#F5F0E6', padding: 14, borderRadius: 12, fontSize: 12, color: '#7A7262', lineHeight: 1.6 }}>
          แอปนี้ต้องได้รับการเพิ่มเข้าระบบจากผู้ดูแลก่อนจึงจะใช้งานได้
        </div>
      </div>
    </PhoneShell>
  );
};

const inputStyle = {
  width: '100%', boxSizing: 'border-box',
  padding: '14px 16px', borderRadius: 12,
  border: '1.5px solid #E5DFD1', background: '#fff',
  fontSize: 17, fontFamily: 'inherit', color: '#1A1A1A',
  outline: 'none',
};

// ──────────────────────────────────────────────
// Home screen — list of lotteries
// ──────────────────────────────────────────────
window.HomeScreen = function HomeScreen() {
  const { user, go, tweaks } = useApp();
  const theme = useTheme();
  const domestic = MOCK_LOTTERIES.filter(l => l.group === 'ในประเทศ');
  const foreign = MOCK_LOTTERIES.filter(l => l.group === 'ต่างประเทศ');

  return (
    <PhoneShell>
      {/* Top header */}
      <div style={{ padding: '14px 20px 10px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{
          width: 38, height: 38, borderRadius: 11,
          background: `linear-gradient(135deg, ${theme.accent}, ${theme.accentDark})`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: '#fff', fontWeight: 800, fontSize: 20,
        }}>฿</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, color: '#8C8678' }}>ยินดีต้อนรับ</div>
          <div style={{ fontSize: 15, fontWeight: 700, color: '#1A1A1A' }}>{user?.name || 'ผู้ใช้'}</div>
        </div>
        <SpeakerBtn label="ฟังข่าว" />
        <button onClick={() => go('profile')} style={{
          width: 40, height: 40, borderRadius: 999, border: 0,
          background: `${theme.accent}15`, color: theme.accent, fontWeight: 800, fontSize: 15, cursor: 'pointer',
        }}>{user?.name?.[0] || '?'}</button>
      </div>

      {/* Hero banner */}
      <div style={{
        margin: '6px 20px 18px', padding: '18px 20px', borderRadius: 18,
        background: `linear-gradient(135deg, ${theme.accent} 0%, ${theme.accentDark} 100%)`,
        color: '#fff', position: 'relative', overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute', right: -30, top: -30, width: 130, height: 130, borderRadius: 999,
          background: `${theme.gold}33`,
        }} />
        <div style={{ position: 'absolute', right: 16, bottom: 14, width: 48, height: 48, borderRadius: 999, background: `${theme.gold}55`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22 }}>🏆</div>
        <div style={{ fontSize: 12, opacity: 0.85, fontWeight: 500, position: 'relative' }}>งวดนี้</div>
        <div style={{ fontSize: 20, fontWeight: 800, marginTop: 2, position: 'relative' }}>Top 5 เลขเด่น AI</div>
        <div style={{ fontSize: 13, opacity: 0.9, marginTop: 6, position: 'relative' }}>วิเคราะห์จากสถิติ 30 งวดหลัง</div>
      </div>

      <div className="home-sections-grid">
        <LotterySection title="หวยในประเทศ" items={domestic} />
        <LotterySection title="หวยต่างประเทศ" items={foreign} />
      </div>

      <div style={{ textAlign: 'center', padding: '14px 20px 28px', fontSize: 11, color: '#A39B87' }}>
        * เพื่อความบันเทิงเท่านั้น ไม่ใช่ระบบรับแทงพนัน
      </div>
    </PhoneShell>
  );
};

function LotterySection({ title, items }) {
  return (
    <div className="lottery-section-item" style={{ padding: '0 20px 8px' }}>
      <div style={{ fontSize: 14, fontWeight: 700, color: '#5A5546', margin: '8px 0 12px', letterSpacing: 0.2 }}>{title}</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {items.map(l => <LotteryCard key={l.slug} lot={l} />)}
      </div>
    </div>
  );
}

function LotteryCard({ lot }) {
  const { go, tweaks } = useApp();
  const theme = useTheme();
  const { text: cd, totalMs } = useCountdown(lot.close);
  const closed = totalMs < 5000 || !lot.aiEnabled;
  const variant = tweaks.cardStyle || 'full';

  if (variant === 'minimal') {
    return (
      <button onClick={() => go('lottery', { slug: lot.slug })} disabled={!lot.aiEnabled} style={{
        display: 'flex', alignItems: 'center', gap: 14,
        padding: '14px 16px', borderRadius: 14, border: '1px solid #EDE7DC',
        background: !lot.aiEnabled ? '#F5F0E6' : '#fff',
        textAlign: 'left', cursor: lot.aiEnabled ? 'pointer' : 'not-allowed',
        opacity: !lot.aiEnabled ? 0.55 : 1, fontFamily: 'inherit', width: '100%',
      }}>
        <div style={{ width: 6, height: 42, borderRadius: 3, background: lot.color }} />
        <div style={{ fontSize: 22 }}>{lot.flag}</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 15, fontWeight: 700, color: '#1A1A1A' }}>{lot.name}</div>
          <div style={{ fontSize: 12, color: '#8C8678', marginTop: 2 }}>ปิด {lot.close} น. • {lot.cadence}</div>
        </div>
        <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 14, fontWeight: 700, color: theme.accent }}>{cd}</div>
      </button>
    );
  }

  if (variant === 'icon') {
    return (
      <button onClick={() => go('lottery', { slug: lot.slug })} disabled={!lot.aiEnabled} style={{
        display: 'flex', alignItems: 'center', gap: 16,
        padding: '16px 18px', borderRadius: 18,
        background: `linear-gradient(135deg, ${lot.color} 0%, ${lot.color}CC 100%)`,
        border: 0, color: '#fff', textAlign: 'left', cursor: 'pointer', fontFamily: 'inherit',
        opacity: !lot.aiEnabled ? 0.5 : 1, width: '100%',
        boxShadow: `0 8px 20px ${lot.color}33`,
      }}>
        <div style={{ fontSize: 40, filter: 'drop-shadow(0 2px 4px rgba(0,0,0,0.2))' }}>{lot.flag}</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 17, fontWeight: 800 }}>{lot.name}</div>
          <div style={{ fontSize: 12, opacity: 0.85, marginTop: 2 }}>ปิดรับ {lot.close} น.</div>
        </div>
        <div style={{
          padding: '6px 12px', borderRadius: 999,
          background: 'rgba(255,255,255,0.22)', backdropFilter: 'blur(10px)',
          fontFamily: 'ui-monospace, monospace', fontSize: 13, fontWeight: 700,
        }}>{cd}</div>
      </button>
    );
  }

  // full card (default)
  return (
    <button onClick={() => go('lottery', { slug: lot.slug })} disabled={!lot.aiEnabled} style={{
      display: 'block', width: '100%', padding: 0, borderRadius: 16,
      background: !lot.aiEnabled ? '#F5F0E6' : '#fff',
      border: '1px solid #EDE7DC', overflow: 'hidden',
      textAlign: 'left', cursor: lot.aiEnabled ? 'pointer' : 'not-allowed',
      fontFamily: 'inherit', opacity: !lot.aiEnabled ? 0.6 : 1,
      boxShadow: '0 2px 8px rgba(90,85,70,0.05)',
    }}>
      <div style={{ height: 4, background: `linear-gradient(90deg, ${lot.color}, ${lot.color}88)` }} />
      <div style={{ padding: '14px 16px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{
            width: 44, height: 44, borderRadius: 12, background: `${lot.color}18`,
            display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24,
          }}>{lot.flag}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 16, fontWeight: 700, color: '#1A1A1A' }}>{lot.name}</div>
            <div style={{ fontSize: 12, color: '#8C8678', marginTop: 2 }}>ปิดรับ {lot.close} น. • {lot.cadence}</div>
          </div>
          {!lot.aiEnabled && (
            <div style={{ fontSize: 11, padding: '3px 8px', borderRadius: 6, background: '#E5DFD1', color: '#8C8678', fontWeight: 600 }}>ปิด AI</div>
          )}
        </div>
        <div style={{
          marginTop: 12, padding: '8px 12px', borderRadius: 10,
          background: closed ? '#F5F0E6' : `${theme.accent}0D`,
          display: 'flex', alignItems: 'center', gap: 8,
        }}>
          <IconClock color={closed ? '#8C8678' : theme.accent} />
          <div style={{ fontSize: 12, color: closed ? '#8C8678' : '#5A5546', fontWeight: 500 }}>
            {closed ? 'ปิดรับแล้ว' : 'เหลือเวลาอีก'}
          </div>
          <div style={{ marginLeft: 'auto', fontFamily: 'ui-monospace, monospace', fontSize: 15, fontWeight: 800, color: closed ? '#8C8678' : theme.accent }}>
            {cd}
          </div>
        </div>
      </div>
    </button>
  );
}
